<template>
  <div class="l-layout">
    <!-- <h2 class="title">
			<v-icon small color="primary" class="mr-1">mdi-circle</v-icon>
			계량 데이터 마감 관리
		</h2> -->
    <PageTitle text="계량 데이터 마감 관리" />

    <v-row ref="searchFilter">
      <!-- 조회조견 -->
      <v-col :cols="12">
        <v-card class="searchFilter">
          <v-row align="end" no-gutters>
            <v-col :cols="2.5">
              <component
                :is="'SelectBlocMstr'"
                ref="SelectBlocMstr"
                :parentPrgmId="myPrgmId"
                :textCols="12"
                customClass="select-large"
              />
            </v-col>
            <v-col :cols="2.5">
              <component
                :is="'selectCodeList'"
                :parentPrgmId="myPrgmId"
                :label="'검침대상유형'"
                dataKey="commCd"
                :sendParam="{ commGrpCd: 'CM_MTTTP', useFg: '1' }"
                customClass="select-large"
              />
            </v-col>

            <v-col :cols="2.5">
              <component
                :is="'SelectMttList'"
                ref="SelectMttList"
                dataKey="readObjId"
                :parentPrgmId="myPrgmId"
                :label="'검침대상'"
                :textCols="12"
                customClass="select-large"
              />
            </v-col>
            <v-col :cols="2.5">
              <component
                ref="fromPicker"
                :is="'Datepicker'"
                :parentPrgmId="myPrgmId"
                :label="'조회기간'"
              />
            </v-col>
            <div class="d-flex">
              <BtnExcelDownload
                class="mr-1"
                :parentPrgmId="myPrgmId"
                :gridName="gridName"
                type="primary"
                :size="'large'"
              />
              <a-button
                type="primary"
                class="mr-1"
                icon="search"
                :ripple="false"
                @click="search"
                style="height: 40px"
              >
                조회
              </a-button>
            </div>
          </v-row>
        </v-card>
      </v-col>
    </v-row>
    <v-row ref="contents">
      <!-- 일일검침정보 목록-->
      <v-col :cols="12" class="h100">
        <v-card class="pb-5">
          <div class="d-flex align-center justify-space-between pa-5">
            <v-card-title class="custom-title-4 pa-0">일일검침정보</v-card-title>
            <div class="d-flex align-center">
              <a-button
                :ripple="false"
                @click="saveReadResultCloseMngMM()"
                type="primary"
                class="mr-1"
                >월마감</a-button
              >
              <a-button
                type="primary"
                :ripple="false"
                @click="saveReadResultCloseMng('N')"
                >일마감</a-button
              >
            </div>
          </div>
          <div class="px-5" style="min-height: calc(100% - 76px)">
            <div ref="gridParent" class="h100 w100">
              <component
                :is="loadGrid ? 'Grid' : null"
                :ref="gridName"
                :parentPrgmId="myPrgmId"
                :gridName="gridName"
                :dataPath="dataPathMock"
              />
            </div>
          </div>
        </v-card>
      </v-col>
    </v-row>
  </div>
</template>
<script>
import mixinGlobal from "@/mixin/global.js";
import { resize } from "@/mixin/resize.js";
import { mapState, mapMutations, mapActions } from "vuex";
import Search from "~/components/common/search";
import Grid from "~/components/common/Grid";
import Utility from "~/plugins/utility";
import SelectBlocMstr from "@/components/common/select/SelectBlocMstr";
import selectCodeList from "@/components/common/select/selectCodeList";
import SelectMttList from "@/components/common/select/SelectMttList";
import Datepicker from "~/components/common/Datepicker";
import BtnExcelDownload from "~/components/common/button/BtnExcelDownload";
import PageTitle from "~/components/common/PageTitle";

