<template>
  <div class="l-layout">
    <v-row ref="searchFilter">
      <v-col :cols="12">
        <v-card class="searchFilter">
          <v-row align="center" no-gutters>
            <v-col :cols="3">
              <!-- 설비종류 -->
              <component
                :is="'SelectBox'"
                ref="SelectBox1"
                :propsValue="selectValue01"
                :itemList="selectValueList01"
                :label="'설비종류'"
                :labelCols="12"
                :textCols="12"
                :iconShow="true"
                :customClass="'select-large'"
                @update:propsValue="selectValue01 = $event"
              />
            </v-col>

            <v-col :cols="3">
              <!-- 대상일 -->
              <component
                :is="'Datepicker'"
                :parentPrgmId="myPrgmId"
                :customClass="'select-large'"
                :label="'대상일'"
                :labelCols="3"
              />
            </v-col>
            <v-col :cols="6" class="text-right">
              <!-- 조회버튼 -->
              <BtnSearch style="margin-top: 20px" size="large" @click="search" />
            </v-col>
          </v-row>
        </v-card>
      </v-col>
    </v-row>
    <v-row style="height: 700px">
      <v-col
        :cols="6"
        v-for="(item, index) in selectData"
        :key="item.eqpmGrpId"
        style="height: 50vh"
      >
        <!-- <v-card class="pa-5" @click="barClick($event,'card')"> -->
        <v-card class="pa-5">
          <div class="d-flex align-center justify-space-between">
            <v-card-title class="pa-0">{{ item.eqpmGrpNm }}</v-card-title>
          </div>
          <div ref="chartParent" style="height: 90%">
            <component
              :id="chartNameList[index]"
              class="w100 h100 totChart"
              :is="loadChartList[index] ? 'Chart' : null"
              :parentPrgmId="myPrgmId"
              :chartName="chartNameList[index]"
              :ref="chartNameList[index]"
              @click="barClick($event, chartNameList[index])"
            />
          </div>
        </v-card>
      </v-col>
      <!-- <v-col :cols="12" style="height: 35%">
              <v-card class="pa-5">
                <div ref="gridParent">
                    <component
                        ref="grid_01"
                        :is="loadGrid_01 ? 'Grid' : null"
                        :gridName="grid_01"
                        :parentPrgmId="myPrgmId"
                    />
                </div>
              </v-card>
          </v-col> -->
    </v-row>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";
import vue from "vue";
import mixinGlobal from "@/mixin/global.js";
import { resize } from "@/mixin/resize.js";
import Datepicker from "~/components/common/Datepicker";
import Grid from "~/components/common/Grid";
import SelectBox from "@/components/common/select/SelectBox";
import BtnSearch from "~/components/common/button/BtnSearch";
import Buttons from "~/components/common/button/Buttons";
import Utility from "~/plugins/utility";
import Chart from "~/components/common/Chart";
let myTitle;
let myPrgmId;

