<!-- 
  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-form>
              <el-button type="danger" @click="dialogVisible = true" :disabled="delBtnStatus" style="margin-left:78%">删除日报</el-button>
              <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="36%">
                <span>确定删除员工 <strong>{{this.queryUserId}}</strong> 在 <strong>{{this.querydateAt}}</strong> 提交的日报，项目号为 <strong>{{this.queryprojectId}}</strong></span>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="dialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="delDailyConfirm" :loading="delDailyBtnLoading">确 定</el-button>
                </span>
              </el-dialog>
          </div>
        </el-card>
        <h3 style="color: red">如需授权,请钉钉联系：邱润琴 ,取得授权后,需当天操作！</h3>

      </el-col>
    </el-row>
    </div>
</template>

<script>
import { getNowDate,getReSubmitStatus,delDaily,delAuthorizationDaily,queryBtn,queryDateList,getProject } from "@/api/daily/daily";
import Cookies from "js-cookie";

export default {
  name: "Index",
  data() {
    return {
        isAdmin: Cookies.get('username') === '迅网' ? true : false,
        timer: '',
        options:[],
        hint: "",
        todayUploadStatus:"请先查日报状态",
        reSubmitBtnStatus: true,
        dialogVisible:false,
        file:{},
        btnloading1:false,
        delBtnStatus:true,
        delBtnStatusAuthorize:true,
        delDailyBtnLoading:false,
        jsona:"",
        SystemDate : "",
        ServerDate : "",
        projectFrom:[],
        userUnit:"",
        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.queryDateList();
        //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 = 'R07';
      queryDateList(userId, perm).then(res => {
        // console.log(res)
        if(res.msg === '下拉选择日期') {
          this.options = res.data
          this.hint = res.msg
        } else {
          this.hint = res.msg
        }
      })
    },
    // queryDelBtn(){
    //   const userId = Cookies.get("username");
    //   const perm = 'R07';
    //   const dateAt = this.form.dateAt;
    //   queryBtn(userId,perm,dateAt).then(res => {
    //     if(res.msg === '显示按钮') {
    //       this.delBtnStatusAuthorize = false
    //     } else {
    //       this.delBtnStatusAuthorize = true
    //     }
    //   })
    // },
    delDailyConfirm(){
        this.delDailyBtnLoading = true;
        if(Cookies.get('id') === 'X9000') {
          // 超级管理员不需要验证权限
          delDaily(this.queryUserId,this.querydateAt,this.queryprojectId).then(res => {
            if(res.msg == "操作成功"){
              this.$message({
                    showClose: true,
                    message: '已成功删除选定日报信息！',
                    type: 'success'
              });
            } else if(res.msg === '该用户暂未授权') {
                this.$message({
                  showClose: true,
                  message: res.msg,
                  type: 'warning'
                });
            } else if(res.msg === '该用户今日次数已用完') {
                this.$message({
                  showClose: true,
                  message: res.msg,
                  type: 'warning'
                });
            } else{
                this.$message({
                      showClose: true,
                      message: '删除失败！',
                      type: 'error'
                });
            }
            this.delDailyBtnLoading = false;
            this.dialogVisible = false;
            this.form.userId = "";
            this.form.projectId = "";
            this.form.dateAt = "";
            this.reSubmitBtnStatus = true;
          })
        } else {
          delAuthorizationDaily(this.queryUserId,this.querydateAt,this.queryprojectId).then(res => {

            if(res.msg == "操作成功"){
              this.$message({
                    showClose: true,
                    message: '已成功删除选定日报信息！',
                    type: 'success'
              });
            } else if(res.msg === '该用户暂未授权') {
                this.$message({
                  showClose: true,
                  message: res.msg,
                  type: 'warning'
                });
            } else if(res.msg === '该用户今日次数已用完') {
                this.$message({
                  showClose: true,
                  message: res.msg,
                  type: 'warning'
                });
            } else{
                this.$message({
                      showClose: true,
                      message: '删除失败！',
                      type: 'error'
                });
            }
            this.delDailyBtnLoading = false;
            this.dialogVisible = false;
            this.form.userId = "";
            this.form.projectId = "";
            this.form.dateAt = "";
            this.reSubmitBtnStatus = true;
          })
        }
        
        this.timer = setTimeout(() => {
          location.reload();
        }, 2000)
    },
    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(formName){
      this.$refs[formName].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.delBtnStatus = true;
            }else{
                if(this.todayUploadStatus === "0" || this.todayUploadStatus === "1"){
                  this.todayUploadStatus = "已上传";
                  this.reSubmitBtnStatus = true;
                  this.$message({
                      showClose: true,
                      message: '当日日报已上传，可以删除!',
                      type: 'success'
                });
                this.delBtnStatus = false;
                }else{
                  this.todayUploadStatus = "未上传";
                  this.reSubmitBtnStatus = false;
                  this.$message({
                      showClose: true,
                      message: '当日日报未上传，不可删除!',
                      type: 'error'
                });
                this.delBtnStatus = true;
                }
            }
          })
        }else{
          return false;
        }
      })
    },
    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;
    }
  }
}
</script>

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