<template>
  <div>
    <div class="d-flex justify-space-between align-center" style="min-height: 80px;">
      <span class="txt custom-title-4-new">Data Set TAG 연결 정보</span>
      <Buttons :parentPrgmId="parentPrgmId" :bindingData="gridName" :detailList="detailDataSetTagList"
        :btnActionsFnc="btnActions" />
    </div>
    <div ref="gridParent">
      <Grid :ref="gridName" :is="loadGrid ? 'Grid' : null" :gridName="gridName" :parentPrgmId="parentPrgmId"
        @getRowsData="getRowData" :innerTabGridInfo="innerTabGridInfo" />
    </div>
    <div ref="formParent" class="mt-4">
      <component :is="'Form'" :parentPrgmId="parentPrgmId" :bindingData="gridName" :detailList="detailDataSetTagList"
        @gridEditingFinish="gridEditingFinish" />
    </div>

    <div ref="formParent" style="min-height: 100px;" class="w100 h100">
      <v-row ref="contents" class="w100">
        <v-col :cols="6">
          <component :is="'Datepicker'" :parentPrgmId="parentPrgmId" :label="'검색기간'" :labelCols="12" :textCols="12" />
        </v-col>
        <v-col :cols="4">
          <component :is="'selectCodeList'" :parentPrgmId="parentPrgmId" :label="'주기'" dataKey="mdlDataTerm"
            :sendParam="{ commGrpCd: 'MDL_DATA_TERM', useFg: '1' }" :addAll="false" :labelCols="12" :textCols="12" :iconShow="true" />
        </v-col>
        <v-col class="text-right align-self-end">
          <a-button @click="jamoviProcClickEvent('view1')" type="primary" :ripple="false" class="mr-1">데이터 분석</a-button>
        </v-col>
        <!-- <v-card class="searchFilter w100">
          <v-row align="center" no-gutters>
          </v-row>
        </v-card> -->
      </v-row>
    </div>
  </div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import Buttons from '~/components/common/button/Buttons';
