<template>
    <div class="app-container">
    <el-row :gutter="10">
            <el-col :span="22" :xs="24">
        <el-card>
          <div slot="header" class="clearfix">
            <span>上传B16-B19</span>
          </div>
          <div class="form">
                <el-form ref="form" :model="form" label-width="100px" style="width:100%">
                <el-button type="primary" :underline="false" style="vertical-align: baseline;" @click="importTemplate">点击下载B16-B19表模板</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="确定要上传B16-B19表吗？"
                  >
                    <el-button slot="reference" type="primary" :disabled="sumitCashOutDisabled">提交B16-B19表</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,getNowDate } from "@/api/daily/daily";
import { setB16ToB19Info } from '@/api/finance/B16ToB19/B16-B19'
import { HaveSingleSheetName,HaveData3Para,import_excel_to_json,checkB16toB19File,makeB16toB19JSONstring } from "@/api/check.xlsx.full";
import Cookies from "js-cookie";

import { Loading } from 'element-ui'
let b16tob19UploadLoadingInstance;

export default {
    data(){
        return{
        file:{},
        ServerDate:"",
        sumitCashOutDisabled:false,
        projectFrom:[]
    }
},
created(){
  this.getNow();
  this.getProject();
},
methods:{
  getNow() {
    var nowDate = new Date();
    this.SystemDate = this.dateFormat("YYYY-mm-dd",nowDate);
    getNowDate().then(response =>{
      this.ServerDate = response.data;
    })
  },
  getProject(){
      const userId = Cookies.get("username");
      getProject(userId).then(response =>{
        this.projectFrom =  response.project;
      })
  },
  submitForm(formName){
      document.getElementById("message").innerHTML = "";
            if(this.file == {} || this.file == null || this.file.name == "" || this.file.name == null){
              this.$message({
                  showClose: true,
                  message: '请先上传B16-B19表文件',
                  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,"B16") != true){
                               document.getElementById('message').innerHTML += HaveSingleSheetName(workbook,"B16");
                               return;
          };

          if (HaveSingleSheetName(workbook,"B17") != true){
            document.getElementById('message').innerHTML += HaveSingleSheetName(workbook,"B17");
            return;
          };

          if (HaveSingleSheetName(workbook,"B18") != true){
            document.getElementById('message').innerHTML += HaveSingleSheetName(workbook,"B18");
            return;
          };

          if (HaveSingleSheetName(workbook,"B19") != true){
            document.getElementById('message').innerHTML += HaveSingleSheetName(workbook,"B19");
            return;
          };

          if (HaveSingleSheetName(workbook,"C") != true){
            document.getElementById('message').innerHTML += HaveSingleSheetName(workbook,"C");
            return;
          };

              if (HaveData3Para(workbook,"C","C6") != true){
                document.getElementById('message').innerHTML += HaveData3Para(workbook,"C","C6")
                return;
              };
              //checkBalanceFile(workbook,logID,strStartDate,strEndDate,userID)
              b16tob19UploadLoadingInstance = Loading.service({ text: "正在上传B16-B19表，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
              checkB16toB19File(workbook,"message",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: 'B16-B19表文件数据校验通过！',
                  type: 'success'
                });
              this.jsona = makeB16toB19JSONstring(workbook);
              setB16ToB19Info(this.jsona,userName,this.projectFrom[0].slice(0,5),this.ServerDate).then(res => {
                if(res.msg == "操作成功"){
                  b16tob19UploadLoadingInstance.close();
                  this.$message({
                  showClose: true,
                  message: '上传B16-B19表成功！',
                  type: 'success'
                  });
                }else{
                  b16tob19UploadLoadingInstance.close();
                  this.$message({
                  showClose: true,
                  message: '上传失败，请联系管理员！',
                  type: 'error'
                  });
                }
              })
            }else{
              b16tob19UploadLoadingInstance.close();
              this.$message({
                  showClose: true,
                  message: 'B16-B19表文件数据校验不通过！请参考底部错误日志栏！',
                  type: 'error'
                });
            }

            });
            }}
},
  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/B16ToB19/B16ToB19Download', {
    },'每月B16_B19表模板'+'_'+Cookies.get("username")+'.xlsx')
  },
}
}
</script>