<template>
  <div>
    <div
      style="
        background-color: #f4f7fc;
        min-height: 80vh;
        overflow: auto;
        padding: 20px;
      "
    >
      <el-row>
        <el-col :span="4"><div class="grid-content ep-bg-purple" /></el-col>
        <el-col :span="16"
          ><div
            v-loading="loading"
            class="grid-content ep-bg-purple-light"
            style="
              background-color: white;
              min-height: 85vh;
              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: 580px">
              <el-form
                ref="ruleFormRef"
                :model="form1"
                :rules="formRules"
                label-width="12vw"
              >
                <el-form-item prop="createBy" label="处室负责人：">
                  <el-input
                    disabled
                    v-model="form1.createBy"
                    style="width: 25vw"
                  />
                </el-form-item>
                <el-form-item prop="deptId" label="所在处室：">
                  <el-tree-select
                    disabled
                    v-model="form1.deptId"
                    style="width: 25vw"
                    :data="deptOptions"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children',
                    }"
                    value-key="id"
                    placeholder="请选择所在处室"
                    check-strictly
                  />
                </el-form-item>
                <el-form-item prop="createBy" label="事务名称：">
                  <el-input
                    v-model="form1.createBy"
                    style="width: 25vw"
                    type="textarea"
                    :rows="2"
                  />
                </el-form-item>
                <el-form-item prop="createBy" label="本周推进情况：">
                  <el-input
                    v-model="form1.createBy"
                    style="width: 25vw"
                    type="textarea"
                    :rows="5"
                  />
                </el-form-item>
                <el-form-item prop="createBy" label="下周计划：">
                  <el-input
                    v-model="form1.createBy"
                    style="width: 25vw"
                    type="textarea"
                    :rows="3"
                  />
                </el-form-item>
                <el-form-item prop="srcDate" label="完成时限：">
                  <el-col :span="24">
                    <el-date-picker
                      :disabled="showTable !== undefined"
                      style="width: 25vw"
                      v-model="form1.srcDate"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      placeholder="值班日期"
                      :disabled-date="disabledDate"
                    />
                    <el-input
                      v-model="form1.createBy"
                      style="width: 25vw; margin-top: 20px"
                      type="textarea"
                      :rows="3"
                    />
                  </el-col>
                </el-form-item>
                <el-form-item label="是否督办">
                  <el-radio-group v-model="form.resource">
                    <el-radio label="是"></el-radio>
                    <el-radio label="否"></el-radio>
                  </el-radio-group>
                </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: 1vh"
                      type="primary"
                      @click="onSubmit"
                      >提交</el-button
                    >
                  </div>
                </div>
              </el-form>

              <el-table
                :data="tableData"
                v-if="showTable !== undefined"
                style="width: 100%"
                ref="multipleTable1"
                :row-key="getRowKeys"
              >
                <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>
              <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="4"><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 { addWork, getConditionUsers } from "@/api/workApply";
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";
import { deptTreeSelect } from "@/api/system/user";
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("格式错误，仅支持输入纯数字"));
        }
      }
    };
    var validator3 = (rule, val, callback) => {
      if (!val) {
        callback(new Error("请输入乘车人数"));
      } else {
        const reg = /^([0-9])*$/; //
        if (reg.test(val)) {
          return callback();
        } else {
          callback(new Error("格式错误，仅支持输入纯数字"));
        }
      }
    };

    return {
      optionsData: [
        {
          value: "0",
          label: "白天",
        },
        {
          value: "1",
          label: "夜晚",
        },
        {
          value: "3",
          label: "带班干部",
        },
        {
          value: "2",
          label: "应急值班",
        },
        {
          value: "4",
          label: "值班司机",
        },
      ],
      value: "",
      WorkData: [],
      createBy: "",
      deptOptions: undefined,
      flowDatas: {
        FK_Flow: null,
        toNodeId: "",
        WorkID: "",
      },
      Fzr: null,
      form1: {
        leaveTime: null,
      },
      form: { params: {} },
      options: [],
      leaveTime: "",
      formRules: {
        createBy: [
          { required: true, trigger: "blur", message: "请输入您的姓名" },
        ],
        // deptId: [{ required: true, trigger: "blur", message: "请输入联系方式" }],

        deptId: [
          {
            required: true,
            message: "请选择所在处室",
            trigger: "change",
          },
        ],
        srcDate: [
          {
            required: true,
            message: "请选择值班日期",
            trigger: "change",
          },
        ],
        targetDate: [
          {
            required: true,
            message: "请选择调班日期",
            trigger: "change",
          },
        ],
        // status: [
        //   {
        //     required: true,
        //     message: "请选择值班类型",
        //     trigger: "change",
        //   },
        // ],
      },
    };
  },

  created() {
    this.getUserInfo();
    this.getDeptTree();
  },
  watch: {},

  mounted() {
    this.getUserInfo();
    this.getDeptTree();
  },

  methods: {
    disabledDate(time) {
      // 获取今天的日期，不包括时间
      const today = new Date();
      today.setHours(0, 0, 0, 0);

      // 禁用所有早于今天的日期
      return time.getTime() < today.getTime();
    },
    getRowKeys(row) {
      return row.userId;
    },
    // el-table只能选一个

    setSelectRows(selection) {
      if (selection.length > 1) {
        const del_row = selection.shift();
        this.$refs.multipleTable1.toggleRowSelection(del_row, false); //设置这一行取消选中
      }
    },

    // 点击表头的全选复选框触发
    selectAll(selection) {
      this.$modal.msgError("人员只能选一个！");
      this.$refs.multipleTable1.clearSelection();
      return;
    },
    handleSelectionChange(selection) {
      console.log("selection", selection);
      if (selection.length != 0) {
        this.form.adjustUserId = selection[0].userId;
      }

      // this.userNames = selection.map((item) => item.NO);
    },
    workPerson(val) {
      console.log(val);
      getConditionUsers({ dateStr: val }).then((res) => {
        console.log("res", res);
        this.WorkData = res.rows;
      });
    },
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    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.dayNum = Math.floor(days) + 1;
    },
    getUserInfo() {
      getInfo().then((res) => {
        this.form1.createBy = res.user.nickName;
        this.createBy = res.user.nickName;
        this.form1.userId = res.user.userId;
        this.form1.deptId = res.user.deptId;
        this.Fzr = res.roles.filter((item) => item == "chushifzr").length > 0;
      });
    },
    onSubmit() {
      this.$refs["ruleFormRef"].validate((valid) => {
        // this.form.createBy = this.form1.createBy;
        this.form.deptId = this.form1.deptId;
        this.form.userId = this.form1.userId;
        this.form.srcDate = this.form1.srcDate;
        this.form.targetDate = this.form1.targetDate;
        // this.form.status = this.form1.status;
        if (
          this.form.adjustUserId == null ||
          this.form.adjustUserId == "" ||
          this.form.adjustUserId == undefined
        ) {
          this.$modal.msgError("请选择调班人");
          return;
        }
        if (valid) {
          if (this.Fzr) {
            this.$modal.loading("提交中...");
            console.log(getJToken());
            this.flowDatas.token = getJToken();
            this.flowDatas.WorkID = this.workId;
            this.flowDatas.FK_Flow = "015";
            this.flowDatas.toNodeId = null;
            console.log(this.flowDatas);
            this.$modal.closeLoading();
            this.$refs["selectRef"].show1(this.flowDatas);
          } else {
            addWork(this.form)
              .then((response) => {
                this.$modal.loading("提交中...");

                ElMessage({
                  message:
                    "已发送到" +
                    response.data.VarToNodeName +
                    "节点，接收人：" +
                    response.data.VarAcceptersName,
                  type: "success",
                });
                this.$refs.ruleFormRef.resetFields();
                this.$modal.closeLoading();
                this.$emit("change1");
                this.reset();
              })
              .catch(() => {
                this.$modal.closeLoading();
              });
          }
        } else {
          this.$modal.closeLoading();
        }
      });
    },

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

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