<!-- 
  1.Not use old method  "getProject",use new "getProjectIDFromCookie",
    new not request from mysql.

     ---by Paul 2022-11-13
-->
<!-- 
//watch，也可以解决 {__ob__: Observer }，不用延时等了

     ---by Paul 2022-11-18
-->

<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="date">
            <span style="padding-left:0%">本机日期：</span><span>{{SystemDate}}</span>
            <span style="padding-left:5%">服务器日期：</span><span>{{ServerDate}}</span>
          </div>
          <div class="form">
              <el-form  :rules="rules" ref="form" :model="form" inline style="width:100%" >
                <el-form-item label="当前帐号：" prop="userId">
                    <el-input clearable v-model="form.userId" v-if="isAdmin"></el-input>
                    <el-input clearable :value="form.userId" v-else></el-input>
                </el-form-item>
                <el-form-item label="选日期" prop="dateAt">
                    <el-date-picker
                        v-if="isAdmin"
                        v-model="form.dateAt"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期">
                    </el-date-picker>

                    <el-select v-model="form.dateAt" :placeholder="hint" v-else>
                      <el-option
                        v-for="item in options"
                        :key="item"
                        :label="item"
                        :value="item">
                      </el-option>
                    </el-select>
                </el-form-item>
                      <el-form-item label="项目号" prop="projectId" style="margin-bottom:30px">
                              <el-select
                              v-model="form.projectId"
                              placeholder="请选择项目归属"
                              allow-create
                              clearable
                              default-first-option
                              filterable>
                                <el-option
                                v-for="item of projectFrom"
                                  :key="item"
                                  :label="item"
                                  :value="item"
                                />
                              </el-select>
                      </el-form-item>
                <el-button @click="getStatus('form')" type="primary">查日报状态</el-button><span style="color:red">&nbsp;&nbsp;{{todayUploadStatus}}</span>
                <el-button type="primary" :underline="false" style="vertical-align: baseline;display:block;margin-top:25px" @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="reSubmitBtnStatus" >补交日报</el-button>
                  </el-popconfirm>
                </el-form-item>
              </el-form>
              <div id="message" style="font-size:17px;color:red"></div>
          </div>
        </el-card>
        <h3 style="color: red">如需授权,请钉钉联系：邱润琴 ,取得授权后,需当天操作！</h3>
        <h3 style="color: red">当前日报模板,版本为:2022-11-11,请下载使用新模板!</h3>
      </el-col>
    </el-row>
    </div>
</template>

<script>
import { getNowDate,getReSubmitStatus,setDailyStatus,setDailyInfo,queryBtn,queryDateList,setDailyRebStatus,getProject } from "@/api/daily/daily";
import { SheetAmount,HaveSheets,HaveData3Para,readWorkbook,makeJSONstring,import_excel_to_json } from "@/api/check.xlsx.full";
import Cookies from "js-cookie";
import { Loading } from 'element-ui'
let dailyUploadLoadingInstance;

