<template>
  <div ref="mainDiv" class="l-layout">
    <!-- <h1 class="h1-title">
      <v-avatar size="12" :style="{ backgroundColor: 'currentColor' }"></v-avatar>
      에너지 사용량 실적
    </h1> -->
    <CommonPageTitle />
    <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="'FAB'"
                :labelCols="12"
                :textCols="12"
                :iconShow="true"
                :customClass="'select-large'"
                @update:propsValue="selectValue01 = $event"
              />
            </v-col>
            <v-col :cols="3">
              <component
                :is="'SelectBox'"
                ref="SelectBox2"
                :propsValue="selectValue02"
                :itemList="selectValueList02"
                :label="'설비종류'"
                :labelCols="12"
                :textCols="12"
                :customClass="'select-large'"
                :iconShow="true"
                @update:propsValue="selectValue02 = $event"
              />
            </v-col>
            <v-col :cols="3">
              <component
                :is="'SelectBox'"
                ref="SelectBox3"
                :propsValue="selectValue03"
                :itemList="selectValueList03"
                :label="'설비그룹'"
                :labelCols="12"
                :textCols="12"
                :customClass="'select-large'"
                :iconShow="true"
                @update:propsValue="selectValue03 = $event"
              />
            </v-col>

            <v-col :cols="3">
              <component
                :is="'SelectCmCycle'"
                :parentPrgmId="myPrgmId"
                :label="'구분'"
                :labelCols="12"
                :textCols="12"
                :customClass="'select-large'"
                :iconShow="true"
              />
            </v-col>
          </v-row>
          <v-row align="center" no-gutters>
            <v-col :cols="3">
              <component
                :is="'DatePicker'"
                :label="'대상년월'"
                :parentPrgmId="myPrgmId"
                :isRangeOption="false"
                :customClass="'datepicker-large'"
              />
            </v-col>
            <v-col :cols="6"> </v-col>
            <v-col :cols="3" class="text-right">
              <div style="height: 26px"></div>
              <!-- <v-btn :ripple="false" @click="search()">조회</v-btn> -->
              <a-button
                icon="search"
                type="primary"
                @click="search()"
                class="search-button"
                size="large"
                >조회</a-button
              >
            </v-col>
          </v-row>
        </v-card>
      </v-col>
    </v-row>
    <v-row ref="contents" style="height: calc(100vh - 230px)">
      <v-col :cols="12" class="h100">
        <v-card class="pb-5 px-2">
          <v-card-title class="d-flex align-center justify-space-between pa-5">
            <span class="tit ft-size_20 ft-weight_600">설비별 현황 리스트</span>
          </v-card-title>
          <div class="px-5" style="height: calc(100% - 56px)">
            <div ref="gridParent" class="w100 h100" style="height: calc(100% - 166px)">
              <component
                :ref="gridName"
                :is="loadGrid ? 'Grid' : null"
                :gridName="gridName"
                :parentPrgmId="myPrgmId"
              />
              <div v-if="loadGrid && totalCount > 0" class="pagination-wrapper">
                <pagination
                  id="pagination"
                  :total-count="totalCount"
                  :page-num="page"
                  :limit="limit"
                  :itemsPerPageArray="itemsPerPageArray"
                  @loadData="changeGrid"
                />
              </div>
              <!--
							<component
								:ref="gridName"
								:is="loadGrid ? 'Grid' : null"
								:gridName="gridName"
								:parentPrgmId="myPrgmId"
								:mouseoverEvent="gridMouseoverEvent"
								:mouseoutEvent="gridMouseoutEvent"
								@dblClick="gridDoubleClickEvent"
							/>
							-->
            </div>
          </div>
        </v-card>
      </v-col>
    </v-row>
    <!--<v-tooltip
			top
			v-model="tooltipData.show"
			:position-x="tooltipData.x" 
			:position-y="tooltipData.y"
			:z-index="1000"
		>
		{{tooltipData.content}}
		</v-tooltip> -->
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import mixinGlobal from "@/mixin/global.js";
import { resize } from "@/mixin/resize.js";
import Utility from "~/plugins/utility";
import SelectBox from "@/components/common/select/SelectBox";
import SelectCmCycle from "@/components/common/select/SelectCmCycle";
import DatePicker from "@/components/common/Datepicker";
import Grid from "~/components/common/Grid";
import pagination from "~/components/common/Pagination";

