<template>
    <div class="app-container">
    <el-row :gutter="10">
            <el-col :span="22" :xs="24">
        <el-card>
          <div slot="header" class="clearfix">
            <span>上传付款</span>
          </div>
          <div class="form">
                <el-form :rules="rules" ref="form" :model="form" label-width="100px" style="width:100%">
                    <el-form-item label="上报年月：" prop="dateregion" style="margin-bottom:30px">
                        <el-date-picker
                          v-model="form.dateregion"
                          @change="yearMonthChange"
                          value-format="yyyyMM"
                          type="month"
                          placeholder="选择月">
                        </el-date-picker>
                        <span style="padding-left:8%;font-size:16px;line-height:16px">起日:{{from}}</span>
                        <span style="padding-left:3%;font-size:16px;line-height:16px">止日:{{to}}</span>
                        <span style="padding-left:6%;font-size:16px;line-height:16px">状态: &nbsp; &nbsp; <span style="padding-left:2%;font-size:16px;line-height:16px;color:red">{{cashOutUploadStatus}}</span>&nbsp;</span>
                    </el-form-item>
                <el-button type="primary" :underline="false" style="vertical-align: baseline;" @click="importTemplate">点击下载付款表模板</el-button>
                <el-upload
                  class="upload-demo"
                  :multiple="false"
                  action="#"
                  :limit="1"
                  :on-exceed="handleUploadExceed"
                  accept=".xlsx"
                  :auto-upload="false"
                  :on-change="handleUploadChange"
                  :on-remove="handleUploadRemove"
                  drag>
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将收入文件拖到此处，或<em>点击上传</em></div>
                  <div class="el-upload__tip" slot="tip">只能上传xlsx文件</div>
                </el-upload>
                <el-form-item  style="margin-top:30px" size="large" label-width="0px">
                  <el-popconfirm
                    confirm-button-text='确定'
                    cancel-button-text='等一下再说'
                    icon="el-icon-info"
                    icon-color="black"
                    @confirm="submitForm('form')"
                    title="确定要上传付款吗？"
                  >
                    <el-button slot="reference" type="primary" :disabled="sumitCashOutDisabled">提交付款</el-button>
                  </el-popconfirm>
                </el-form-item>
              </el-form>
              <div id="message" style="font-size:18px;color:red;margin-bottom:4%;border:1px dashed red"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    </div>
</template>



<script>
import { getProject } from "@/api/daily/daily";
import { setCashOutInfo,getCashOutUploadStatus } from '@/api/finance/CashOut/cashOut'
import { HaveSingleSheetName,HaveData3Para,import_excel_to_json,makeCashOutJSONstring,checkCashOutFile } from "@/api/check.xlsx.full";
import Cookies from "js-cookie";
import { Loading } from 'element-ui'
let cashOutUploadLoadingInstance;

export default {
    data(){
        return{
        data:"",
        from:"",
        to:"",
        file:{},
        cashOutUploadStatus:"请先选择年月",
        sumitCashOutDisabled:false,
        form:{
            dateregion:""
        },
        projectFrom:[],
        rules: {
          dateregion: [
            { required: true, message: '请选择上传年月', trigger: 'change' },
          ]
        }
    }
},
created(){
  this.getProject();
},
methods:{
  getProject(){
      const userId = Cookies.get("username");
      getProject(userId).then(response =>{
        this.projectFrom =  response.project;
      })
  },
  submitForm(formName){
      document.getElementById("message").innerHTML = "";
      this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.file == {} || this.file == null || this.file.name == "" || this.file.name == null){
              this.$message({
                  showClose: true,
                  message: '请先上传付款表文件',
                  type: 'error'
                });
            }else{
            if (!/\.xlsx$/g.test(this.file.name)) {
              this.$message({
                  showClose: true,
                  message: '仅支持读取xlsx格式文件！',
                  type: 'error'
                });
            }else{
            var userName = Cookies.get("username");
            let data = this.file.raw;
            import_excel_to_json(data).then(res => {
              let workbook = res;
             if (HaveSingleSheetName(workbook,"FK") != true){
                               document.getElementById('message').innerHTML += HaveSingleSheetName(workbook,"FK");
                               return;
                             };

                          if (HaveData3Para(workbook,"FK","H1") != true){
                            document.getElementById('message').innerHTML += HaveData3Para(workbook,"FK","H1")
                            return;
                          };
                          //checkBalanceFile(workbook,logID,strStartDate,strEndDate,userID)
                          checkCashOutFile(workbook,"message",this.from,this.to,userName);
                         // if (document.getElementById('TextBox3').innerHTML == ""&&document.getElementById('FileUpload1').value != "") {                           
                         //     document.getElementById('Button1').disabled =false;
                              //alert("pass!")                             
                        //  }


            if(document.getElementById("message").innerHTML == null || document.getElementById("message").innerHTML == ""){
              this.$message({
                  showClose: true,
                  message: '付款表文件数据校验通过！',
                  type: 'success'
                });
                cashOutUploadLoadingInstance = Loading.service({ text: "正在上传付款表，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
              this.jsona = makeCashOutJSONstring(workbook);
              setCashOutInfo(this.jsona,userName,this.projectFrom[0].slice(0,5),this.date).then(res => {
                if(res.msg == "操作成功"){
                  cashOutUploadLoadingInstance.close();
                  this.$message({
                  showClose: true,
                  message: '上传付款表成功！',
                  type: 'success'
                  });
                  this.yearMonthChange();
                }else{
                  cashOutUploadLoadingInstance.close();
                  this.$message({
                  showClose: true,
                  message: '上传失败，请联系管理员！',
                  type: 'error'
                  });
                  this.yearMonthChange();
                }
              })
            }else{
              cashOutUploadLoadingInstance.close();
              this.$message({
                  showClose: true,
                  message: '付款表文件数据校验不通过！请参考底部错误日志栏！',
                  type: 'error'
                });
            }

            });
            }}
          } else {
            return false;
          }
        });
  },
  yearMonthChange(){
    this.date = this.form.dateregion;
    this.from = this.dateFormat("YYYY-mm-dd",new Date(this.form.dateregion.slice(0,4), this.form.dateregion.slice(4,6)-1, 1));
    this.to = this.dateFormat("YYYY-mm-dd",new Date(this.form.dateregion.slice(0,4), this.form.dateregion.slice(4,6), 0));
    document.getElementById("message").innerHTML = "";
    if(this.form.dateregion != "" && this.form.dateregion != null){
      getCashOutUploadStatus(Cookies.get("username"),this.projectFrom[0].slice(0,5),this.form.dateregion).then(res => {
        if(res.msg != null){
          this.$message({
                showClose: true,
                message: '本月的付款已上传，无法再次上传！',
                type: 'error'
              });
          this.sumitCashOutDisabled = true;
          this.cashOutUploadStatus = "已上传";
        }else{
          this.$message({
                showClose: true,
                message: '本月的付款未上传，可以上传！',
                type: 'success'
              });
          this.sumitCashOutDisabled = false;
          this.cashOutUploadStatus = "未上传";
        }
      });
    }
  },
  handleUploadExceed(){
      this.$message({
                showClose: true,
                message: '超过最大上传文件数量，操作失败！',
                type: 'error'
      });
  },
  handleUploadChange(file,filelist){
      this.file = file;
  },
  handleUploadRemove(file,filelist){
    this.file = {};
  },
  dateFormat(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
  },
  /** 下载模板操作 */
  importTemplate() {
    this.download('/finance/cashOut/CashOutDownload', {
    },'付款表模板'+'_'+Cookies.get("username")+'.xlsx')
  },
}
}
</script>