<template>
  <div class="l-layout">
    <CommonPageTitle />
    <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="'조회기간'"
                customClass="datepicker-large"
              />
            </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">
        <v-card class="pb-5 w100">
          <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 ref="gridParent" class="px-5 w100" style="height: 55vh;">
              <component
                :is="loadGrid ? 'Grid' : null"
                :ref="gridName"
                :parentPrgmId="myPrgmId"
                :gridName="gridName"
              />
          </div>
					<div class="d-flex align-center justify-center pa-5" v-if="loadGrid && totalCount > 0">
            <pagination id="pagination" :total-count="totalCount" :page-num="page" :limit="limit"
								@loadData="changeGrid" />
						</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 pagination from '~/components/common/Pagination';

let myTitle;
// const myPrgmId = "PRG0018";
let myPrgmId;
export default {
  mixins: [mixinGlobal, resize],
  async asyncData(context) {
    // console.log('----DEBUG-----ReadResultCloseMngPage--asyncData:', Utility.setFormatDate(new Date(), "YYYYMMDD"));
    try{
      myPrgmId = context.route.query.prgmId;
      const myState = context.store.state;
      const activeMenuInfo = myState.menuData[myPrgmId];
      myTitle = activeMenuInfo.menuNm;

      // console.log('-----DEBUG----store.commit----setActiveMenuInfo:', activeMenuInfo);
      await context.store.commit("setActiveMenuInfo", activeMenuInfo);
      myTitle = await myState.activeMenuInfo.menuNm;
      // console.log('-----DEBUG----store.commit----setActiveMenuInfo---Compeleted:', myState.activeMenuInfo);
    }catch(err){
      // console.log('-----DEBUG----err', err);
    }
  },
  meta: {
    title: () => {
      return myTitle;
    },
    prgmId: myPrgmId,
    closable: true,
  },
  components: {
    SelectBlocMstr,
    selectCodeList,
    SelectMttList,
    BtnExcelDownload,
    Datepicker,
    Search,
    Grid,
    pagination,
  },
  data() {
    return {
      myPrgmId: myPrgmId,
      gridName: "rowGrid",
      loadGrid: false,
			itemsPerPage: 10,
			itemsPerPageArray: [10, 20, 50],
			limit: 20,
			page: 1,
			totalCount: 0,
    };
  },
  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.page = 1;
				this.search(false);
			}
    },
    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 });
    },
  },
  beforeCreate() { 
    // console.log('----DEBUG-----ReadResultCloseMngPage--beforeCreate:', Utility.setFormatDate(new Date(), "YYYYMMDD"));
    myPrgmId = this.$route.query.prgmId;
    const context = {
      key: "create",
      prgmId: myPrgmId,
      defaultData: defaultData,
    };
    this.$store.dispatch("chkOpenTabList", context);
  },
  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,
      });
    },
    async search(isPaging) {
      await this.getRowGridData(isPaging);
    },
    async getRowGridData(isPaging) {
      if(!isPaging) {
        this.loadGrid = false;
      }
      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, // 조회기간
            limit: this.limit,
					  page: this.page,
					  offset: (this.page - 1) * this.limit, // MariaDB Query에서 직접 계산이 안됨
          },
        });

        const res2 = await this.postApiReturn({
					apiKey: 'selectReadResultCloseMngPageTotal',
					resKey: 'cdKindPageTotal',
          sendParam: {
            blocId: this.pageData.blocMstrList[this.pageData.blocId].blocId, // 사업장
            mttCd: this.pageData.commCd, // 검침대상유형
            mttTp: this.pageData.readObjId, // 검침대상
            readDt: this.pageData.fromDt, // 조회기간
          },
				});

				this.totalCount = res2[0].totalcount;

        this.setGridData({
          gridKey: this.gridName,
          value: res.map((item) => ({
            ...item,
            mgnf: item.mgnf || 0,
          })),
        });
      }
      this.setPageData({ isFind: false });
      this.$nextTick(() => {
        this.loadGrid = true;
      })
    },
    //전월 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 });
      }
    },
    changeGrid: async function (pageNum, limit) {
			this.page = pageNum;
			this.limit = limit;

			this.search(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;
      }
    },
  },
];
</script>
<style lang="scss" scoped>
	::v-deep{
		.tui-grid-layer-state{
			top: 40px !important;
		}
	}
</style>