let myTitle;
let myPrgmId;
let paramKey;

export default {
  mixins: [mixinGlobal, resize],
  async asyncData(context) {
    const myState = context.store.state;
    myPrgmId = context.route.query.prgmId;
    await context.store.commit("setActiveMenuInfo", myState.menuData[myPrgmId]);
    myTitle = await myState.activeMenuInfo.menuNm;
  },
  meta: {
    title: () => {
      return myTitle;
    },
    prgmId: myPrgmId,
    closable: true,
  },
  components: {
    Utility,
    SelectBox,
    SelectCmCycle,
    DatePicker,
    Grid,
    pagination,
  },
  data() {
    return {
      myPrgmId: myPrgmId,

      initedFlag: false,
      queryParams: null,

      selectValueList01: [],
      selectValueList02: [],
      selectValueList03: [],

      selectValue01: null,
      selectValue02: null,
      selectValue03: null,

      loadGrid: false,
      gridName: "grid01",

      enrgUseMainIdxDesc: [],
      itemsPerPageArray: [10, 20, 50],
      limit: 10,
      page: 1,
      totalCount: 0,

      // tooltipData: {
      // 	show: false,
      // 	x: 0,
      // 	y: 0,
      // 	content: null,
      // },
      // tooltipTranscationFlag: false,
    };
  },
  computed: {
    ...mapState({
      pageData: (state) => state.pageData[myPrgmId],
      isDarkMode: "isDarkMode",
    }),
    fromDt() {
      return this.pageData.fromDt;
    },
  },
  watch: {
    async $route(to, from) {
      if (to.query.prgmId == myPrgmId) {
        if (to.params.key) {
          document.getElementById("refresh").click();
        }
      }
    },
    async selectValue01(value) {
      if (this.initedFlag) {
        await this.search();
      }
    },
    async selectValue02(value) {
      if (this.initedFlag) {
        await this.getSelectValueList03();
      }
    },
    async selectValue03(value) {
      if (this.initedFlag) {
        await this.search();
      }
    },
    async fromDt(value) {
      if (this.initedFlag) {
        await this.search();
      }
    },
    isDarkMode(newVal) {
      // Switch mode for 10 tooltips
      for (let i = 0; i < 10; i++) {
        const tooltipEl = document.getElementById(`tooltipElement_${i}`);
        if (tooltipEl) {
          tooltipEl.classList.remove("light-mode", "dark-mode");
          tooltipEl.classList.add(newVal ? "dark-mode" : "light-mode");
        }
      }
    },
  },
  async beforeCreate() {
    myPrgmId = this.$route.query.prgmId;
    await this.$store.dispatch("chkOpenTabList", {
      key: "create",
      prgmId: myPrgmId,
      defaultData: defaultData,
    });
  },
  created() {},
  mounted() {
    this.init();
  },
  beforeDestroy() {
    this.initedFlag = false;
    this.chkOpenTabList({ key: "destroy", prgmId: myPrgmId });
  },
  methods: {
    changeGrid: async function (pageNum, limit) {
      this.page = pageNum;
      this.limit = limit;
      this.getGridData(true);
    },
    async init() {
      await this.getSelectValueList();
      await this.setQueryParams();
      this.gridInit();
      await this.getGridData(false);

      this.initedFlag = true;
    },
    async setQueryParams() {
      this.queryParams = null;

      if (paramKey == this.$route.params.key) {
        return;
      }

      if (this.$route.params.key) {
        paramKey = this.$route.params.key;
        this.queryParams = this.$route.params;
      }

      if (this.queryParams && typeof this.queryParams == "object") {
        this.selectValue01 = this.queryParams["fabId"];
        this.selectValue02 = this.queryParams["eqpmKindId"];
        await this.getSelectValueList03();
        this.selectValue03 = this.queryParams["eqpmGrpId"];
      }
    },
    async getSelectValueList() {
      await this.getSelectValueList01();
      await this.getSelectValueList02();
      await this.getSelectValueList03();
    },
    async getSelectValueList01() {
      let res = await this.postApiReturn({
        apiKey: "selectFabCodeList",
        resKey: "fabCodeLists",
        sendParam: {},
      });
      if (res.length > 0) {
        this.selectValueList01 = await res.map((item) => {
          return {
            text: item.eccNm,
            value: item.eccId,
          };
        });
        this.selectValue01 = this.selectValueList01[0].value;
      } else {
        this.selectValueList01 = [];
        this.selectValue01 = null;
      }
    },
    async getSelectValueList02() {
      var res = await this.postApiReturn({
        apiKey: "selectEmsEqpmKindList",
        resKey: "eqpmGrpPysclQtyMngData",
        sendParam: {},
      });

      if (res.length > 0) {
        this.selectValueList02 = await res.map((item) => {
          return {
            text: item.eqpmKindNm,
            value: item.eqpmKindId,
            data: {
              ...item,
            },
          };
        });
        this.selectValue02 = this.selectValueList02[0].value;
      } else {
        this.selectValueList02 = [];
        this.selectValue02 = null;
      }
    },
    async getSelectValueList03() {
      var res = await this.postApiReturn({
        apiKey: "selectEmsEqpmGrpList",
        resKey: "eqpmGrpPysclQtyMngData",
        sendParam: {
          eqpmKindId: this.selectValue02,
        },
      });

      if (res.length > 0) {
        this.selectValueList03 = await res.map((item) => {
          return {
            text: item.eqpmGrpNm,
            value: item.eqpmGrpId,
            data: {
              ...item,
            },
          };
        });
        this.selectValue03 = this.selectValueList03[0].value;
      } else {
        this.selectValueList03 = [];
        this.selectValue03 = null;
      }
    },
    gridInit() {
      const gridHeight = this.$refs.gridParent.offsetHeight - 30;
      const _this = this;
      // Define custom button
      class CustomButton {
        constructor(props, pageData) {
          const { grid, rowKey, columnInfo } = props;
          const gridData = grid.store.data.rawData;
          const value = gridData[rowKey][columnInfo.name];
          const onClickCallback = columnInfo.renderer.options.onClick;

          this.disabled = columnInfo.renderer.options.disabled || false;
          const elDiv = document.createElement("div");
          elDiv.innerHTML = `<span>${value}</span>`;
          $(elDiv).addClass("tui-grid-cell-content d-flex justify-space-between");
          const el2 = document.createElement("button");
          $(el2).addClass("edit-btn blue--text");
          el2.innerText = "보기";
          elDiv.appendChild(el2);
          this.el = elDiv;
          if (!this.disabled && typeof onClickCallback === "function") {
            // click 이벤트
            this.el.addEventListener("click", function (event) {
              onClickCallback(rowKey);
            });
          }
        }
        getElement() {
          return this.el;
        }
        getValue() {
          // return this.el.value;
        }
        mounted() {
          // this.el.focus();
        }
      }

      var columnList = [
        { header: "NO", name: "no", align: "right", width: 80 },
        { header: "fabId", name: "fabId", hidden: true },
        { header: "FAB", name: "fabNm", align: "left" },
        { header: "eqpmGrpId", name: "eqpmGrpId", hidden: true },
        {
          header: "설비그룹",
          name: "eqpmGrpNm",
          align: "left",
          width: 200,
        },
        { header: "eqpmId", name: "eqpmId", hidden: true },
        { header: "설비명", name: "eqpmNm", align: "left", width: 200,
          // Render custom button to switch page instead of double click on row
          renderer: {
            type: CustomButton,
            options: {
              value: "보기",
              onClick: (rowKey) => {
                const gridInstance = this.$refs[this.gridName].gridInstance;
                const eventRowData = gridInstance.invoke("getRow", rowKey);

                const data = {
                  cmCycle: this.pageData.cmCycle,
                  fromDt: this.pageData.fromDt,
                  fabId: this.selectValue01,
                  eqpmKindId: this.selectValue02,
                  eqpmGrpId: this.selectValue03,
                  eqpmId: eventRowData.eqpmId,
                };
                const key = "tick_" + Math.random();
                this.$router.push({
                  name: "ems-effc-EnrgUseEqpmDetlMntrPage",
                  query: {
                    prgmId: "PRG0082",
                  },
                  params: {
                    ...data,
                    key: key,
                  },
                });
              },
            },
          },
        },
        {
          header: "계획량",
          name: "planVal",
          align: "right",
          minWidth: 110,
          formatter: numberFormatter,
        },
        {
          header: "사용량",
          name: "usedVal",
          align: "right",
          minWidth: 110,
          formatter: numberFormatter,
        },
        {
          header: "KPI",
          name: "effcRt",
          align: "right",
          formatter: numberFormatter,
        },
        {
          header: "지표1",
          name: "gd01",
          align: "right",
          formatter: numberFormatter,
        },
        {
          header: "지표2",
          name: "gd02",
          align: "right",
          formatter: numberFormatter,
        },
        {
          header: "지표3",
          name: "gd03",
          align: "right",
          formatter: numberFormatter,
        },
        {
          header: "지표4",
          name: "gd04",
          align: "right",
          formatter: numberFormatter,
        },
        {
          header: "지표5",
          name: "gd05",
          align: "right",
          formatter: numberFormatter,
        },
        {
          header: "지표6",
          name: "gd06",
          align: "right",
          formatter: numberFormatter,
        },
        {
          header: "지표7",
          name: "gd07",
          align: "right",
          formatter: numberFormatter,
        },
        {
          header: "지표8",
          name: "gd08",
          align: "right",
          formatter: numberFormatter,
        },
        {
          header: "지표9",
          name: "gd09",
          align: "right",
          formatter: numberFormatter,
        },
        {
          header: "지표10",
          name: "gd10",
          align: "right",
          formatter: numberFormatter,
        },
      ];
      const myOptions = {
        columnOptions: {
          resizable: true,
        },
        header: {
          height: 105,
          complexColumns: [
            {
              header: "주요지표",
              name: "complexColumn01",
              childNames: [
                "gd01",
                "gd02",
                "gd03",
                "gd04",
                "gd05",
                "gd06",
                "gd07",
                "gd08",
                "gd09",
                "gd10",
              ],
            },
          ],
        },
        // pageOptions: {
        //   useClient: true,
        //   perPage: 3,
        // }
      };

      this.setGridOption({
        gridKey: this.gridName,
        value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
      });

      this.setGridColumn({
        gridKey: this.gridName,
        value: columnList,
      });
    },
    async getGridData(isPaging) {
      if(!isPaging) {
        this.loadGrid = false;
      }
      this.enrgUseMainIdxDesc = [];
      var apiKey = null;
      var apiKey2 = null;
      var params = {
        fabId: this.selectValue01,
        eqpmKindId: this.selectValue02,
        eqpmGrpId: this.selectValue03,
        fromDt: this.pageData.fromDt,
        limit: this.limit,
        page: this.page,
        offset: (this.page - 1) * this.limit, // MariaDB Query에서 직접 계산이 안됨
      };

      if (this.pageData.cmCycle == "CYC_DAY") {
        params["fromDtMm"] = String(this.pageData.fromDt).substring(0, 6);
        apiKey = "selectDailyEnrgUseMainIdx";
        apiKey2 = "selectDailyEnrgUseMainIdxPageTotal";
      } else if (this.pageData.cmCycle == "CYC_MONTH") {
        apiKey = "selectMonthlyEnrgUseMainIdx";
        apiKey2 = "selectMonthlyEnrgUseMainIdxPageTotal";
      }

      
      var [res, res2] = await Promise.all([
        this.postApiReturn({
          apiKey: apiKey,
          resKey: "eqpmIndMntrData",
          sendParam: params,
        }),
        this.postApiReturn({
          apiKey: apiKey2,
          resKey: "eqpmIndMntrPageTotal",
          sendParam: params,
        }),
      ]);

      // var res = await this.postApiReturn({
      //   apiKey: apiKey,
      //   resKey: "eqpmIndMntrData",
      //   sendParam: params,
      // });

      // var res2 = await this.postApiReturn({
      //   apiKey: apiKey2,
      //   resKey: "eqpmIndMntrPageTotal",
      //   sendParam: params,
      // });

      this.totalCount = res2[0].totalcount;
      this.enrgUseMainIdxDesc = await this.postApiReturn({
        apiKey: "selectEnrgUseMainIdxDesc",
        resKey: "eqpmIndMntrData",
        sendParam: {
          eqpmGrpId: this.selectValue03,
        },
      });

      var newRes = [];
      for (var i = 0; i < res.length; i++) {
        newRes.push({
          ...res[i],
          no: i + 1,
        });
      }
      this.setGridData({
        gridKey: this.gridName,
        value: newRes,
      });

      this.loadGrid = true;
      this.makeTooltip();
    },
    async search() {
      await this.getGridData(false);
    },
    async makeTooltip() {
      var gdIdxList = [
        "gd01",
        "gd02",
        "gd03",
        "gd04",
        "gd05",
        "gd06",
        "gd07",
        "gd08",
        "gd09",
        "gd10",
      ];
      var elementList = [];

      await new Promise((resolve) => setTimeout(resolve, 1000));

      for (var i = 0; i < gdIdxList.length; i++) {
        var selector = '.tui-grid-cell-header[data-column-name="' + gdIdxList[i] + '"]';
        var tempElement = document.querySelector(selector);
        elementList.push(tempElement);
      }

      console.log("this.enrgUseMainIdxDesc : ", this.enrgUseMainIdxDesc);

      for (var i = 0; i < elementList.length; i++) {
        var tooltipElement = document.createElement("div");
        var tooltipContent = "";
        if (this.enrgUseMainIdxDesc[i]) {
          tooltipContent = this.enrgUseMainIdxDesc[i].gdIdxNm;
        } else {
          tooltipContent = "지표에 대한 정보가 없습니다.";
        }

        // textContent 세팅
        tooltipElement.textContent = tooltipContent;

        // id값 설정
        elementList[i].id = "tooltipTargetElement_" + i;
        tooltipElement.id = "tooltipElement_" + i;
        tooltipElement.classList.add(this.isDarkmode ? "dark-mode" : "light-mode");
        // element 추가
        elementList[i].append(tooltipElement);
      }
    },
    // gridMouseoverEvent(e) {
    // 	if (e.targetType == 'columnHeader') {
    // 		if (String(e.columnName).search('gd') >= 0) {
    // 			this.tooltipTranscationFlag = true;

    // 			this.tooltipData.content = null;
    // 			var element = document.querySelector(
    // 				'.tui-grid-cell-header[data-column-name="' + e.columnName + '"]',
    // 			);
    // 			var boundingClientRect = element.getBoundingClientRect();

    // 			this.tooltipData.x =
    // 				(boundingClientRect.right + boundingClientRect.left) / 2;
    // 			this.tooltipData.y = boundingClientRect.top;

    // 			for (var i = 0; i < this.enrgUseMainIdxDesc.length; i++) {
    // 				if (
    // 					this.enrgUseMainIdxDesc[i].gdSeq ==
    // 					String(e.columnName).toUpperCase()
    // 				) {
    // 					this.tooltipData.content = this.enrgUseMainIdxDesc[i].gdIdxNm;
    // 				}
    // 			}

    // 			if (this.tooltipData.content == null) {
    // 				this.tooltipData.content = '지표에 대한 정보가 없습니다.';
    // 			}

    // 			this.tooltipData.show = true;
    // 			this.tooltipTranscationFlag = false;
    // 		}
    // 	}
    // },
    // gridMouseoutEvent(e) {
    // 	if (
    // 		e.targetType == 'columnHeader' &&
    // 		this.tooltipTranscationFlag === false
    // 	) {
    // 		this.tooltipData.show = false;
    // 	}
    // },
    gridDoubleClickEvent(_, event, gridName) {
      var gridInstance = this.$refs[this.gridName].gridInstance;
      var eventRowData = gridInstance.invoke("getRow", event.rowKey);

      var data = {
        cmCycle: this.pageData.cmCycle,
        fromDt: this.pageData.fromDt,
        fabId: this.selectValue01,
        eqpmKindId: this.selectValue02,
        eqpmGrpId: this.selectValue03,
        eqpmId: eventRowData.eqpmId,
      };
      var key = "tick_" + Math.random();
      this.$router.push({
        name: "ems-effc-EnrgUseEqpmDetlMntrPage",
        query: {
          prgmId: "PRG0082",
          // tick:key
        },
        params: {
          ...data,
          key: key,
        },
      });
    },
  },
};