let myTitle;
// const myPrgmId = "PRG0018";
let myPrgmId;
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: {
    SelectBlocMstr,
    selectCodeList,
    SelectMttList,
    BtnExcelDownload,
    Datepicker,
    Search,
    Grid,
    PageTitle,
  },
  data() {
    return {
      myPrgmId: myPrgmId,
      gridName: "rowGrid",
      loadGrid: true,
      dataPathMock: {
        rowGrid: {
          column: [
            { header: "태그", name: "id", headerAlign: "left" },
            { header: "배율", name: "lable", headerAlign: "left" },
            { header: "설비비", name: "type", headerAlign: "left" },
            { header: "설비배분비율", name: "note", headerAlign: "left" },
            { header: "금일데이터", name: "note", headerAlign: "left" },
            { header: "최종마감시각", name: "date", headerAlign: "left" },
          ],
          data: dataPathDataExample,
          defaultRow: dataPathDataExample,
          option: {},
        },
      },
    };
  },
  computed: {
    ...mapState({
      isDarkMode: (state) => state.isDarkMode,
      pageData: (state) => state.pageData[myPrgmId],
    }),
    chkIsFind() {
      // 조회 플래그
      return this.pageData.isFind;
    },
    chkBlocId() {
      // 사업장 코드
      return this.pageData.blocId;
    },
    chkCommCd() {
      this.setPageData({ sendMttParam: { mttTp: this.pageData.commCd } });
      return this.pageData.commCd;
    },
    chkReadObjId() {
      return this.pageData.readObjId;
    },
  },
  watch: {
    chkIsFind(val) {
      if (val) this.search();
    },
    chkBlocId() {
      this.setPageData({ isFind: true });
    },
    chkPlcKind() {
      this.setPageData({ isFind: true });
    },
    chkCommCd() {},
    async chkReadObjId(val) {
      // console.log("sendMttParam",this.pageData.sendMttParam.mttTp);
      // if(this.pageData.sendMttParam.mttTp){
      // await this.getRowGridData();
      // }
      this.setPageData({ isFind: true });
    },
  },
  async beforeCreate() {
    myPrgmId = this.$route.query.prgmId;
    await this.$store.dispatch("chkOpenTabList", {
      key: "create",
      prgmId: myPrgmId,
      defaultData: defaultData,
    });
  },
  mounted() {
    this.init();
  },
  created() {},
  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",
    }),
    init() {
      this.gridInit();
    },
    gridInit() {
      const gridHeight = this.$refs.gridParent.offsetHeight - 30;

      const myOptions = {
        columnOptions: {
          resizable: true,
        },
      };
      this.setGridOption({
        gridKey: this.gridName,
        value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
      });
      this.setGridColumn({
        gridKey: this.gridName,
        value: myColumns,
      });
      this.loadGrid = true;
    },
    async search() {
      await this.getRowGridData();
    },
    async getRowGridData() {
      if (
        this.pageData.blocMstrList.length > 0 &&
        this.pageData.commCdList.length > 0 &&
        this.pageData.readObjIdList.length > 0
      ) {
        const res = await this.postApiReturn({
          apiKey: "selectReadResultCloseMng",
          resKey: "cdKindData",
          sendParam: {
            blocId: this.pageData.blocMstrList[this.pageData.blocId].blocId, // 사업장
            mttCd: this.pageData.commCd, // 검침대상유형
            mttTp: this.pageData.readObjId, // 검침대상
            readDt: this.pageData.fromDt, // 조회기간
          },
        });
        this.setGridData({
          gridKey: this.gridName,
          value: res.map((item) => ({
            ...item,
            mgnf: item.mgnf || 0,
          })),
        });
      }
      this.setPageData({ isFind: false });
    },
    //전월 or 일 마감--------------------------------------------------------------------------------------------
    async saveReadResultCloseMng(mnthYn) {
      const result = confirm("마감시 기존자료는 삭제됩니다. \n계속하겠습니까?");
      if (await result) {
        const sendParam = {
          datas: {},
          params: {
            mnthYn: mnthYn,
            procIp: "0.0.0.0",
            readDt: this.pageData.fromDt,
          },
        };
        await this.postUpdateApi({
          apiKey: "saveReadResultCloseMngSP",
          sendParam: sendParam,
        });
        this.setPageData({ isFind: true });
      }
    },
    async saveReadResultCloseMngMM() {
      const result = confirm("마감시 기존자료는 삭제됩니다. \n계속하겠습니까?");
      if (await result) {
        const sendParam = {
          datas: {},
          params: {
            procIp: "0.0.0.0",
            readDt: this.pageData.fromDt,
          },
        };
        await this.postUpdateApi({
          apiKey: "saveReadResultCloseMngSPMM",
          sendParam: sendParam,
        });
        this.setPageData({ isFind: true });
      }
    },
  },
};

const defaultData = {
  /* 검색옵션 */
  mttTp: "",
  mttTpList: [],
  sendMttParam: {},
  readPlc: "",
  readObjId: "",
  readObjIdList: [],
  commCd: "",
  commCdList: [],
  cmCycle: "CYC_HOUR",
  blocId: "",
  blocMstrList: [],

  fromDt: Utility.setFormatDate(new Date(), "YYYYMMDD"),

  isFind: false,

  /* data 세팅 - sms 목록 */
  rowGrid: {
    data: [],
    column: [],
    option: {},
  },

  defaultRange: {
    CYC_HOUR: 0,
  },

  xlsFileInfo: {
    // 출력하려는 grid 와 같은 이름으로 세팅
    rowGrid: {
      // 엑셀변환시 데이타 가공이 추가로 필요하게 된다면 여기에 가공된 rowData 를 넣어야 할듯
      fileName: null, // 갑이 없으면 해당 페이지 메뉴명
      sheetName: null, //  갑이 없으면 'Sheet1'
    },
  },
};

const myColumns = [
  {
    header: "태그",
    name: "readPlcNm",
    width: 300,
  },
  {
    header: "배율",
    name: "distRt",
    align: "right",
    formatter({ value }) {
      if (value === null) {
        return "";
      } else {
        return value;
      }
    },
  },
  {
    header: "설비비",
    name: "eccNm",
    formatter({ value }) {
      if (value === null) {
        return "";
      } else {
        return value;
      }
    },
  },
  {
    header: "설비배분비율",
    name: "eccDistRt",
    align: "right",
    formatter({ value }) {
      if (value === null) {
        return "";
      } else {
        return value;
      }
    },
  },
  {
    header: "금일데이터",
    name: "totVal",
    align: "right",
    excelType: "number",
    excelFormatter: "2",
    formatter({ value }) {
      return Utility.setFormatIntDecimal(value, 2);
    },
  },
  {
    header: "최종마감시각",
    name: "procDttm",
    align: "center",
    formatter({ value }) {
      if (value === null) {
        return "";
      } else {
        return value;
      }
    },
  },
];

import { getPathDataExample } from "@/const/const";
const dataPathDataExample = getPathDataExample({
  id: "INCHEON.HVAC.EQP_HT_CH001.UT_CH101.CHI_AMP_1A_PV",
  lable: "INCHEON 고온 냉동기 101호기 - 호로1",
  type: "사용",
  note: "-",
  date: "2023-01-10 20:02:00",
});
</script>
