<template>
  <v-row class="search-box" align="center" no-gutters>
    <v-dialog
      ref="popModal"
      v-model="dialog"
      width="1200px"
      overlay-color="#000"
      overlay-opacity="0.8"
      scrollable
    >
      <v-card style="height: 100%" class="searchFilter">
        <div class="pa-5">
          <!-- <v-text-field label="위치정보 선택"></v-text-field> -->
          <v-row align="center" no-gutters>
            <v-col :cols="3">
              <component
                :is="'SelectBox'"
                ref="SelectBox1"
                :propsValue="selectValue01"
                :itemList="selectValueList01"
                :label="'설비종류'"
                :labelCols="4"
                :textCols="7"
                @update:propsValue="selectValue01 = $event"
              />
            </v-col>
            <v-col :cols="3">
              <component
                :is="'SelectBox'"
                ref="SelectBox2"
                :propsValue="selectValue02"
                :itemList="selectValueList02"
                :label="'설비그룹'"
                :labelCols="4"
                :textCols="7"
                @update:propsValue="selectValue02 = $event"
              />
            </v-col>
            <v-col :cols="3">
              <component
                :is="'SelectBox'"
                ref="SelectBox3"
                :propsValue="selectValue03"
                :itemList="selectValueList03"
                :label="'설비'"
                :labelCols="4"
                :textCols="7"
                @update:propsValue="selectValue03 = $event"
              />
            </v-col>
            <v-col :cols="3">
              <v-row align="center">
                <v-col :cols="3" style="width: 100%">
                  <label for="" class="search-box-label">
                    <v-icon small :color="'primary'" class="mr-1 icon-blue"
                      >$icoBulletPoint</v-icon
                    >
                    TAG명
                  </label>
                </v-col>
                <v-col :cols="8" style="width: 100%">
                  <v-text-field
                    append-icon="mdi-magnify"
                    class="v-input__custom"
                    outlined
                    :hide-details="true"
                    v-model="searchWord"
                    @keyup.enter="search"
                  ></v-text-field>
                </v-col>
                <v-col :cols="1" style="width: 100%" class="text-right">
                  <v-btn icon tile :ripple="false" @click="dialogOpenCloseEvent(dialog)">
                    <v-icon>mdi-close</v-icon>
                  </v-btn>
                </v-col>
              </v-row>
            </v-col>
            <!-- <v-col :cols="1" class="text-right">
							<v-btn icon tile :ripple="false" @click="dialogOpenCloseEvent()">
								<v-icon>mdi-close</v-icon>
							</v-btn>
						</v-col> -->
          </v-row>
        </div>
        <v-divider></v-divider>

        <!-- <div id="chartParent" ref="chartParent" style="height: 100px"> -->
        <div :style="'height: 550px'" ref="modalGridDiv">
          <!-- <div :style="'height: 50vh'" ref="modalGridDiv"> -->
          <!-- <div :style="'height: calc(50%)'"> -->
          <div class="d-flex align-center justify-space-between pa-4" style="height: 10%">
            <v-card-title class="pa-0 custom-title-4">TAG 리스트</v-card-title>
          </div>
          <!-- <div id="chartParent" ref="chartParent" :style="'height: 80%'"> -->
          <div ref="modalGridParent" class="h100 w100">
            <component
              :is="loadGrid && dialog ? 'Grid' : null"
              :ref="gridName + parentPrgmId"
              :gridName="gridName"
              :dataPath="searchParam.tagTrndPopModalData.tagTrndPop"
              :parentPrgmId="parentPrgmId"
              @getRowsData="getRowData"
              @dblClick="setUpdate($event)"
            />
          </div>
        </div>
        <v-divider></v-divider>
        <v-card-actions class="pa-5 d-flex align-center justify-center">
          <v-btn color="primary" dark @click="setUpdate()">확인</v-btn>
          <v-btn color="primary" dark @click="dialogOpenCloseEvent(dialog)">취소</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-row>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import Grid from "~/components/common/Grid";
import Utility from "~/plugins/utility";
import selectCodeList from "@/components/common/select/selectCodeList";
import InputText from "~/components/common/input/InputText";
import Chart from "~/components/common/Chart";
import SelectBox from "@/components/common/select/SelectBox";

