<template>
  <div>
    <div
      style="
        background-color: #f4f7fc;
        height: 80vh;
        overflow: auto;
        padding: 20px;
      "
    >
      <el-row>
        <el-col :span="5"><div class="grid-content ep-bg-purple" /></el-col>
        <el-col :span="14"
          ><div
            v-loading="loading"
            class="grid-content ep-bg-purple-light"
            style="
              background-color: white;
              height: 60vh;
              border: 1px solid #e4e7ed;
            "
          >
            <div
              style="
                height: 60px;
                line-height: 60px;
                text-align: center;
                color: red;
                font-weight: 700;
                font-size: 20px;
                border-bottom: 1px solid #e4e7ed;
              "
            >
              职工请（休）假申请表
            </div>
            <div style="padding: 20px; margin-top: 10px; height: 490px">
              <el-form
                ref="ruleFormRef"
                :model="form1"
                :rules="formRules"
                label-width="15vw"
              >
                <!-- <div style="display: flex"> -->
                <el-form-item prop="name" label="姓名：">
                  <el-input disabled v-model="form1.name" style="width: 14vw" />
                </el-form-item>

                <el-form-item prop="leaveTpye" label="请（休）假类别：">
                  <el-select
                    v-model="form1.leaveTpye"
                    clearable
                    placeholder="请选择请 (休) 假类别"
                    style="width: 14vw"
                  >
                    <el-option
                      v-for="dict in leave_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <!-- <el-radio-group v-model="form1.leaveTpye">
                  <el-radio
                    :disabled="showTable !== undefined"
                    label="0"
                    size="large"
                    >事假</el-radio
                  >
                  <el-radio
                    :disabled="showTable !== undefined"
                    label="1"
                    size="large"
                    >病假</el-radio
                  >
                  <el-radio
                    :disabled="showTable !== undefined"
                    label="2"
                    size="large"
                    >年休假</el-radio
                  >
                  <el-radio
                    :disabled="showTable !== undefined"
                    label="3"
                    size="large"
                    >探亲假</el-radio
                  >
                  <el-radio
                    :disabled="showTable !== undefined"
                    label="4"
                    size="large"
                    >婚假</el-radio
                  >
                  <el-radio
                    :disabled="showTable !== undefined"
                    label="5"
                    size="large"
                    >丧假</el-radio
                  >
                  <el-radio
                    :disabled="showTable !== undefined"
                    label="6"
                    size="large"
                    >产假</el-radio
                  >
                </el-radio-group> -->
                </el-form-item>
                <el-form-item prop="leaveTime" label="请（休）假起止日期：">
                  <el-col :span="24">
                    <el-date-picker
                      :disabled="showTable !== undefined"
                      style="width: 14vw"
                      v-model="form1.leaveTime"
                      type="daterange"
                      value-format="YYYY-MM-DD"
                      range-separator="至"
                      start-placeholder="起始日期"
                      end-placeholder="截止日期"
                      @change="changeDate(form1.leaveTime)"
                    />
                  </el-col>
                </el-form-item>
                <el-form-item prop="leaveNumber" label="请（休）假天数：">
                  <!-- :disabled="showTable !== undefined" -->
                  <el-input
                    disabled
                    v-model="form1.leaveNumber"
                    style="width: 14vw; margin-right: 10px"
                  />天
                </el-form-item>
                <el-form-item prop="leaveReason" label="请（休）假事由：">
                  <el-col :span="23">
                    <el-input
                      :disabled="showTable !== undefined"
                      style="width: 14vw"
                      v-model="form1.leaveReason"
                      type="textarea"
                    />
                  </el-col>
                </el-form-item>
                <div v-if="leaveTrue !== true">
                  <div v-if="leaveClear == true">
                    <el-form-item
                      v-if="showTable !== undefined"
                      label="下一步节点："
                    >
                      <el-select
                        v-model="selNextNode"
                        placeholder="请选择下一步节点"
                      >
                        <el-option
                          v-for="item in options"
                          :key="item.NodeID"
                          :label="item.Name"
                          :value="item.NodeID"
                      /></el-select>
                    </el-form-item>
                    <el-form-item label="销假日期：">
                      <el-date-picker
                        v-model="valDate"
                        type="date"
                        placeholder="请选择销假日期"
                        :size="size"
                      />
                    </el-form-item>
                  </div>
                  <div v-else>
                    <el-form-item
                      v-if="showTable !== undefined"
                      label="下一步节点："
                    >
                      <el-select
                        v-model="selNextNode"
                        placeholder="请选择下一步节点"
                      >
                        <el-option
                          v-for="item in options"
                          :key="item.NodeID"
                          :label="item.Name"
                          :value="item.NodeID"
                      /></el-select>
                    </el-form-item>
                    <el-form-item v-if="showTable" label="审核意见：">
                      <el-col :span="23">
                        <el-input
                          v-model="reviewMsg"
                          style="width: 20vw"
                          type="textarea"
                        />
                      </el-col>
                    </el-form-item>
                  </div>
                  <div
                    v-if="showTable !== undefined"
                    style="text-align: center"
                  >
                    <el-form-item>
                      <el-button
                        style="margin-top: 4vh"
                        type="primary"
                        @click="sendNext"
                        >提交</el-button
                      >
                      <el-button
                        style="margin-top: 4vh"
                        type="danger"
                        @click="sendBack"
                        >退回</el-button
                      >
                    </el-form-item>
                  </div>
                  <div v-else style="text-align: center; width: 100%">
                    <el-button
                      style="padding: 0 35px; margin-top: 14vh"
                      type="primary"
                      @click="onSubmit"
                      >提交</el-button
                    >
                  </div>
                </div>
              </el-form>

              <el-table
                :data="tableData"
                v-if="showTable !== undefined"
                style="width: 100%"
              >
                <el-table-column
                  type="index"
                  align="center"
                  label="序号"
                  width="80"
                />
                <el-table-column
                  prop="NodeName"
                  align="center"
                  label="处理步骤"
                />
                <el-table-column prop="EmpName" align="center" label="处理人" />
                <el-table-column
                  prop="DeptName"
                  align="center"
                  label="处理部门"
                />
                <el-table-column prop="" align="center" label="到达日期">
                  <template #default="scope">
                    {{ parseTime(scope.row.RDT, "{y}-{m}-{d} ") }}
                  </template>
                </el-table-column>
                <el-table-column prop="" align="center" label="处理日期" />
                <!-- <el-table-column prop="IsPass" align="center" label="处理意见">
                <template #default="scope">
                  <div v-if="scope.row.IsPass == 0">未处理</div>
                  <div v-if="scope.row.IsPass == 1">已通过</div>
                </template>
              </el-table-column> -->
              </el-table>
              <div style="text-align: center" v-if="closeDialog == true">
                <el-button
                  style="padding: 0 30px; margin: 0px; margin-top: 2vh"
                  type="primary"
                  @click="closeLeaveDialog"
                  >关闭</el-button
                >
              </div>
            </div>
          </div></el-col
        >
        <el-col :span="5"><div class="grid-content ep-bg-purple" /></el-col>
      </el-row>
      <select-user
        @ok="SubmitSelect"
        @closeDialogf="closeSelUser"
        ref="selectRef"
      ></select-user>
      <!-- 退回 -->
      <el-dialog title="退回" v-model="dialogBack" width="40%">
        <el-form>
          <el-form-item label-width="200" label="退回节点：">
            <el-select
              v-model="nodeValue"
              placeholder="请选择退回节点信息"
              style="width: 240px"
            >
              <el-option
                v-for="item in nodeData"
                :key="item.No"
                :label="item.Name"
                :value="item.No"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label-width="200"
            label="退回原因："
            placeholder="请输入退回原因"
          >
            <el-input v-model="returnMsg" style="width: 20vw" type="textarea" />
          </el-form-item>
        </el-form>
        <span
          style="position: relative; left: 28vw"
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="dialogBack = false">取 消</el-button>
          <el-button type="primary" @click="submitNodeBack">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  leave,
  getLeave,
  getReturnWorkNode,
  WorkProgressBar,
  NodeReturnWork,
} from "@/api/clocking/leave";
import {
  generNextStepNode,
  generNextStepAllNode,
  sendFlowToNext,
  sendFlowToNextLeave,
  node_ReturnWork,
} from "@/api/liucheng";
import { ElMessage } from "element-plus";
import selectUser from "@/views/clocking/selectUser.vue";
import { getJToken } from "@/utils/auth";
import { getInfo } from "@/api/login";
import { useDict } from "@/utils/dict";
import { get } from "@vueuse/core";
import { ColorStyle } from "quill";
export default {
  name: "YinetoaLeaveApplication",
  props: [
    "dialogVisible",
    "name",
    "showTable",
    "WorkId",
    "FK_Flow",
    "nodeName",
    "trueLeave",
    "closeDialog",
  ],
  components: { selectUser },
  data() {
    var validator2 = (rule, val, callback) => {
      if (!val) {
        callback(new Error("请输入请假天数"));
      } else {
        const reg = /^([0-9])*$/; //
        if (reg.test(val)) {
          return callback();
        } else {
          callback(new Error("格式错误，仅支持输入纯数字"));
        }
      }
    };

    return {
      leave_type: useDict("leave_type").leave_type,
      loading: false,
      leaveTrue: false,
      valDate: null,
      nodeValue: null,
      returnMsg: null,
      dialogBack: false,
      reviewMsg: "",
      formData: {
        jtoken: null,
        optionName: null,
        toNodeId: null,
        users: null,
        workid: null,
        reviewMsg: null,
      },
      leaveInfo: [
        {
          lable: "事假",
          value: "0",
        },
        {
          lable: "年假",
          value: "1",
        },
        {
          lable: "病假",
          value: "2",
        },
      ],
      flowDatas: {
        FK_Flow: null,
        toNodeId: "",
        WorkID: "",
      },
      Fzr: null,
      selNextNode: null,
      tableData: [],
      nodeData: [],
      queryParams: {
        token: null,
        workID: null,
      },
      FK_flow: null,
      leaveClear: false,
      workId: null,
      value2: "",
      // name: "",
      input: "",
      form1: {
        leaveTime: null,
      },
      form: {
        status: "1",
        params: {},
      },
      options: [],
      leaveTime: "",
      formRules: {
        name: [{ required: true, trigger: "blur", message: "请输入您的姓名" }],
        leaveNumber: [
          {
            required: true,
            trigger: "blur",
            validator: validator2,
            // message: "请输入请（休）假天数",
          },
        ],
        leaveTpye: [
          {
            required: true,
            message: "请选择请（休）假类别",
            trigger: "change",
          },
        ],
        leaveStartTime: [
          {
            required: true,
            message: "请选择请（休）假起始时间",
            trigger: "change",
          },
        ],
        leaveTime: [
          {
            required: true,
            message: "请选择请（休）假起止时间",
            trigger: "change",
          },
        ],
        leaveEndTime: [
          {
            required: true,
            message: "请选择请（休）假截止时间",
            trigger: "change",
          },
        ],
        leaveReason: [
          {
            required: true,
            message: "请输入请（休）假事由",
            trigger: "change",
          },
        ],
      },
    };
  },

  created() {
    this.getInfo();
  },
  mounted() {},
  watch: {
    trueLeave: {
      handler(newValue, oldValue) {
        if (newValue) {
          this.leaveTrue = newValue;
        }
      },
      deep: true,
      immediate: true,
    },
    name: {
      handler(newValue, oldValue) {
        if (newValue) {
          this.form1.name = newValue;
        }
      },
      deep: true,
      immediate: true,
    },
    WorkId: {
      handler(newValue, oldValue) {
        if (newValue) {
          this.workId = newValue;
          this.getLeave();
          this.selNextNode = null;
          this.nodeValue = null;
          this.returnMsg = null;
          this.valDate = null;
        }
      },
      deep: true,
      immediate: true,
    },
    FK_Flow: {
      handler(newValue, oldValue) {
        if (newValue) {
          this.FK_flow = newValue;
          this.getLeave();
        }
      },
      deep: true,
      immediate: true,
    },
    nodeName: {
      handler(newValue, oldValue) {
        if (newValue) {
          this.NodeName = newValue;
          if (this.NodeName == "请假人员") {
            this.leaveClear = true;
          }
          if (this.NodeName == "人事处销假") {
            this.leaveClear = false;
          }
          if (this.NodeName == "人事处") {
          }
          this.getLeave();
        }
      },
      deep: true,
      immediate: true,
    },
  },

  mounted() {},

  methods: {
    changeDate(val) {
      var d1 = new Date(val[0]);
      var d2 = new Date(val[1]);
      var diff = d2 - d1;
      var days = diff / (1000 * 60 * 60 * 24);
      this.form1.leaveNumber = Math.floor(days) + 1;
    },
    closeLeaveDialog() {
      this.$emit("closeViewLeave");
    },

    async submitNodeBack() {
      if (this.nodeValue == null) {
        this.$message.error("请选择退回节点信息");
        return;
      }
      if (this.returnMsg == null) {
        this.$message.error("请输入退回原因");
        return;
      }
      let res = await NodeReturnWork(
        this.workId,
        this.nodeValue,
        this.returnMsg
      );
      this.$message.success(res);
      this.dialogBack = false;
      this.$modal.closeLoading();
      this.$emit("closeViewLeave");
      this.nodeValue = null;
      this.returnMsg = null;
      this.valDate = null;
      this.selNextNode = null;
    },
    async getReturnWorkNode() {
      let nodeData = await getReturnWorkNode(getJToken(), this.workId);
      this.nodeData = nodeData;
    },
    sendBack() {
      this.dialogBack = true;
      this.getReturnWorkNode();
      if (this.NodeName == "请假人员") {
        this.leaveClear = false;
      }
    },
    /** 选择用户后进行下一步 */
    handleQuery(selUsers) {
      this.formData.users = selUsers;
      if (selUsers != undefined && selUsers != "") {
        this.nextSubmit();
      }
    },
    //下一步提交
    async nextSubmit() {
      this.$modal.loading("提交中...");
      this.formData.jtoken = getJToken();
      this.formData.workid = this.workId;
      this.formData.toNodeId = this.selNextNode;
      if (this.leaveClear == true) {
        this.formData.reviewMsg = "同意";
      } else {
        this.formData.reviewMsg = this.reviewMsg;
      }
      this.formData.xjDate = this.valDate;
      this.formData.optionName = this.nodeName;

      let { data, code } = await sendFlowToNextLeave(this.formData);

      if (code == 200) {
        ElMessage({
          message:
            "已发送到" +
            data.VarToNodeName +
            "节点，接收人：" +
            data.VarAcceptersName,
          type: "success",
        });
        this.$refs["selectRef"].closeView();
        this.$modal.closeLoading();
        this.$emit("change1");
        this.selNextNode = null;
        this.reviewMsg = "";
      }
    },

    //获取下一节点的接收人信息
    async sendNext() {
      if (this.leaveClear == true) {
        if (this.selNextNode == undefined) {
          this.$modal.msgWarning("请选择下一节点");
          return;
        }
        if (this.valDate == null) {
          this.$modal.msgWarning("请选择销假日期！");
          return;
        }
      } else {
        if (this.selNextNode == undefined) {
          this.$modal.msgWarning("请选择下一节点");
          return;
        }
        if (this.reviewMsg == "") {
          this.$modal.msgWarning("请填写审批意见！");
          return;
        }
      }

      this.flowDatas.token = getJToken();
      this.flowDatas.WorkID = this.workId;
      this.flowDatas.FK_Flow = "009";
      this.flowDatas.toNodeId = null;
      this.$refs["selectRef"].show1(this.flowDatas);
    },

    //获取工作进度
    async WorkProgressBar() {
      this.queryParams.token = getJToken();
      this.queryParams.workID = this.workId;
      let { Track } = await WorkProgressBar(getJToken(), this.workId);
      this.tableData = Track;
    },
    //获取审批信息
    async getLeave() {
      let { data } = await getLeave(this.workId);

      this.form1.name = data.name;
      this.form1.leaveNumber = data.leaveNumber;
      this.form1.leaveReason = data.leaveReason;
      this.form1.leaveTpye = data.leaveTpye;
      this.form1.leaveTime = [data.leaveStartTime, data.leaveEndTime];

      if (this.leaveTrue == false) {
        this.generNextStepAllNode();
      }

      this.WorkProgressBar();
    },
    async generNextStepAllNode() {
      let res = await generNextStepAllNode(
        this.FK_flow,
        this.workId,
        "",
        getJToken()
      );
      this.options = res;
      if (this.options.length == 1) {
        this.selNextNode = this.options[0].NodeID;
      }
    },
    //基本信息
    getInfo() {
      getInfo().then((res) => {
        this.form1.name = res.user.nickName;
        this.Fzr = res.roles.filter((item) => item == "chushifzr").length > 0;
        this.form.deptId = res.user.dept.deptId;
      });
    },
    reset() {
      this.form1 = {
        name: "",
        leaveNumber: null,
        leaveTime: null,
        leaveTpye: null,
        leaveReason: null,
        status: "1",
      };
      this.form1.name = this.form.name;
    },
    onSubmit() {
      this.$refs["ruleFormRef"].validate((valid) => {
        if (valid) {
          this.form.leaveNumber = Number(this.form1.leaveNumber);
          this.form.name = this.form1.name;
          this.form.leaveReason = this.form1.leaveReason;
          this.form.leaveTpye = Number(this.form1.leaveTpye);
          this.form.leaveStartTime = this.form1.leaveTime[0];

          this.form.leaveEndTime = this.form1.leaveTime[1];

          if (this.Fzr) {
            this.flowDatas.token = getJToken();
            this.flowDatas.WorkID = this.workId;
            this.flowDatas.FK_Flow = "009";
            this.flowDatas.toNodeId = null;
            console.log(this.flowDatas);
            this.$refs["selectRef"].show1(this.flowDatas);
          } else {
            leave(this.form)
              .then((res) => {
                this.$modal.loading("提交中...");

                this.$modal.msgSuccess(
                  "已发送到" +
                    res.data.VarToNodeName +
                    "节点," +
                    "处理人:" +
                    res.data.VarAcceptersName
                );
                this.$nextTick(() => {
                  this.reset();
                  this.$refs.ruleFormRef.resetFields();
                });
                this.$modal.closeLoading();
                this.$emit("change1");
              })
              .catch(() => {
                this.$modal.closeLoading();
              });
          }
        } else {
          this.$modal.closeLoading();
        }
      });
    },
    // handleQuery(selUsers) {
    //   this.formData.users = selUsers;
    //   if (selUsers != undefined && selUsers != "") {
    //     this.nextSubmit();
    //   }
    // },
    SubmitSelect(selUsers) {
      this.form.params["toEmps"] = selUsers;
      if (selUsers != undefined && selUsers != "") {
        console.log(this.form);
        leave(this.form)
          .then((res) => {
            this.$modal.msgSuccess(
              "已发送到" +
                res.data.VarToNodeName +
                "节点," +
                "处理人:" +
                res.data.VarAcceptersName
            );
            this.$nextTick(() => {
              this.reset();
              this.$refs.ruleFormRef.resetFields();
            });
            this.$emit("change1");
          })
          .catch(() => {
            this.$modal.closeLoading();
          });
      }
    },
    // },
  },
};
</script>

<style lang="scss" scoped></style>
