<!--
  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
                           default-first-option
-->
<!--
组成项目号的年份，不是取服务器日期的年份，因为最后几天可能，划到下年去，改为从期别表中查询
     ---by Paul 2023-1-3
-->

<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-tabs type="border-card">
              <el-tab-pane :label="ServerDate +' ' + todayUploadStatus + ' ' + belongWeekNum" >
                <el-result
                  v-if="todayUploadStatus == '已上传'"
                  icon="success"
                  title="已成功上传"
                  subTitle="如有问题请联系网站管理人员"
                >
                </el-result>
                <el-form
                  v-if="this.todayUploadStatus != '已上传'"
                  :rules="rules"
                  ref="form"
                  :model="form"
                  label-width="100px"
                  style="width: 45%"
                >

                  <el-form-item
                    label="项目归属："
                    prop="region"
                    style="margin-bottom: 30px"
                  >
                    <el-select
                      v-model="form.region"
                      placeholder="请选择项目归属"
                      allow-create
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item of projectFrom"
                        :key="item"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </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="todayUploadBtnStatus"
                        >提交日报</el-button
                      >
                    </el-popconfirm>
                  </el-form-item>
                </el-form>
                <div id="message" style="font-size: 17px; color: red"></div>
              </el-tab-pane>
              <el-tab-pane :label="ServerLastDate + ' ' + yestodayUploadStatus  + ' ' + belongWeekNum2">
                <el-result
                  v-if="yestodayUploadStatus == '已上传'"
                  icon="success"
                  title="已成功上传"
                  subTitle="如有问题请联系网站管理人员"
                >
                </el-result>
                <el-form
                  v-if="this.yestodayUploadStatus != '已上传'"
                  :rules="rules"
                  ref="yesform"
                  :model="yesform"
                  label-width="100px"
                  style="width: 45%"
                >
                  <el-form-item
                    label="项目归属："
                    prop="region"
                    style="margin-bottom: 30px"
                  >
                    <el-select
                      v-model="yesform.region"
                      placeholder="请选择项目归属"
                      allow-create
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item of projectFrom2"
                        :key="item"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </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="handleUploadChange2"
                    :on-remove="handleUploadRemove2"
                    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="submitForm2('yesform')"
                      title="确定要上传日报吗？"
                    >
                      <el-button
                        slot="reference"
                        :loading="btnloading2"
                        type="primary"
                        :disabled="yestodayUploadBtnStatus"
                        >提交日报</el-button
                      >
                    </el-popconfirm>
                  </el-form-item>
                </el-form>
                <div id="message2" style="font-size: 18px; color: red"></div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-card>
        <h3 style="color: red">当前日报模板,版本为:2022-11-11,请下载使用新模板!</h3>
      </el-col>
    </el-row>
  </div>
</template>

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