export default {
  props: {
    parentPrgmId: {
      type: String,
      require: true,
      default: "비교대상 최대(20개)",
    },
    label: {
      type: String,
      require: false,
      default: "전력 계약 정보",
    },
    valueNm: {
      type: String,
      require: false,
      default: "",
    },
    title: {
      type: String,
      require: false,
      default: "전력 계약 목록",
    },
    labelCols: {
      type: Number,
      require: false,
      default: 4,
    },
    textCols: {
      type: Number,
      require: false,
      default: 7,
    },
    item: {
      type: Object,
      require: true,
    },
    bindingData: {
      type: String,
      require: false,
    },
  },
  components: {
    Grid,
    selectCodeList,
    InputText,
    Chart,
    SelectBox,
    // Tree
  },
  data() {
    return {
      labelPrepend: true,
      gridName: "grid_01",
      myModalKey: "tagTrndPop",
      modalDataKey: "tagTrndPopModalData",
      // gridName: 'rowElecContGrid',
      loadChart: false,
      // selectedTargetMonth: 'all',
      dialog: false,
      selectValue01: null,
      selectValueList01: [],
      selectValue02: null,
      selectValueList02: [],
      selectValue03: null,
      selectValueList03: [],
      searchWord: "",
      loadGrid: false,
      initFlag: false,
      selectedData: {},
      totalSelectedTags: "",
    };
  },
  computed: {
    ...mapState({
      // searchParam: state => state.pageData,
      searchParam(state) {
        return state.pageData[this.parentPrgmId];
      },
      myBindingData(state) {
        //return state.pageData[this.parentPrgmId]["rowGridSelectData"];
        if (!this.bindingData) {
          return state.pageData[this.parentPrgmId]["rowGridSelectData"];
        } else {
          return state.pageData[this.parentPrgmId][this.bindingData]["rowGridSelectData"];
        }
      },
      // chkTotalSelectedTags(state) {
      // 	return state.pageData[this.parentPrgmId]['totalSelectedTags'];
      // }
      chkTotalSelectedTags(state) {
        return this.searchParam["totalSelectedTags"];
      },
    }),
    chkDialog() {
      return this.dialog;
    },
    // 	get() {
    // 		// if(this.searchParam.rowGridSelectData){
    // 		//     return this.searchParam.rowGridSelectData[this.item.valueNm];
    // 		// }
    // 		return this.myBindingData ? this.myBindingData[this.item.valueNm] : '';
    // 	},
    // 	set(value) {
    // 		// return value;
    // 		// return this.myBindingData({ [this.item.valueNm]: value });
    // 		//return this.setPageData({ [this.item.valueNm]: value });
    // 		return this.myBindingData({ [this.item.valueNm]: value });
    // 	},
    // },
  },
  watch: {
    async chkDialog(val) {
      if (val) {
        // await this.setSelectValueList01();
        // await this.setSelectValueList02();
        // await this.setSelectValueList03();
        this.search();
      } else {
        this.dialogOpenCloseEvent(val);
      }
      this.$nextTick();
      this.dialog = val;
    },
    async selectValue01(value) {
      await this.setSelectValueList02();
      // if(this.selectValue02 == '0'){
      // 	this.search();
      // }else{
      // 	this.setSelectValueList02();
      // }
    },
    async selectValue02(value) {
      await this.setSelectValueList03();
    },
    async selectValue03(value) {
      if (this.initFlag) {
        this.search();
      }
    },
    chkTotalSelectedTags(value) {
      this.totalSelectedTags = value;
    },
  },

  beforeCreate() {
    this.$store.commit("setPageData", {
      tagTrndPopModalData: { tagTrndPop },
    });
  },
  async created() {
    await this.setSelectValueList01();
    await this.setSelectValueList02();
    await this.setSelectValueList03();
    this.init();
    // if(this.searchParam.isMulti == true){
    //   this.setPageData({
    //     facInfoList : localStorage.getItem(this.parentPrgmId + "CheckedRow") !=null ? JSON.parse(localStorage.getItem(this.parentPrgmId + "CheckedRow")) : {}
    //   });
    // }else{
    //   this.setPageData({
    //     facInfo : localStorage.getItem(this.parentPrgmId + "CheckedRow") !=null ? JSON.parse(localStorage.getItem(this.parentPrgmId + "CheckedRow")) : {}
    //   });
    // }
  },
  methods: {
    ...mapMutations({
      setPageData: "setPageData",
      setModalGridData: "setModalGridData",
      setModalGridColumn: "setModalGridColumn",
      setModalGridOption: "setModalGridOption",
    }),
    ...mapActions({
      postApiReturn: "modules/list/postApiReturn",
    }),
    async init() {
      // this.setChart();
      this.gridInit();
      await this.setGridData();
      this.initFlag = true;
    },
    async setSelectValueList01() {
      let res = await this.postApiReturn({
        apiKey: "selectEqpmKindCodeList",
        resKey: "eqpmKindCodeLists",
        sendParam: {},
      });

      // this.setPageData({
      // 	eqpmKindIdList: res,
      // 	eqpmKindId: res[0].eqpmKindId,
      // });

      if (res.length > 0) {
        this.selectValueList01 = await res.map((item) => {
          return {
            text: item.eqpmKindNm,
            value: item.eqpmKindId,
            data: {
              ...item,
            },
          };
        });
        this.selectValue01 = this.selectValueList01[0].value;
      } else {
        this.selectValueList01 = [];
        this.selectValue01 = null;
      }
    },
    async setSelectValueList02() {
      let res = await this.postApiReturn({
        apiKey: "selectEqpmGrpCodeList",
        resKey: "eqpmGrpCodeLists",
        sendParam: { eqpmKindId: this.selectValue01 },
      });
      if (res.length > 0) {
        this.selectValueList02 = await res.map((item) => {
          return {
            text: item.eqpmGrpNm,
            value: item.eqpmGrpId,
          };
        });
        this.selectValue02 = this.selectValueList02[0].value;
      } else {
        this.selectValueList02 = [];
        this.selectValue02 = null;
      }
      // this.setPageData({
      // 	eqpmGrpList: this.selectValueList02,
      // 	eqpmGrpId: this.selectValue02,
      // });
    },
    async setSelectValueList03() {
      var res = await this.postApiReturn({
        apiKey: "selectEqpmBaseInfo",
        resKey: "eqpmBaseInfoData",
        sendParam: {
          eqpmGrpId: this.selectValue02,
        },
      });
      if (res.length > 0) {
        this.selectValueList03 = await res.map((item) => {
          return {
            text: item.eqpmNm,
            value: item.eqpmId,
            data: {
              ...item,
            },
          };
        });
        this.selectValueList03.unshift({
          text: "전체",
          value: "all",
        });
        // 설비 그룹을 변경하여 설비를 다시 조회하였지만 이전에 조회한 값이 '전체'일 경우
        // watch에서 값 변화를 인지 못하기 때문에 여기서 조회 시킨다.
        if (this.selectValue03 == "all" && this.initFlag) {
          this.search();
        }
        this.selectValue03 = this.selectValueList03[0].value;
      } else {
        this.selectValueList03 = [];
        this.selectValue03 = null;
      }
    },
    // 계약 정보 조회
    setUpdate() {
      if (this.selectedData.tagId != undefined) {
        let res = this.chkDuplicateTagId(this.selectedData.tagId);
        if (res) {
          alert("TAG가 중복 됩니다.");
        } else {
          if (this.selectedData.tagId != undefined) {
          }
          this.dialog = false;
          for (var key in this.searchParam["rowGrid"]["defaultRow"]) {
            let dt = {
              columnName: key,
              value: this.selectedData[key],
            };
            this.$emit("gridEditingFinish", dt);
            this.setPageData({ rowGridSelectData: this.selectedData });
          }
          // this.$emit('gridEditingFinish', dt);
          // 중복 선택 및
          // let tempWord = '';
          // tempWord += this.selectedData.tagId + '/*wq2a/';
          // let totalSelectedTags = this.totalSelectedTags + tempWord;
          // let tempTagList = totalSelectedTags.split('/*wq2a/');
          // let tagList = tempTagList.filter(item => item != '');

          let tagList = this.searchParam.tagList;
          tagList.push(this.selectedData.tagId);
          // console.log('temp!!!', temp);
          // console.log('tagList!!!', tagList);
          // this.setPageData({ totalSelectedTags : totalSelectedTags });
          this.setPageData({ tagList: tagList });
        }
      } else {
        alert("TAG를 선택해주세요.");
      }
    },
    dialogOpenCloseEvent(val) {
      this.searchWord = "";
      if (val) {
        this.dialog = !val;
      } else {
        this.$emit("closePopEvent");
      }
    },
    async search() {
      await this.setGridData();
    },
    gridInit() {
      // const gridHeight = this.$refs.modalGridParent.offsetHeight - 60
      const myOptions = {
        columnOptions: {
          resizable: true,
        },
        header: {
          height: 38,
        },
      };
      this.setModalGridOption({
        modalKey: this.myModalKey,
        gridKey: this.gridName,
        modalDataKey: this.modalDataKey,
        value: Object.assign(
          // Utility.defaultGridOption(this.$refs.modalGridParent.offsetHeight - 60, myOptions),
          Utility.defaultGridOption(460, myOptions),
          myOptions
        ),
      });
      const _this = this;
      const myColumns = [
        // { header: '가이드ID', name: 'gdIdxId', align: 'center', hidden: true},
        { header: "설비그룹", name: "eqpmGrpNm", align: "left", width: 130 },
        {
          header: "설비그룹 ID",
          name: "eqpmGrpId",
          align: "center",
          hidden: true,
        },
        { header: "설비ID", name: "eqpmId", align: "left", width: 130 },
        { header: "설비명", name: "eqpmNm", align: "left", width: 130 },
        { header: "TAG ID", name: "tagId", align: "left", width: 470 },
        { header: "TAG 명", name: "tagNm", align: "left" },
        { header: "rowStat", name: "rowStat", align: "center", hidden: true },
      ];
      this.setModalGridColumn({
        modalKey: this.myModalKey,
        gridKey: this.gridName,
        modalDataKey: this.modalDataKey,
        value: myColumns,
      });

      this.loadGrid = true;
    },
    async setGridData() {
      this.loadGrid = false;
      let searchParam = {
        eqpmGrpId: this.selectValue02,
        eqpmId: this.selectValue03,
        searchWord: this.searchWord,
      };
      // let res = [
      //   {
      //     eqpmGrpNm: "냉각 시스템",
      //     eqpmGrpId: "GRP001",
      //     eqpmId: "EQ001",
      //     eqpmNm: "냉각기 A",
      //     tagId: "TAG001-001",
      //     tagNm: "냉각 온도 센서",
      //     rowStat: "I",
      //   },
      //   {
      //     eqpmGrpNm: "전력 시스템",
      //     eqpmGrpId: "GRP002",
      //     eqpmId: "EQ002",
      //     eqpmNm: "변압기 B",
      //     tagId: "TAG002-002",
      //     tagNm: "전류 센서",
      //     rowStat: "U",
      //   },
      //   {
      //     eqpmGrpNm: "공기압 시스템",
      //     eqpmGrpId: "GRP003",
      //     eqpmId: "EQ003",
      //     eqpmNm: "압축기 C",
      //     tagId: "TAG003-003",
      //     tagNm: "압력 센서",
      //     rowStat: "D",
      //   },
      // ];
      let res = await this.postApiReturn({
          apiKey: "selectTagAndEqpmList",
          resKey: "tagTrndDatas",
          sendParam: searchParam,
      });
      let newRes = [];
      if (this.searchParam["tagList"].length > 0) {
        newRes = res.filter((item) => {
          return !this.searchParam["tagList"].includes(item.tagId);
        });
        res = newRes;
      }
      this.setModalGridData({
        modalKey: this.myModalKey,
        gridKey: this.gridName,
        modalDataKey: this.modalDataKey,
        value: res,
      });
      this.$nextTick(() => {
        if (res.length > 0) {
          try {
            this.$refs[this.gridName + this.parentPrgmId].focus({
              rowKey: 0,
              setScroll: true,
            });
          } catch (error) {
            // console.log('error', error);
          }
        }

        // 	await this.setGridData();
      });
      this.loadGrid = true;
    },
    getRowData(data) {
      this.selectedData = { ...data };
    },
    chkDuplicateTagId(data) {
      let res = false;
      let tempList = [];
      // tempList = this.totalSelectedTags.split('/*wq2a/');
      tempList = this.searchParam.tagList;
      if (tempList.includes(data)) {
        res = true;
      }
      return res;
    },
  },
};

let tagTrndPop = {
  grid_01: {
    data: [],
    column: {},
    option: {},
  },
};
// 전력량 요금(원/kWh)
</script>
