<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:45%">
                    <el-form-item label="上报年月：" prop="dateregion" style="margin-bottom:30px">
                        <el-date-picker
                          v-model="form.dateregion"
                          @change="yearMonthChange"
                          type="month"
                          value-format="yyyyMM"
                          placeholder="选择月">
                        </el-date-picker>
                        <span style="padding-left:11%;font-size:16px;line-height:16px">状态: &nbsp; &nbsp; <span style="padding-left:2%;font-size:16px;line-height:16px;color:red">{{salaryUploadStatus}}</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" :loading="btnloading" type="primary" :disabled="sumitSalaryDisabled">提交工资</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 { setSalaryInfo,getSalaryUploadStatus } from '@/api/finance/salary/salary'
import { HaveSingleSheetName,HaveData3Para,import_excel_to_json,checkSalaryFile,makeSalaryJSONstring } from "@/api/check.xlsx.full";
import Cookies from "js-cookie";

import { Loading } from 'element-ui'
let salaryUploadLoadingInstance;
export default {
    data(){
        return{
        value2:"",
        form:{
          dateregion:""
        },
        file:{},
        sumitSalaryDisabled:false,
        salaryUploadStatus:"请先选择年月",
        projectFrom:[],
        btnloading:false,
        rules: {
          dateregion: [
            { required: true, message: '请选择上传年月', trigger: 'change' },
          ]
        }
    }
},
created(){
  this.getProject();
},
methods:{
  yearMonthChange(){
    document.getElementById("message").innerHTML = "";
    if(this.form.dateregion != "" && this.form.dateregion != null){
      getSalaryUploadStatus(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.sumitSalaryDisabled = true;
          this.salaryUploadStatus = "已上传";
        }else{
          this.$message({
                showClose: true,
                message: '本月的工资未上传，可以上传！',
                type: 'success'
              });
          this.sumitSalaryDisabled = false;
          this.salaryUploadStatus = "未上传";
        }
      });
    }
  },
  //获取项目编号
  getProject(){
      const userId = Cookies.get("username");
      getProject(userId).then(response =>{
        this.projectFrom =  response.project;
      })
  },
  handleUploadExceed(){
      this.$message({
                showClose: true,
                message: '超过最大上传文件数量，操作失败！',
                type: 'error'
      });
  },
  handleUploadChange(file,filelist){
      this.file = file;
  },
  handleUploadRemove(file,filelist){
    this.file = {};
  },
  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,"CGZ") != true){
                               document.getElementById('message').innerHTML += HaveSingleSheetName(workbook,"CGZ");
                               return;
                             };

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

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

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

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

            });
            }}
          } else {
            return false;
          }
        });
  },
  /** 下载模板操作 */
  importTemplate() {
    this.download('/finance/salary/Salarydownload', {
    },'每月工资表模板'+'_'+Cookies.get("username")+'.xlsx')
  },
}
}
</script>