import Grid from '~/components/common/Grid';
import { CustumChecbox } from '~/plugins/gridUtility';
import { CustomNumberEditor } from '~/plugins/gridUtility';
import Form from '~/components/common/form/Form';
import mixinGlobal from '@/mixin/global.js';
import Utility from '~/plugins/utility';
import Datepicker from '~/components/common/DatepickerTopView';
import selectCodeList from '@/components/common/select/selectCodeList';
export default {
  mixins: [mixinGlobal],
  components: {
    Buttons,
    Grid,
    Form,
    Datepicker,
    selectCodeList,
  },
  props: {
    parentPrgmId: {
      type: String,
      require: true,
    },
    innerTabGridInfo: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      loadGrid: true,
      gridName: 'rowDataSetTagRelGrid',
      detailDataSetTagList: myDataSetTagDetail,
      dataPathMock: {
        "rowDataSetTagRelGrid": {
          column: [
            { header: 'TAG ID', name: 'id', headerAlign: 'left' },
            { header: 'TAG 명', name: 'name', headerAlign: 'left' },
            { header: '모델 Data 구분', name: 'type', headerAlign: 'left' }
          ],
          data: dataPathDataExample,
          defaultRow: dataPathDataExample,
          option: {}
        }
      },
    };
  },
  computed: {
    ...mapState({
      pageData(state) {
        return state.pageData[this.parentPrgmId];
      },
    }),
    selectedCommCd() {
      return this.pageData[this.gridName].data;
    },
    myUseFgList() {
      return this.pageData.useFgList;
    },
    selectedComId() {
      return this.pageData.rowGridSelectData.comId;
    },
    selectedDataSetId() {
      return this.pageData.rowGridSelectData.dataSetId;
    },
  },

  mounted() {
    this.init();
  },
  methods: {
    ...mapMutations({
      setPageData: 'setPageData',
      setGridData: 'setGridData',
      setGridColumn: 'setGridColumn',
      setGridOption: 'setGridOption',
    }),
    ...mapActions({
      postApi: 'modules/list/postApi',
      postUpdateApi: 'modules/list/postUpdateApi',
      postApiReturn: 'modules/list/postApiReturn',
      setTree: 'modules/list/setTree',
      chkOpenTabList: 'chkOpenTabList',
      getCodeList: 'modules/search/getCodeList',
    }),
    init() {
      this.gridInit();
    },
    gridInit() {
      const gridHeight = this.$refs['gridParent'].offsetHeight - 36;

      const myOptions = {
        // bodyHeight: gridHeight,
        // minBodyHeight: gridHeight,
        header: {
          height: 28,
        },
        rowHeight: 29,
        minRowHeight: 29,
        selectionUnit: 'row',
        editingEvent: 'click',
        // columnOptions: {
        //   resizable: true,
        //   minWidth: 100
        // }
      };
      this.setGridOption({
        gridKey: this.gridName,
        // value: myOptions
        value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
      });

      const _this = this;
      let useFgSelectList = [];
      this.pageData.useFgList.forEach(item => {
        const it = { text: item.commCdNm, value: item.commCd };
        useFgSelectList.push(it);
      });
      const myColumns = [
        { header: '회사 ID', name: 'comId', hidden: true },
        { header: 'DataSet ID', name: 'dataSetId', hidden: true },
        { header: 'DataSet 명', name: 'dataSetNm', hidden: true },
        { header: 'TAG ID', name: 'tagId', align: 'left', width: 440 },
        { header: 'TAG 명', name: 'tagNm', align: 'left', width: 320 },
        {
          header: '모델 Data 구분',
          name: 'mdlDataTypeCd',
          align: 'center',
          width: 120,
          formatter({ value }) {
            var retVal = '';

            for (var i = 0; i < _this.pageData.mdlDataTypeCdList.length; i++) {
              if (_this.pageData.mdlDataTypeCdList[i].commCd === value) {
                retVal = _this.pageData.mdlDataTypeCdList[i].commCdNm;
              }
            }

            return retVal;
          },
        },
        {
          header: '사용여부',
          name: 'useFg',
          align: 'center',
          width: 100,
          formatter({ value }) {
            value = value === true ? '1' : '0';
            const newValue = _this.pageData.useFgList.filter(
              item => item.commCd == value,
            );
            return newValue[0].commCdNm;
          },
          // editor: {
          //   type: "select",
          //   options: {
          //     listItems: useFgSelectList
          //   }
          // }
        },
        { header: '비고', name: 'rmrk', align: 'center' },
      ];

      this.setGridColumn({
        gridKey: this.gridName,
        value: myColumns,
      });

      this.loadGrid = true;
    },
    async getRowData(data, gridName) {
      // if (data.rowStat === 'I') {
      // 	this.detailDataSetTagList[0].disabled = false;
      // 	this.detailDataSetTagList[1].disabled = false;
      // } else {
      // 	this.detailDataSetTagList[0].disabled = true;
      // 	this.detailDataSetTagList[1].disabled = true;
      // }
      this.setGridSelectData({
        gridKey: gridName,
        gridSelect: true,
        rowGridSelectKey: data.rowKey,
        rowGridSelectData: Object.assign({}, data),
      });
    },
    async btnActions(action) {
      let dataArr = [];
      switch (action) {
        case 'add':
          console.log('add this.pageData : '); // , this.pageData);
          const defaultRow = {
            dataSetId: this.pageData.dataSetId,
            dataSetNm: this.pageData.dataSetNm,
            mdlDataTypeCd: 'SUM',
            tagId: '',
            tagNm: '',
            rmrk: null,
            useFg: true,
          };
          this.$refs[this.gridName].addRow(defaultRow);
          this.detailDataSetTagList[0].disabled = false;
          this.detailDataSetTagList[1].disabled = false;
          break;

        case 'remove':
          this.$refs[this.gridName].removeRow();
          this.detailDataSetTagList[0].disabled = true;
          this.detailDataSetTagList[1].disabled = true;
          break;

        case 'save':
          dataArr = this.$refs[this.gridName].save();
          // this.loadGrid = false;
          const newDataArr = dataArr.map(item => {
            const newData = {
              ...item,
              comId: this.selectedComId,
              dataSetId: this.selectedDataSetId,
            };
            newData.reprTagFg = newData.reprTagFg == true ? '1' : '0';
            newData.useFg = newData.useFg == true ? '1' : '0';
            return newData;
          });
          if (dataArr.length > 0) {
            var validCheck = true;
            dataArr.filter(item => {
              if (item.rowStat === 'I') {
                if (item.tagId == '' || item.distRt == '' || item.ercId == '') {
                  alert('필수 입력값을 입력해주세요.');
                  validCheck = false;
                }
              } else if (item.rowStat === 'U') {
                if (item.distRt == '' || item.ercId == '') {
                  alert('필수 입력값을 입력해주세요.');
                  validCheck = false;
                }
              }
            });

            if (validCheck) {
              const sendParam = {
                datas: {
                  dsMdlDataSetTagRel: newDataArr,
                },
                params: {},
              };
              await this.postUpdateApi({
                apiKey: 'saveMdlDataSetTagRel',
                sendParam: sendParam,
              });
              // this.loadGrid = true;
              this.setPageData({ isFind: true });
            }
          } else {
            alert('저장할 내용이 없습니다.');
          }
          break;

        default:
          break;
      }
    },
    gridEditingFinish(data, bindingData) {
      this.$refs[this.gridName].editingFinish(data);
    },
    emits: ['jamoviClickEvent'],
    search() { },
    jamoviProcClickEvent() {
      let data = {
        comId: this.selectedComId,
        dataSetId: this.selectedDataSetId,
      };
      console.log('data : ', data);
      this.$emit('jamoviClickEvent', 'view1', data);
    },
  },
};