export default {
  name: "Index",
  data() {
    return {
      textarea: "",
      todayUploadStatus: "",
      yestodayUploadStatus: "",
      todayUploadBtnStatus: false,
      yestodayUploadBtnStatus: false,
      file: {},
      file2: {},
      btnloading1: false,
      btnloading2: false,
      jsona: "",
      jsona2: "",
      SystemDate: "",
      ServerDate: "",
      ServerLastDate: "",
      belongWeekNum:"",
      belongWeekNum2:"",
      form: {
        region: "",
      },
      projectFrom: [],
      projectFrom2: [],
      yesform: {
        region: "",
      },
      rules: {
        region: [
          { required: true, message: "请选择项目编号", trigger: "change" },
          { min: 10, max: 70, message: "请输入正确的项目编号" },
        ],
      },
    };
  },
  created() {
    this.getNow();
    this.getStatus();
    this.getWeekInfo();
    this.getWeekInfo2();
    //this.getProject();//先不用这个了，不用每次从后台取了
    //this.getProjectIDFromCookie();
  },

 // mounted() {
 //   setTimeout(()=>{
       //这里就写你要执行的语句即可，先让数据库的数据加载进去数组中你在从数组中取值就好了
        //this.form.region = this.projectFrom;
       // console.log(this.projectFrom);
       // this.getProjectIDFromCookie();
       // this.form.region =  this.projectFrom[0];
      //  this.yesform.region =  this.projectFrom[0];
 //   },1000)//这样使用，解决 {__ob__: Observer }，
// },

//watch，也可以解决 {__ob__: Observer }，不用延时等了
 watch:{
  belongWeekNum(val){
   // console.log(val);
        this.getProjectIDFromCookie();
        this.form.region =  this.projectFrom[0];
  },
  belongWeekNum2(val){
   // console.log(val);
        this.getProjectIDFromCookie2();
        this.yesform.region =  this.projectFrom2[0];
  },
  immediate: true,
  deep: false
 },
  methods: {
    getWeekInfo(){
      getWeekInfo().then(response =>{
          this.belongWeekNum = response.data.belongWeekNum;
      })
    },
    getWeekInfo2(){
      getWeekInfo2().then(response =>{
          this.belongWeekNum2 = response.data.belongWeekNum;
      })
    },
    handleUploadChange(file, filelist) {
      this.file = file;
    },
    handleUploadChange2(file, filelist) {
      this.file2 = file;
    },
    handleUploadRemove(file, filelist) {
      this.file = {};
    },
    handleUploadRemove2(file, filelist) {
      this.file2 = {};
    },
    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.ServerDate;
              var userId = Cookies.get("id");
              var userName = Cookies.get("username");
              var unitID = this.projectFrom[0].slice(0, 5);
              var projectID = this.form.region;
              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,
                    userName,
                    projectID,
                    ServerDate
                  ).then((res) => {
                    if (res.msg == "操作成功") {
                      setDailyStatus(userId, projectID, ServerDate).then(
                        (res) => {
                          if (res.msg == "操作成功") {
                            this.btnloading1 = false;
                            dailyUploadLoadingInstance.close();
                            this.$message({
                              showClose: true,
                              message: "日报上传成功！",
                              type: "success",
                            });
                            this.getStatus();
                            document.getElementById("message").innerHTML = "";
                          } 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 {
                  this.btnloading1 = false;
                  dailyUploadLoadingInstance.close();
                  this.$message({
                    showClose: true,
                    message: "日报文件数据校验不通过！请参考底部错误日志栏！",
                    type: "error",
                  });
                }
              });
            }
          }
        } else {
          return false;
        }
      });
    },
    submitForm2(formName) {
      document.getElementById("message2").innerHTML = "";
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (
            this.file2 == {} ||
            this.file2 == null ||
            this.file2.name == "" ||
            this.file2.name == null
          ) {
            this.$message({
              showClose: true,
              message: "请先上传昨天的日报文件",
              type: "error",
            });
          } else {
            if (!/\.xlsx$/g.test(this.file2.name)) {
              this.$message({
                showClose: true,
                message: "仅支持读取xlsx格式！",
                type: "error",
              });
            } else {
              var ServerDate = this.ServerLastDate;
              var userId = Cookies.get("id");
              var userName = Cookies.get("username");
              var unitID = this.projectFrom[0].slice(0, 5);
              var projectID = this.yesform.region;
              let data = this.file2.raw;
              import_excel_to_json(data).then((res) => {
                let workbook = res;
                if (SheetAmount(workbook) != true) {
                  document.getElementById("message2").innerHTML =
                    SheetAmount(workbook);
                  return;
                }

                if (HaveSheets(workbook) != true) {
                  // errorFlag = HaveSheets(workbook);
                  document.getElementById("message2").innerHTML =
                    HaveSheets(workbook);
                  return;
                }

                if (HaveData3Para(workbook, "C", "C16") != true) {
                  document.getElementById("message2").innerHTML = HaveData3Para(
                    workbook,
                    "C",
                    "C16"
                  );
                  //  errorFlag = HaveDatas(workbook);
                  return;
                }
                this.btnloading2 = true;
                dailyUploadLoadingInstance = Loading.service({
                  text: "正在上传日报，请稍候",
                  spinner: "el-icon-loading",
                  background: "rgba(0, 0, 0, 0.7)",
                });
                readWorkbook(
                  workbook,
                  "message2",
                  ServerDate,
                  userName,
                  unitID,
                  projectID
                );
                // if (document.getElementById('TextBox3').innerHTML == ""&&document.getElementById('FileUpload1').value != "") {

                //     document.getElementById('Button1').disabled =false;
                //alert("pass!")
                //  }
                if (
                  document.getElementById("message2").innerHTML == null ||
                  document.getElementById("message2").innerHTML == ""
                ) {
                  this.$message({
                    showClose: true,
                    message: "日报文件数据校验通过！",
                    type: "success",
                  });
                  this.jsona = makeJSONstring(workbook);
                  setDailyInfo(this.jsona).then((res) => {
                    if (res.msg == "操作成功") {
                      setDailyStatus(userId, projectID, ServerDate).then(
                        (res) => {
                          if (res.msg == "操作成功") {
                            this.btnloading2 = false;
                            dailyUploadLoadingInstance.close();
                            this.$message({
                              showClose: true,
                              message: "日报上传成功！",
                              type: "success",
                            });
                            this.getStatus();
                            document.getElementById("message").innerHTML = "";
                          } else {
                            this.btnloading2 = false;
                            dailyUploadLoadingInstance.close();
                            this.$message({
                              showClose: true,
                              message: "上传失败，请联系管理员！",
                              type: "error",
                            });
                          }
                        }
                      );
                    } else {
                      this.btnloading2 = false;
                            dailyUploadLoadingInstance.close();
                            this.$message({
                              showClose: true,
                              message: "上传失败，请联系管理员！",
                              type: "error",
                            });
                    }
                  });
                } else {
                  this.btnloading2 = 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() {
      const userId = Cookies.get("id");
      getStatus(userId).then((response) => {
        this.todayUploadStatus = response.data;
        this.yestodayUploadStatus = response.data1;
        if (this.todayUploadStatus !== null && this.todayUploadStatus !== "2") {
          this.todayUploadStatus = "已上传";
          this.todayUploadBtnStatus = true;
        } else {
          this.todayUploadStatus = "未上传";
        }
        if (
          this.yestodayUploadStatus !== null &&
          this.yestodayUploadStatus !== "2"
        ) {
          this.yestodayUploadStatus = "已上传";
          this.yestodayUploadBtnStatus = true;
        } else {
          this.yestodayUploadStatus = "未上传";
        }
      });
    },
    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.belongWeekNum.substr(0,4);
      }
    },
    getProjectIDFromCookie2() {
       const unitid = Cookies.get("unitid");
      //console.log(unitid);
      const arrunitid = unitid.split("|");
      //console.log(arrunitid);

      for (let index = 0; index < arrunitid.length; index++) {
        this.projectFrom2[index] = arrunitid[index]+"P" + this.belongWeekNum2.substr(0,4);
      }
    },
    //获取项目编号
    getProject() {
      const userId = Cookies.get("id");
      getProject(userId).then((response) => {
        this.projectFrom = response.project;
      });
    },
    // 提交上传文件
    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>
