<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="yearMonth" style="margin-bottom:30px">
                        <el-date-picker
                          v-model="form.yearMonth"
                          type="month"
                          @change="yearMonthChange"
                          value-format="yyyyMM"
                          placeholder="选择月">
                        </el-date-picker>
                        <span style="padding-left:5%;font-size:15px">起日：{{from}}&nbsp;&nbsp;&nbsp;</span><span style="padding-left:5%;font-size:15px">止日：{{to}}</span><span style="padding-left:5%;font-size:15px">状态：&nbsp;&nbsp;&nbsp;</span><span style="padding-left:1%;color:red">{{BalanceUploadStatus}}</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" :loading="btnloading1" type="primary" :disabled="sumitBalanceDisabled">提交支援</el-button>
                  </el-popconfirm>
                </el-form-item>
              </el-form>
              <div id="message" style="font-size:18px;color:red"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    </div>
</template>


<script>
import { HaveSingleSheetName,HaveData3Para,import_excel_to_json,checkBalanceFile,makeBalanceJSONstring } from "@/api/check.xlsx.full";
import {setBalanceInfo,getBalanceUploadStatus} from "@/api/income/balance"
import { getProject } from "@/api/daily/daily";
import Cookies from "js-cookie";

import { Loading } from 'element-ui'
let balanceUploadLoadingInstance;
export default {
    data(){
        return{
        form:{
            yearMonth:""
        },
        projectFrom:[],
        sumitBalanceDisabled:false,
        BalanceUploadStatus:"请先选择年月",
        from:"",
        to:"",
        yesform:{
            region:""
        },
        file:{},
        rules: {
          yearMonth: [
            { required: true, message: '请选择上传年月', trigger: 'change' },
          ]
        }
    }
},
created(){
  this.getProject();
},
methods:{
  yearMonthChange(){
    if(this.form.yearMonth != "" && this.form.yearMonth != null){
      getBalanceUploadStatus(Cookies.get("id"),this.projectFrom[0].toString().slice(0,5),this.form.yearMonth).then(res => {
        if(res.msg == "1"){
          this.$message({
                showClose: true,
                message: '本月的支援已上传，无法再次上传！',
                type: 'error'
              });
          this.sumitBalanceDisabled = true;
          this.BalanceUploadStatus = "已上传";
        }else{
          this.$message({
                showClose: true,
                message: '本月的支援未上传，可以上传！',
                type: 'success'
              });
          this.sumitBalanceDisabled = false;
          this.BalanceUploadStatus = "未上传";
        }
      });
    }
    this.from = this.dateFormat("YYYY-mm-dd",new Date(this.form.yearMonth.slice(0,4), this.form.yearMonth.slice(4,6)-1, 1));
    this.to = this.dateFormat("YYYY-mm-dd",new Date(this.form.yearMonth.slice(0,4), this.form.yearMonth.slice(4,6), 0));
  },
        handleUploadRemove(file,filelist){
      this.file = {};
    },
    handleUploadChange(file,filelist){
      this.file = file;
    },
    handleUploadExceed(){
      this.$message({
                showClose: true,
                message: '超过最大上传文件数量，操作失败！',
                type: 'error'
              });
    },
    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");
            var userId = Cookies.get("id");
            let data = this.file.raw;
            var unitID = this.projectFrom[0].toString().slice(0,5);
            import_excel_to_json(data).then(res => {
              let workbook = res;
              if (HaveSingleSheetName(workbook,"GRZY") != true){
                      document.getElementById('message').innerHTML += HaveSingleSheetName(workbook,"GRZY");
                      return;
                    };
                    if (HaveSingleSheetName(workbook,"JJZY") != true){
                      document.getElementById('message').innerHTML += HaveSingleSheetName(workbook,"JJZY");
                      return;
                    };
                    if (HaveSingleSheetName(workbook,"C") != true){
                      document.getElementById('message').innerHTML += HaveSingleSheetName(workbook,"C");
                      return;
                    };

                 if (HaveData3Para(workbook,"C","C4") != true){
                   document.getElementById('message').innerHTML += HaveData3Para(workbook,"C","C4");
                   return;
                 };
                 //checkBalanceFile(workbook,logID,strStartDate,strEndDate,userID)
                 balanceUploadLoadingInstance = Loading.service({ text: "正在上传支援，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
                checkBalanceFile(workbook,"message",this.from,this.to,userName);
                // if (document.getElementById('TextBox3').innerHTML == ""&&document.getElementById('FileUpload1').value != "") {                           
                //     document.getElementById('Button1').disabled =false;
                     //alert("pass!")                             
               //  }
              // console.log(makeBalanceJSONstring(workbook));
            // alert(makeIncomeJSONstring(workbook));
             // 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'
                });
              this.jsona = makeBalanceJSONstring(workbook);
              setBalanceInfo(this.jsona,userId,unitID,this.form.yearMonth).then(res =>{
                if(res.msg == "操作成功"){
                  // setDailyStatus(userName,projectID,ServerDate).then(res =>{
                  //     if(res.msg == "操作成功"){
                  //         this.uploadBtnLoading = false;
                  //         this.$message({
                  //           showClose: true,
                  //           message: '日报上传成功！',
                  //           type: 'success'
                  //     });
                  //     this.getStatus();
                  //     document.getElementById("message").innerHTML = "";
                  //     }else{
                  //       this.$message({
                  //         showClose: true,
                  //         message: '上传失败，请联系管理员！',
                  //         type: 'error'
                  //     });
                  //     }
                  // });
                  balanceUploadLoadingInstance.close();
                  this.yearMonthChange();
                  this.$message({
                  showClose: true,
                  message: '上传支援表成功！',
                  type: 'success'
                  });
                }else{
                  balanceUploadLoadingInstance.close();
                  this.$message({
                  showClose: true,
                  message: '上传失败，请联系管理员！',
                  type: 'error'
                  });
                }
              })
            }else{
              balanceUploadLoadingInstance.close();
              this.$message({
                  showClose: true,
                  message: '支援表文件数据校验不通过！请参考底部错误日志栏！',
                  type: 'error'
                });
            }

            });
            }}
          } else {
            return false;
          }
        });
    },
      //获取项目编号
  getProject(){
      const userId = Cookies.get("id");
      getProject(userId).then(response =>{
        this.projectFrom =  response.project;
      })
  },
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('/income/balancedownload', {
      },'每月支援表模板'+'_'+Cookies.get("username")+"_"+this.dateFormat("YYYYmm",new Date())+'.xlsx')
    },

}
}
</script>