export default {
  mixins: [mixinGlobal, resize],
  async asyncData(context) {
    const myState = context.store.state;
    myPrgmId = context.route.query.prgmId;
    console.log("active menu:", myState.menuData);
    await context.store.commit("setActiveMenuInfo", myState.menuData[myPrgmId]);
    myTitle = await myState.activeMenuInfo.menuNm;
  },
  meta: {
    title: () => {
      return myTitle;
    },
    prgmId: myPrgmId,
    closable: true,
  },
  components: {
    Datepicker,
    Grid,
    SelectBox,
    BtnSearch,
    Buttons,
    Utility,
    Chart,
  },
  data() {
    return {
      myPrgmId: myPrgmId,
      selectValue01: null,
      selectValueList01: [],
      loadChartList: [],
      chartNameList: [],
      selectData: [],
      url: "",
      objList: {},
    };
  },
  computed: {
    chkIsFind() {
      // 조회 플래그
      return this.pageData.isFind;
    },
    fromDt() {
      return this.pageData.fromDt;
    },
  },
  watch: {
    chkIsFind(val) {
      if (val) this.search();
    },
    selectValue01(val) {
      this.chartNameList = [];
      this.search();
    },
    fromDt(val) {
      this.chartNameList = [];
    },
  },
  async beforeCreate() {
    myPrgmId = this.$route.query.prgmId;
    await this.$store.dispatch("chkOpenTabList", {
      key: "create",
      prgmId: myPrgmId,
      defaultData: defaultData,
    });
  },
  created() {},
  async mounted() {
    await this.init();

    // document.getElementById('totChart').on('click', function(params){

    // });
  },
  beforeDestroy() {
    this.chkOpenTabList({ key: "destroy", prgmId: myPrgmId });
  },
  methods: {
    ...mapMutations({
      setChartOption: "setChartOption",
      setPageData: "setPageData",
    }),
    ...mapActions({
      getCodeList: "modules/search/getCodeList",
      getBlocMstrList: "modules/search/getBlocMstrList",
      getAddInfoList: "modules/search/getAddInfoList",
    }),
    async init() {
      await this.getEqpmKind();
      await this.getData();
      // await this.getChartData();
      // await this.setChartData(data);
    },
    async search() {
      // this.getRowGridData();
      await this.getData();
      this.setPageData({
        isFind: false,
      });
    },
    async getEqpmKind() {
			let res = await this.postApiReturn({
				apiKey: 'selectEqpmKindCodeList',
				resKey: 'eqpmKindCodeLists',
				sendParam: {},
			});

			if (res.length > 0) {
				this.selectValueList01 = await res.map(item => {
					return {
						text: item.eqpmKindNm,
						value: item.eqpmKindId,
					};
				});
				this.selectValue01 = this.selectValueList01[0].value;
			} else {
				this.selectValueList01 = [];
				this.selectValue01 = null;
			}
			this.setPageData({
				eqpmKindList: this.selectValueList01,
				eqpmKindId: this.selectValue01,
			});
		},
    gridInit() {},
    getRowGridData() {},
    async getData() {
			let res = await this.postApiReturn({
				apiKey: 'selectEnrgEffcTotSumm',
				resKey: 'totSummData',
				sendParam: {
					fromDt: this.pageData.fromDt,
					eqpmKindId: this.selectValue01,
				},
			});

			await this.getChartData(res);

			this.selectData = res.filter((item, i) => {
				return (
					res.findIndex((item2, j) => {
						return item.eqpmGrpId === item2.eqpmGrpId;
					}) === i
				);
			});
		},
    barClick(event, chartName) {
      var data = {};
      if (chartName == "card") {
        data.fromDt = null;
        data.eqpmGrpId = null;
        data.eqpmGrpNm = null;
        data.fabId = null;
        data.fabNm = null;
        data.okFg = null;
        data.eqpmKindNm = null;
      } else {
        var chartData = this.objList[chartName];
        data.fromDt = this.pageData.fromDt;
        data.eqpmGrpId = chartData[event.dataIndex].eqpmGrpId;
        data.eqpmGrpNm = chartData[event.dataIndex].eqpmGrpNm;
        data.fabId = chartData[event.dataIndex].fabId;
        data.fabNm = chartData[event.dataIndex].fabNm;
        data.okFg = event.seriesName;
        data.eqpmKindId = this.selectValue01;
      }

      this.$router.push({
        name: "ems-effc-EnrgEffcEqpmDetlMntrPage",
        params: {
          ...data,
          key: "data_" + Math.random(),
        },
        query: {
          prgmId: "PRG0084",
          // key : "data_"+Math.random()
        },
      });
    },
    async getChartData(data) {
			var chartDataObj = {};
			this.objList = {};
			// let res = await this.postApiReturn({
			//   apiKey : 'selectEnrgEffcTotSumm',
			//   resKey : 'totSummData',
			//   sendParam:{
			//     fromDt  : this.pageData.fromDt,
			//     eqpmKindId : this.pageData.eqpmKindId,
			//   }
			// });

			data.map(item => {
				if (chartDataObj[item.eqpmGrpId] != null) {
					chartDataObj[item.eqpmGrpId].push(item);
				} else {
					chartDataObj[item.eqpmGrpId] = [item];
				}
			});

			// chartDataObj.keys()[0]
			var i = 0;
			for (var x of Object.keys(chartDataObj)) {
				this.loadChartList.push(false);
				i++;
				this.objList['chart_0' + i] = chartDataObj[x];
				this.chartNameList.push('chart_0' + i);
				this.setPageData({
					[this.chartNameList[i - 1]]: Utility.defaultChartOption(true),
				});

				this.setChartData(chartDataObj[x], i);
			}
			// this.setChartData(chartDataObj[Object.keys(chartDataObj)[0]]);
		},
    async setChartData(data, number) {
      this.loadChartList[number - 1] = false;
      let xAxisData = [];
      let seriesData = [];
      var emphasisStyle = {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: "rgba(0,0,0,0.3)",
        },
      };

      console.log("data : ", data);
      data.map((item) => {
        xAxisData.push(item.fabNm);
      });

      seriesData.push({
        name: "OK",
        type: "bar",
        stack: "one",
        barWidth: "40",
        emphasis: emphasisStyle,
        data: data.map((obj) => obj["okCnt"]),
      });
      seriesData.push({
        name: "NG",
        type: "bar",
        stack: "one",
        barWidth: "40",
        emphasis: emphasisStyle,
        data: data.map((obj) => obj["ngCnt"]),
      });

      var dataZoom = [];
      if (xAxisData.length > 7) {
        dataZoom = [
          {
            type: "inside",
            disabled: false,
            start: 0,
            end: parseInt(700 / xAxisData.length) - 1,
          },
          {
            show: true,
            moveOnMouseMove: true,
            start: 0,
            end: parseInt(700 / xAxisData.length) - 1,
          },
        ];
      } else {
        dataZoom = [
          {
            type: "inside",
            disabled: true,
            start: 0,
            end: parseInt(700 / xAxisData.length) - 1,
          },
          {
            show: false,
            moveOnMouseMove: false,
            start: 0,
            end: parseInt(700 / xAxisData.length) - 1,
          },
        ];
      }

      // console.log("xAxisData : ", xAxisData);
      console.log("seriesData : ", seriesData);
      var chartOption = {
        legend: {
          top: xAxisData.length > 7 ? "top" : "bottom",
        },
        grid: {
          top: "10%",
          bottom: "16%",
        },
        yAxis: {},
        xAxis: {
          data: xAxisData,
        },
        series: seriesData,
        tooltip: {},
        dataZoom: dataZoom,
      };

      await this.$nextTick();
      this.setChartOption({
        chartKey: this.chartNameList[number - 1],
        value: chartOption,
      });
      this.loadChartList[number - 1] = true;
    },
  },
};

const defaultData = {
  isFind: false,
  eqpmKindList: [],
  eqpmKindId: "",
  cmCycle: "CYC_DAY", // 주기
  defaultRange: {
    CYC_DAY: 0,
  },
  fromDt: Utility.setFormatDate(new Date(), "YYYYMMDD"), // 조회 시작일
};
</script>
<style lang="scss" scoped>
// @import "@/assets/scss/common.scss";

// .echarts::v-deep > div > canvas:hover {
//     cursor: pointer;
// }
// ::v-deep{
// 	.echarts:hover > div:nth-child(1){
// 		cursor:pointer !important;
// 	}
// }
</style>