export default {
  name: "Index",
  data() {
    return {
        isAdmin: Cookies.get('id') === 'X9000' ? true : false,
        timer: '',
        options:[],
        hint: "",
        todayUploadStatus:"请先查日报状态",
        reSubmitBtnStatus: true,
        reSubmitBtnStatusAuthorize: true,
        file:{},
        btnloading1:false,
        jsona:"",
        SystemDate : "",
        ServerDate : "",
        userUnit:"",
        projectFrom:[],
        form:{
            projectId:"",
            dateAt:'',
            userId:Cookies.get('id'),
        },
        queryprojectId:"",
        querydateAt:'',
        queryUserId:'',
        rules: {
          projectId: [
            { required: true, message: '请输入项目编号', trigger: 'blur' },
            { min: 10,max:10,message: '请输入正确的项目编号'}
          ],
          dateAt: [
            { required: true, message: '请选择日期', trigger: 'change' }
          ],
          userId:[
              { required: true, message: '请输入员工用户名', trigger: 'blur' },
              { min: 1,max:10,message: '请输入正确的员工用户名'}
          ]
        }
    };
  },
  created(){
      this.getNow();
      this.getStatus();
      clearTimeout(this.timer);
  },
/*   mounted() {
    setTimeout(()=>{
       //这里就写你要执行的语句即可，先让数据库的数据加载进去数组中你在从数组中取值就好了
        //this.form.region = this.projectFrom;
       // console.log(this.projectFrom); 
        //this.queryUnit();
        this.getProjectIDFromCookie();
        this.form.projectId = this.projectFrom[0];
    },1000)//这样使用，解决 {__ob__: Observer }，
 }, */
//watch，也可以解决 {__ob__: Observer }，不用延时等了
watch:{
  ServerDate(val){
   // console.log(val);
        this.queryDateList();
        this.getProjectIDFromCookie();
        this.form.projectId = this.projectFrom[0];
  },
  immediate: true,
  deep: false      
 },
  methods :{
    getProjectIDFromCookie() {
       const unitid = Cookies.get("unitid");
      //console.log(unitid);
      const arrunitid = unitid.split("|");
      //console.log(arrunitid);

      for (let index = 0; index < arrunitid.length; index++) {
        this.projectFrom[index] = arrunitid[index]+"P" + this.ServerDate.substr(0,4);
      }
    },
    // 根据cookie的用户民查找unit号
    queryUnit() {
      const userId = Cookies.get("id");
      getProject(userId).then(res => {
        // console.log(res);
        this.form.projectId = res.project[0]
      })
    },
    queryDateList(){
      const userId = Cookies.get("id");
      const perm = 'R08';
      queryDateList(userId, perm).then(res => {
        // console.log(res)
        if(res.msg === '下拉选择日期') {
          this.options = res.data
          this.hint = res.msg
        } else {
          this.hint = res.msg
        }
      })
    },
    // queryRebBtn(){
    //   const userId = Cookies.get("username");
    //   const perm = 'R08';
    //   const dateAt = this.form.dateAt;

    //   queryBtn(userId,perm,dateAt).then(res => {
    //     if(res.msg === '显示按钮') {
    //       this.reSubmitBtnStatusAuthorize = false
    //     } else {
    //       this.reSubmitBtnStatusAuthorize = true
    //     }
    //   })
    // },
    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 ServerDate = this.querydateAt;
            var userName = Cookies.get('username')
            var yuangongId = this.queryUserId;
            var unitID = this.userUnit.slice(0,5);
            var projectID = this.queryprojectId;
            let data = this.file.raw;
            import_excel_to_json(data).then(res => {
              let workbook = res;
              if (SheetAmount(workbook) != true){
                document.getElementById("message").innerHTML = SheetAmount(workbook);
                return;
              }
            
              if (HaveSheets(workbook) != true){
                // errorFlag = HaveSheets(workbook);
                document.getElementById("message").innerHTML = HaveSheets(workbook);
                return;
                }
            
              if (HaveData3Para(workbook,"C","C16") != true){
                document.getElementById("message").innerHTML = HaveData3Para(workbook,"C","C16");
              //  errorFlag = HaveDatas(workbook);
               return;
              }
            this.btnloading1 = true;
            dailyUploadLoadingInstance = Loading.service({ text: "正在上传日报，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
            readWorkbook(workbook,"message",ServerDate,userName,unitID,projectID);
             // 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 = makeJSONstring(workbook);
              setDailyInfo(this.jsona).then(res =>{
                if(res.msg == "操作成功"){
                  if(Cookies.get('id') === 'X9000') {
                    setDailyStatus(yuangongId,projectID,ServerDate).then(res =>{

                      if(res.msg == "操作成功"){
                        this.btnloading1 = false;
                        dailyUploadLoadingInstance.close();
                        this.$message({
                          showClose: true,
                          message: '日报上传成功！',
                          type: 'success'
                        });
                        // this.getStatus('form');
                        this.form.projectId = "";
                        this.form.dateAt = "";
                        this.form.userId = "";
                        this.todayUploadStatus = "请先查询日报状态";
                        document.getElementById("message").innerHTML = "";
                      } else if(res.msg === '该用户暂未授权') {
                        this.btnloading1 = false;
                        dailyUploadLoadingInstance.close();
                        this.$message({
                          showClose: true,
                          message: res.msg,
                          type: 'warning'
                        });
                      } else if(res.msg === '该用户今日次数已用完') {
                        this.btnloading1 = false;
                        dailyUploadLoadingInstance.close();
                        this.$message({
                          showClose: true,
                          message: res.msg,
                          type: 'warning'
                        });
                      } else{
                        this.btnloading1 = false;
                        dailyUploadLoadingInstance.close();
                        this.$message({
                          showClose: true,
                          message: '上传失败，请联系管理员！',
                          type: 'error'
                        });
                      }
                    });
                  } else {
                    setDailyRebStatus(yuangongId,projectID,ServerDate).then(res =>{

                      if(res.msg == "操作成功"){
                        this.btnloading1 = false;
                        dailyUploadLoadingInstance.close();
                        this.$message({
                          showClose: true,
                          message: '日报上传成功！',
                          type: 'success'
                        });
                        // this.getStatus('form');
                        this.form.projectId = "";
                        this.form.dateAt = "";
                        this.form.userId = "";
                        this.todayUploadStatus = "请先查询日报状态";
                        document.getElementById("message").innerHTML = "";
                      } else if(res.msg === '该用户暂未授权') {
                        this.btnloading1 = false;
                        dailyUploadLoadingInstance.close();
                        this.$message({
                          showClose: true,
                          message: res.msg,
                          type: 'warning'
                        });
                      } else if(res.msg === '该用户今日次数已用完') {
                        this.btnloading1 = false;
                        dailyUploadLoadingInstance.close();
                        this.$message({
                          showClose: true,
                          message: res.msg,
                          type: 'warning'
                        });
                      } else{
                        this.btnloading1 = false;
                        dailyUploadLoadingInstance.close();
                        this.$message({
                          showClose: true,
                          message: '上传失败，请联系管理员！',
                          type: 'error'
                        });
                      }
                    });
                  }
                  
                  this.timer = setTimeout(() => {
                    location.reload();
                  }, 2000)
                  
                }else{
                  this.btnloading1 = false;
                          dailyUploadLoadingInstance.close();
                  this.$message({
                  showClose: true,
                  message: '上传失败，请联系管理员！',
                  type: 'error'
              });
                }
              })
            }else{
              this.btnloading1 = false;
              dailyUploadLoadingInstance.close();
              this.$message({
                  showClose: true,
                  message: '日报文件数据校验不通过！请参考底部错误日志栏！',
                  type: 'error'
                });
            }
            });
            }}
           } else {
            return false;
          }
        });
    },
      handleUploadExceed(){
        this.$message({
                  showClose: true,
                  message: '超过最大上传文件数量，操作失败！',
                  type: 'error'
                });
      },
      getNow() {
          var nowDate = new Date();
          this.SystemDate = this.dateFormat("YYYY-mm-dd",nowDate);
          getNowDate().then(response =>{
            this.ServerDate = response.data;
            this.ServerLastDate = response.data1;
          })
  },
  getStatus(form){
    this.$refs[form].validate((valid) => {
      if (valid) {
        this.queryprojectId = this.form.projectId;
        this.queryUserId = this.form.userId;
        this.querydateAt = this.form.dateAt;
        getReSubmitStatus(this.queryUserId,this.querydateAt,this.queryprojectId).then(response =>{
          this.todayUploadStatus = response.data;
          this.userUnit = response.data1;
          if(this.userUnit === ""){
            this.$message({
              showClose: true,
              message: '该员工不存在，请检查后输入！',
              type: 'error'
            });
            this.todayUploadStatus = "请输入正确员工名";
            this.reSubmitBtnStatus = true;
          }else{
            if(this.todayUploadStatus === "0" || this.todayUploadStatus === "1"){
              this.todayUploadStatus = "已上传";
              this.reSubmitBtnStatus = true;
              this.$message({
                  showClose: true,
                  message: '当日日报已上传，请先删除后再补交!',
                  type: 'error'
              });
            }else{
              this.todayUploadStatus = "未上传";
              this.reSubmitBtnStatus = false;
              this.$message({
                  showClose: true,
                  message: '当日日报未上传，可以补交!',
                  type: 'success'
              });
            }
          }
        })
      }else{
        return false;
      }
    });
  },
  // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    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('/daily/download', {
      },'日报模板'+'_'+Cookies.get("username")+"_"+this.ServerDate+'.xlsx')
    },
}
}
</script>

<style>
.date{
  margin-bottom: 35px;
  margin-top: 25px;
}
</style>