const myDataSetTagDetail = [
  {
    type: 'EvtObjPop',
    labelContent: 'TAG',
    modalTitle: 'TAG 리스트',
    valueNm: 'tagId',
    valueNm2: 'tagNm',
    disabled: true,
    cols: 6,
    class: 'py-1 mt-2',
    required: true,
    labelCols: 12,
    textCols: 12,
    iconShow: true,
  },
  {
    type: 'InputText',
    label: 'TAG 명',
    valueNm: 'tagNm',
    disabled: false,
    cols: 6,
    class: 'py-2 mt-2',
    required: true,
    labelCols: 12,
    textCols: 12,
    iconShow: true
  },
  {
    type: 'SelectBox',
    label: '모델 Data 구분',
    valueNm: 'mdlDataTypeCd',
    disabled: false,
    cols: 6,
    class: 'py-2 mt-2',
    list: 'mdlDataTypeCdList',
    itemText: 'commCdNm',
    itemValue: 'commCd',
    required: true,
    textCols: 12,
    iconShow: true,
  },
  {
    type: 'CheckBox',
    label: '사용여부',
    valueNm: 'useFg',
    disabled: false,
    cols: 5,
    class: 'py-2 mt-2',
    value: { '1': true, '0': false },
    required: true,
    textCols: 12,
    iconShow: true,
    // class: "d-flex align-end"
  },
  {
    type: 'TextArea',
    label: '비고',
    valueNm: 'rmrk',
    disabled: false,
    cols: 12,
    textCols: 12,
    rows: 2,
    class: 'py-2 mt-2',
    required: false,
  },
];


const dataPathDataExample = [
  {
    id: 'INCHEON.HVAC.EQP_HT_CH001.UT_CH101.CHI_AMP_1A_PV',
    name: 'INCHEON 고온 냉동기 101호기 - 호로1',
    type: '합계'
  },
  {
    id: 'INCHEON.HVAC.EQP_HT_CH001.UT_CH101.CHI_AMP_1A_PV',
    name: 'INCHEON 고온 냉동기 101호기 - 호로1',
    type: '합계'
  },
  {
    id: 'INCHEON.HVAC.EQP_HT_CH001.UT_CH101.CHI_AMP_1A_PV',
    name: 'INCHEON 고온 냉동기 101호기 - 호로1',
    type: '합계'
  },
];
</script>