const defaultData = {
  cmCycle: "CYC_MONTH",
  cmCycleList: [
    { idx: 0, text: "월", value: "CYC_MONTH" },
    { idx: 1, text: "일", value: "CYC_DAY" },
  ],
  defaultRange: {
    CYC_MONTH: 1,
    CYC_DAY: 1,
  },
  fromDt: Utility.setFormatDate(new Date(), "YYYYMM"), // 조회 시작일
  grid01: {
    data: [],
    column: [],
    option: {},
  },
};

function numberFormatter({ value }) {
  if (typeof value == "number" || typeof value == "string") {
    // return Math.round(Number(value) * 100) / 100;
    // return Utility.setFormatIntDecimal(Number(value), 2);
    // return Math.ceil(Number(value));

    var tempValue = Utility.setFormatIntDecimal(Number(value), 2);

    if (tempValue[tempValue.length - 1] == "0") {
      tempValue = tempValue.slice(0, -1);
    }
    if (
      tempValue[tempValue.length - 1] == "0" &&
      tempValue[tempValue.length - 2] == "."
    ) {
      tempValue = tempValue.slice(0, -2);
    }

    return tempValue;
  } else {
    return "";
  }
}
</script>
<style lang="scss" scoped>
::v-deep {
  @for $i from 0 through 9 {
    #gridParent > * {
      // .tui-grid-content-area{
      background-color: red;
      color: red;
      overflow: visible;
      position: relative;
    }
    #tooltipTargetElement_#{$i} {
      overflow: visible;
      position: relative; // 테스트3번쨰
      white-space: nowrap; // 테스트3번쨰
    }
    #tooltipElement_#{$i} {
      display: none;
      overflow: visible;
      position: relative;
    }
    #tooltipTargetElement_#{$i}:hover #tooltipElement_#{$i} {
      display: block;
      position: absolute;
      min-width: 100%;
      bottom: 40px;
      z-index: 1000000000;
      align: "center";
      color: #f2f2f2;
      background-color: #000000d9;
      // width : 77px;
      width: 200%;
      left: -50%;
      border-radius: 4px;
      padding: 6px 0px;
      word-break: keep-all;
      white-space: pre-wrap;
      // Light mode
      &.light-mode {
        background-color: #000000d9;
      }
      // Dark mode
      &.dark-mode {
        background-color: #424242;
      }

      &::after {
        content: "";
        position: absolute;
        top: 100%;
        left: 50%;
        margin-left: -6px;
        border-width: 6px;
        border-style: solid;
      }

      &.light-mode::after {
        border-color: #000000d9 transparent transparent transparent;
      }

      &.dark-mode::after {
        border-color: #424242 transparent transparent transparent;
      }
    }

    .tui-grid-rside-area {
      display: none;
      overflow: visible;
      overflow-x: visible;
      overflow-y: visible;
    }
    .tui-grid-header-area {
      border-style: solid;
      border-width: 0 0 1px;
      position: relative;
      overflow: visible;
      overflow-x: visible;
      overflow-y: visible;
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 12px 0;
  }
}
</style>
