<template>
  <div class="contents">
    <div class="contents_wrap">
      <div class="top_wrap">
        <h3 class="title">청구 검증</h3>
        <p class="breadcrumb">운영 관리 &gt; 청구 검증</p>
      </div>
      <div class="search_wrap">
        <div class="input_box cal">
          <label for="right" class="label txt">조회기간</label>
          <div class="term">
            <span class="custom_input icon_date">
              <vuejs-datepicker
                :language="ko"
                :format="customFormatter"
                :disabled-dates="disabledDate"
                :minimumView="sDateDiv"
                :maximumView="sDateDiv"
                v-model="lmtYm"
                @selected="selectedDate"
              ></vuejs-datepicker>
            </span>
          </div>
        </div>
        <button type="button" class="button grey" @click="adressModalOpen()">조회</button>
      </div>
      <div class="info">
        <div class="count">
          총 <span>{{totalCnt}}</span>건
        </div>
        <div class="button_group">
          <button type="button" class="button grey" @click="excuteVerification()">청구 검증 실행</button>
          <button type="button" class="button blue download" @click="verificationExcel()">엑셀다운로드</button>
        </div>
      </div>
      <div class="table calculate scroll">
        <section>
          <div class="box_scroll box_OFvis">
            <table class="tbl_col_type cgrid" style="table-layout: fixed;">
              <colgroup>
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 180px;">
                <col style="width: 120px;">
                <col style="width: 180px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 80px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 100px;">
                <col style="width: 80px;">
                <col style="width: 80px;">
                <col style="width: 100px;">
              </colgroup>
              <thead>
                <tr>
                  <th scope="col" rowspan="2">할인율(%)</th>
                  <th scope="col" rowspan="2">유큐브<br>청구금액</th>
                  <th scope="col" rowspan="2">계산된<br>청구금액</th>
                  <th scope="col" rowspan="2">청구금액<br>일치여부</th>
                  <th scope="col" rowspan="2">고객사</th>
                  <th scope="col" rowspan="2">사업자번호</th>
                  <th scope="col" rowspan="2">유큐브등록번호</th>
                  <th scope="col" rowspan="2">상품명</th>
                  <th scope="col" rowspan="2">가입일</th>
                  <th scope="col" rowspan="2">일할대상</th>
                  <th scope="col" rowspan="2">상태</th>
                  <th scope="col" rowspan="2">성공건수</th>
                  <th scope="colgroup" colspan="6" id="thHeader08" class="th_line">결과</th>
                  <th scope="colgroup" colspan="8" id="thHeader09" class="th_line">이전 달</th>
                  <th scope="colgroup" colspan="5" id="thHeader10" class="th_line">사용금액</th>
                </tr>
                <tr>
                  <th headers="thHeader08" class="th_line">과금금액</th>
                  <th headers="thHeader08" class="th_line">일할 정액요금</th>
                  <th headers="thHeader09" class="th_line">소멸금액</th>
                  <th headers="thHeader08" class="th_line">신규 이월금액</th>
                  <th headers="thHeader08" class="th_line">예상 이월금액</th>
                  <th headers="thHeader08" class="th_line">이월 일치여부</th>
                  <th headers="thHeader09" class="th_line">정액요금</th>
                  <th headers="thHeader09" class="th_line">이월금액</th>
                  <th headers="thHeader09" class="th_line">소멸충전금액</th>
                  <th headers="thHeader09" class="th_line">이월충전금액</th>
                  <th headers="thHeader09" class="th_line">소멸충전복원</th>
                  <th headers="thHeader09" class="th_line">이월충전복원</th>
                  <th headers="thHeader09" class="th_line">소멸충전잔액</th>
                  <th headers="thHeader09" class="th_line">이월충전잔액</th>
                  <th headers="thHeader010" class="th_line">총</th>
                  <th headers="thHeader010" class="th_line">알림톡</th>
                  <th headers="thHeader010" class="th_line">SMS</th>
                  <th headers="thHeader010" class="th_line">LMS</th>
                  <th headers="thHeader010" class="th_line">MMS</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, i) in list" v-bind:key="i" >
                  <td><input type="text" class="search-box" @keypress="onlyNumFstZero" @input="onlyNumFstZero" maxlength="3" v-model="item.discount" autocomplete="off"></td>
                  <td><input type="text" class="search-box" @keypress="onlyNumFstZero" @input="onlyNumFstZero" maxlength="10" v-model="item.billAmt" autocomplete="off"></td>
                  <td>{{item.calUseAmt}}</td>
                  <td>{{item.billRslt}}</td>
                  <td>{{item.custNm}}</td>
                  <td>{{item.bizrno}}</td>
                  <td>{{item.entrNo}}</td>
                  <td>{{item.prodNm}}</td>
                  <td>{{item.opnDt}}</td>
                  <td>{{item.dayUser}}</td>
                  <td>{{item.dtlCdNm}}</td>
                  <td>{{item.succCnt}}</td>
                  <td>{{item.mrtUseAmt}}</td>
                  <td>{{item.lmtPerUseDay}}</td>
                  <td>{{item.extncAmt}}</td>
                  <td>{{item.nowCfwdAmt}}</td>
                  <td>{{item.estCfwdAmt}}</td>
                  <td>{{item.rsltStr}}</td>
                  <td>{{item.fxLmtAmt}}</td>
                  <td>{{item.cfwdAmt}}</td>
                  <td>{{item.extcChrgAmt}}</td>
                  <td>{{item.cfwdChrgAmt}}</td>
                  <td>{{item.extcChrgRsrt}}</td>
                  <td>{{item.cfwdChrgRsrt}}</td>
                  <td>{{item.extcChrgBlnc}}</td>
                  <td>{{item.cfwdChrgBlnc}}</td>
                  <td>{{item.totalUseAmt}}</td>
                  <td>{{item.kkoNotiUseAmt}}</td>
                  <td>{{item.smsUseAmt}}</td>
                  <td>{{item.lmsUseAmt}}</td>
                  <td>{{item.mmsUseAmt}}</td>
                </tr>
                <tr v-if="list.length < 1">
                  <td colspan="29" class="no_data">검색 결과가 없습니다.</td>
                </tr>
              </tbody>
            </table>

          </div>
        </section>
      </div>
      <common-modal ref="commmonModal"></common-modal>
    </div>
  </div>
</template>

<script>
import moment from 'moment';
import xlsx from '@/common/excel';
import commonModal from '@/components/modal/commonModal';
import calcMgtApi from "@/modules/calculate/service/calcMgtApi";
import {utils_mixin, chkPattern2} from '../service/mixins';

export default {
  name: 'verification',
  mixins: [utils_mixin, chkPattern2],
  data() {
    return {
      ko: vdp_translation_ko.js,
      periodDay: 7,
      sDateDiv: 'month',
      lmtYm: new Date(new Date().setMonth(new Date().getMonth()-1)),
      disabledDate: {from : new Date(new Date().setMonth(new Date().getMonth()-1))},
      
      row: {},
      
      list: [],
      params: {},
      pageType: 'VERIFICATION',
      totalCnt : 0,
      noDataStr: '검색 결과가 없습니다.',
      excelHeader: [],
      excelDownAble:false,
      zip: '',
      addr1: '',
      addr2: ''
    };
  },
  components: {
    commonModal,
    vuejsDatepicker
  },
  computed : {},
  watch: {},
  created() {
    this.getExcelHeader();
  },
  destroyed() {},
  mounted() {
    let isKeep = false;
    this.verification();
  },
  methods: {
    async verification() {
      this.excelDownAble = false;
      this.params = {
        lmtYm: moment(this.lmtYm).format('YYYYMM')
      }
      try {
        const response = await calcMgtApi.verification(this.params);

        const result = response.data;
        
        if (result != null && result.retCode == '0000') {
          this.list = result.data.list;
          this.totalCnt = result.data.list.length;
        }else{
          this.initData();
          this.row.title = '청구 목록 조회 실패';
          this.row.msg1 = result.retMsg;
          this.$refs.commmonModal.alertModalOpen(this.row);
          return false;
        }

      } catch(err){
        this.initData();
        this.row.title = '청구 목록 조회 실패';
        this.row.msg1 = err;
        this.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }
    },
    adressModalOpen: function(){
      //this.$refs.adressModal.adressPopupOpen();
      window.open("/calculate/adressPopup", "pop", "width=480, height=800, top=100, left=100, fullscreen=no, menubar=no, status=no, toolbar=no, titlebar=yes, location=no, scrollbar=no,  rel=opener");
    },
    initData: function(){
      this.list = [];
      this.totalCnt = 0;
    },
    customFormatter: function (date) {
      if (this.sDateDiv == 'month') {
        return moment(date).format('YYYY-MM');
      } else if (this.sDateDiv == 'year') {
        return moment(date).format('YYYY');
      } else {
        return moment(date).format('YYYY-MM-DD');
      }
    },
    selectedDate(day) {
      let isKeep = false;
      this.lmtYm = day;
      this.verification();
    },
    getExcelHeader() {
      // 헤더를 mockup으로 관리한다.
      calcMgtApi.getExcelHeader(this.pageType).then((res) => {

        this.excelHeader = res;
      });
    },
    excuteVerification() {
      if (this.list.length <= 0) {
        this.row.title = '청구 검증 실행';
        this.row.msg1 = '조회된 데이터가 없습니다.';
        this.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }
      
      if(moment(new Date(new Date().setMonth(new Date().getMonth()-1))).format('YYYYMM') == moment(this.lmtYm).format('YYYYMM') 
      && (new Date().getDate() < 4)){
        this.row.title = '청구 검증 실행';
        this.row.msg1 = '해당월은 4일 부터 청구 검증이 가능합니다.';
        this.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }
      
      this.list = this.list.map((item,index) => {
        
        if(item.discount.trim() == undefined || item.discount.trim() == null || item.discount.trim() == "" || item.discount.trim().toLowerCase() == "e"){
          item.discount = 0;
        }

        if(item.billAmt.trim() == undefined || item.billAmt.trim() == null || item.billAmt.trim() == "" || item.billAmt.trim().toLowerCase() == "e"){
          item.billAmt = 0;
        }
        
        item.calUseAmt = (Number(item.lmtPerUseDay)+Number(item.mrtUseAmt.replaceAll(",","")));
        item.calUseAmt = item.calUseAmt - (item.calUseAmt*(Number(item.discount)/100));
        item.calUseAmt = Math.floor(item.calUseAmt/10) * 10; 

        item.billRslt = "불일치";
        if(item.calUseAmt == item.billAmt){
          item.billRslt = "일치";
        }
        return {...item}
      });
      
      this.excelDownAble = true;
    },

    async verificationExcel() {
      let today = moment().format('YYYYMMDDHHmmss');
      const saveFileName = `청구 검증(${moment(this.lmtYm).format('YYYY-MM')})_${today}.xls`;

      if (!this.excelDownAble) {
        this.row.title = '청구 검증 엑셀 다운로드';
        this.row.msg1 = '청구 검증을 먼저 실행해 주세요.';
        this.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }

      let options = {
        header: this.excelHeader,
        dataOrder: 'header',
      };
      
      xlsx.export(this.list, saveFileName, options).then(() => {});
    },
    jusoCallBack(roadFullAddr, roadAddrPart1, addrDetail, roadAddrPart2, engAddr, jibunAddr, zipNo, admCd, rnMgtSn, bdMgtSn){
      // 도로명주소검색팝업창에서 결과를 리턴하는 스크립트로 빨간 라인은 해당 시스템에 맞게 수정하여 사용
      //2017년 2월 제공항목이 확대되었습니다. 원하시는 항목을 추가하여 사용하시면 됩니다.
      console.log(roadFullAddr, roadAddrPart1, addrDetail, roadAddrPart2, engAddr, jibunAddr, zipNo, admCd, rnMgtSn, bdMgtSn);
    }
  }
};
</script>
