<template>
  <div>
    <div
      style="
        background-color: #f4f7fc;
        min-height: 78vh;
        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: 78vh;
              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 60px;
                margin-top: 10px;
                height: 580px;
                overflow: auto;
              "
            >
              <el-form
                ref="ruleFormRef"
                :model="form"
                :rules="rules"
                label-width="100px"
              >
                <el-form-item label="督办事项" prop="title">
                  <el-input v-model="form.title" placeholder="请输入督办事项" />
                </el-form-item>
                <!-- <el-form-item label="信息类别" prop="infoType">
                  <el-input
                    rows="5"
                    type="textarea"
                    v-model="form.infoType"
                    placeholder="请输入信息类别"
                    :min-height="192"
                  />
                </el-form-item> -->
                <el-row type="flex" justify="">
                  <el-col :span="12">
                    <el-form-item label="督办来源" prop="infoSource">
                      <el-select
                        v-model="form.infoSource"
                        placeholder="请选择督办来源"
                        clearable
                        style="width: 16vw"
                        @change="infoSourceChange"
                      >
                        <el-option
                          v-for="dict in infoSourceData"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        /> </el-select></el-form-item
                  ></el-col>
                  <el-col :span="12">
                    <el-form-item label="完成时限" prop="doneTime">
                      <el-date-picker
                        clearable
                        style="width: 100%"
                        v-model="form.doneTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择完成时限"
                      >
                      </el-date-picker></el-form-item
                  ></el-col>
                  <!-- <el-col :span="12">
                    <el-form-item
                      style="margin-left: 20px"
                      label-width="110px"
                      label="处室及负责人"
                      prop="departmentHead"
                    >
                      <el-input
                        disabled
                        v-model="form.departmentHead"
                        placeholder="请输入处室及负责人"
                      /> </el-form-item
                  ></el-col> -->
                </el-row>
                <el-form-item label="督办内容" prop="infoSourceContent">
                  <el-input
                    :placeholder="infoSourceContent"
                    rows="5"
                    type="textarea"
                    v-model="form.infoSourceContent"
                    :min-height="192"
                  />
                </el-form-item>
                <!-- <el-form-item label="完成时限" prop="doneTime">
                  <el-date-picker
                    clearable
                    v-model="form.doneTime"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择完成时限"
                  >
                  </el-date-picker
                ></el-form-item> -->
                <!-- <el-form-item prop="doneContent">
                  <el-input
                    rows="3"
                    type="textarea"
                    v-model="form.doneContent"
                    placeholder="**月**日
    ****要求/文件要求/部门确定"
                    :min-height="192"
                  />
                </el-form-item> -->
                <!-- <el-form-item label="议定事项" prop="itemPostil">
                  <el-input
                    rows="3"
                    type="textarea"
                    v-model="form.itemPostil"
                    placeholder="请输入议定事项"
                    :min-height="192"
                  />
                </el-form-item> -->
                <el-form-item label="责任处室" prop="prersonLiable">
                  <el-input
                    rows="4"
                    disabled
                    style="width: 80%; display: inline-block"
                    type="textarea"
                    v-model="form.prersonLiable"
                    placeholder="请选择责任处室"
                  />
                  <el-button
                    style="margin-left: 20px"
                    type="primary"
                    @click="handleSelect"
                    >选择</el-button
                  >
                </el-form-item>
                <!--                <el-form-item label="完成时限" prop="doneTime">
                  <el-date-picker clearable
                                  v-model="form.doneTime"
                                  type="date"
                                  value-format="YYYY-MM-DD"
                                  placeholder="请选择完成时限">
                  </el-date-picker>
                    <el-input rows="3" type="textarea" v-model="form.doneContent" placeholder="请输入完成时限内容" :min-height="192"/>
                </el-form-item>-->
                <!--                <el-form-item label="进展情况" prop="progress">
                  <el-input  rows="12"  type="textarea"  v-model="form.progress" placeholder="请输入进展情况" />
                </el-form-item>-->
              </el-form>
              <div style="text-align: center">
                <!-- <el-button
                  style="padding: 0 30px; margin: 0px; margin-top: 2vh"
                  type="primary"
                  @click="sumbitSupervise"
                  >提 交</el-button
                > -->
                <el-button
                  style="padding: 0 30px; margin: 0px; margin-top: 2vh"
                  type="primary"
                  @click="saveSuperviseThis"
                  >保 存</el-button
                >
              </div>
              <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>
              <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>
      <el-dialog
        v-model="dialogVisibleSel"
        title="请选择责任处室"
        width="1200px"
        style="height: 850px"
        :before-close="handleClose"
      >
        <el-row :gutter="20">
          <el-col
            style="
              padding: 0;
              width: 250px;
              border: 1px solid #e7eaec;
              border-radius: 5px;
              min-height: 680px;
            "
            :span="4.5"
            :xs="24"
          >
            <div
              style="
                display: flex;
                width: 250px;
                height: 40px;
                line-height: 40px;
                border-bottom: 1px solid #e7eaec;
                margin-bottom: 10px;
              "
            >
              <div
                @click="toggle(0)"
                :class="{ selected: fontIndex === 0 }"
                style="
                  font-size: 17px;
                  margin-left: 15px;
                  padding-left: 10px;
                  height: 40px;
                  width: 110px;
                  border-right: 1px solid #e7eaec;
                  cursor: pointer;
                "
              >
                所属部门
              </div>
            </div>
            <div class="head-container"></div>
            <!-- 部门 -->
            <div class="head-container">
              <el-tree
                :data="deptOptions"
                :props="{ label: 'label', children: 'children' }"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="dept"
                node-key="id"
                highlight-current
                default-expand-all
                @node-click="handleNodeClick"
                :current-node-key="currentNodeKey"
                :default-expanded-keys="expandedKeys"
              />
            </div>
          </el-col>
          <!-- 所属部门 -->
          <el-col
            style="margin-left: 40px; margin-top: 5px"
            :span="17"
            :xs="10"
          >
            <el-form
              :model="queryParams"
              ref="queryRef"
              :inline="true"
              label-width="68px"
              style="margin-bottom: 20px"
            >
              <el-form-item label="用户姓名" prop="nickName">
                <el-input
                  v-model="queryParams.nickName"
                  placeholder="请输入用户姓名"
                  clearable
                  style="width: 240px"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery"
                  >搜索</el-button
                >
                <el-button icon="RefreshRight" @click="resetQuery"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>

            <el-table
              style="height: 55vh; overflow: auto"
              ref="multipleTable1"
              :row-key="getRowKeys"
              :data="userList"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                :selectable="getSelectable"
                :reserve-selection="true"
                type="selection"
                width="50"
                align="center"
              />
              <el-table-column
                label="用户姓名"
                align="center"
                key="nickName"
                prop="nickName"
                v-if="columns[2].visible"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                align="center"
                prop="phonenumber"
                label="联系方式"
              ></el-table-column>
              <el-table-column
                label="所属部门"
                align="center"
                key="deptName"
                prop="dept.deptName"
                v-if="columns[3].visible"
                :show-overflow-tooltip="true"
              />
            </el-table>
            <div style="float: right; margin-top: 20px; margin-right: 20px">
              <el-pagination
                v-model:current-page="queryParams.pageNum"
                v-model:page-size="queryParams.pageSize"
                :page-sizes="[10, 20, 30, 50, 100]"
                :small="small"
                :disabled="disabled"
                :background="background"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-col>
        </el-row>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="this.dialogVisibleSel = false">取消</el-button>
            <el-button type="primary" @click="submitUserList"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { addCar } from "@/api/car";
import {
  generNextStepNode,
  generNextStepAllNode,
  sendFlowToNext,
  sendFlowToNextLeave,
  node_ReturnWork,
  getSelfParas,
} from "@/api/liucheng";
import { listUser2, deptTreeSelect2 } from "@/api/system/user";
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 { deptTreeSelect } from "@/api/system/user";
import { startSupervision, saveSupervision } from "@/api/offcial/supervision";
export default {
  name: "YinetoaLeaveApplication",
  props: [
    "dialogVisible",
    "name",
    "showTable",
    "WorkId",
    "FK_Flow",
    "nodeName",
    "trueLeave",
    "closeDialog",
    "form1",
  ],
  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 {
      form: { ywSupervisionStartUserList: [] },
      userIdAll: [],
      ids: [],
      userLogin: "",
      dialogVisibleSel: false,
      total: 0,
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true },
      ],
      loading: false,
      selection: [],
      deptOptions: [],
      userList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
        nickName: undefined,
      },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      upload: {
        headers: { Authorization: "Bearer" + getJToken() },
        url: import.meta.env.VITE_APP_BASE_API + "/system/file/fileupload",
      },
      infoSourceData: useDict("info_source").info_source,
      sys_yes_no: useDict("sys_yes_no").sys_yes_no,
      db_template: useDict("db_template").db_template,
      infoSourceContent: "",
      rules: {
        title: [
          {
            required: true,
            message: "请输入标题",
            trigger: "blur",
          },
        ],
        infoType: [
          {
            required: true,
            message: "请输入信息类别",
            trigger: "blur",
          },
        ],
        departmentHead: [
          {
            required: true,
            message: "请输入处室及负责人",
            trigger: "blur",
          },
        ],
        infoSource: [
          {
            required: true,
            message: "请选择信息来源",
            trigger: "change",
          },
        ],
        doneTime: [
          {
            required: true,
            message: "请选择完成时限",
            trigger: "change",
          },
        ],
        infoSourceContent: [
          {
            required: true,
            message: "请输入信息来源内容",
            trigger: "blur",
          },
        ],
        doneContent: [
          {
            required: true,
            message: "请输入完成时限内容",
            trigger: "blur",
          },
        ],
        itemPostil: [
          {
            required: true,
            message: "请输入议定事项",
            trigger: "blur",
          },
        ],
        prersonLiable: [
          {
            required: true,
            message: "请输入责任处室",
            trigger: "blur",
          },
        ],
      },
    };
  },

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

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

  methods: {
    saveSuperviseThis() {
      this.$modal.loading("保存中...");
      saveSupervision(this.form)
        .then((response) => {
          this.$modal.msgSuccess("保存成功");
          this.$nextTick(() => {
            this.reset();
            this.$refs.ruleFormRef.resetFields();
            this.$emit("change1");
            this.$emit("guanbi");
          });
          this.$modal.closeLoading();
        })
        .catch(() => {
          this.$modal.closeLoading();
        });
    },
    // 选择人员
    handleSelect() {
      // this.mailUserIds = [];
      // this.getContactsTree();
      this.queryParams = {
        deptId: undefined,
        pageNum: 1,
        pageSize: 120,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        postIds: undefined,
        beginTime: undefined,
        endTime: undefined,
      };
      this.getList();
      this.getDeptTree();

      // 回显
      console.log("回显", this.form.ywSupervisionStartUserList);
      if (this.form.ywSupervisionStartUserList.length > 0) {
        this.$nextTick(() => {
          this.$refs.multipleTable1.clearSelection();
          this.userIdAll = [];
          for (
            let i = 0;
            i < this.form.ywSupervisionStartUserList.length;
            i++
          ) {
            this.userIdAll.push(this.form.ywSupervisionStartUserList[i].userId);
          }
          console.log("this.userIdAll", this.userIdAll);
          setTimeout(() => {
            this.userIdAll.forEach((item) => {
              this.userList.forEach((item1) => {
                if (item == item1.userId) {
                  console.log("item1", item1);
                  this.$refs.multipleTable1.toggleRowSelection(item1, true);
                }
              });
            });
          }, 300);
        });
      }
      this.dialogVisibleSel = true;
    },
    submitUserList() {
      // console.log("selection", this.selection);
      this.form.ywSupervisionStartUserList = [];
      this.form.prersonLiable = "";
      let arr = [];
      for (let i = 0; i < this.selection.length; i++) {
        let obj = {
          userName: this.selection[i].userName,
          userId: this.selection[i].userId,
          nickName: this.selection[i].nickName,
        };
        this.form.ywSupervisionStartUserList.push(obj);
        arr.push(
          this.selection[i].dept.deptName + "--" + this.selection[i].nickName
        );
        console.log("arr", arr);
        this.form.prersonLiable = arr.join(" , ");
      }
      console.log(
        "ywSupervisionStartUserList",
        this.form.ywSupervisionStartUserList
      );
      // let arr = this.selection.map((item) => {
      //   console.log(item);
      //   return item.dept.deptName + "--" + item.nickName;
      // });
      // this.form.prersonLiable = arr.join(" , ");
      console.log("this.form.prersonLiable", this.form.prersonLiable);
      this.dialogVisibleSel = false;
    },
    // // 多选框选中数据  常用联系人
    handleSelectionChange(selection) {
      console.log("selection", selection);
      this.selection = [];
      this.selection = selection;

      this.single = this.selection.length !== 1;
      this.multiple = !this.selection.length;
    },
    // /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryRef");
      this.queryParams.deptId = undefined;
      this.$nextTick(() => {
        this.$refs.deptTreeRef.setCurrentKey(null);
      });
      this.handleQuery();
    },
    // /** 节点单击事件 */
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    getRowKeys(row) {
      return row.userId;
    },
    getSelectable(row) {
      return row.status !== "REJECT";
    },
    //分页
    handleSizeChange(newPage) {
      this.queryParams.pageSize = newPage;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    // /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // /** 查询部门下拉树结构 */
    async getDeptTree() {
      await deptTreeSelect2().then((response) => {
        this.deptOptions = response.data;
      });
    },
    async getList() {
      this.loading = true;
      await listUser2(this.addDateRange(this.queryParams, this.dateRange)).then(
        (res) => {
          this.loading = false;
          this.userList = res.rows;
          //console.log("this.userList", this.userList);
          this.total = res.total;
        }
      );
      // this.selection = [];
    },

    infoSourceChange(val) {
      console.log("db_template", this.db_template);
      console.log(val);
      this.infoSourceContent = this.db_template[val - 1].label;
    },
    // getDeptTree() {
    //   deptTreeSelect().then((response) => {
    //     this.deptOptions = response.data;
    //   });
    // },
    sumbitSupervise() {
      this.$refs["ruleFormRef"].validate((valid) => {
        if (valid) {
          this.$modal.loading("提交中...");

          startSupervision(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();
            });
        }
      });
    },
    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.userLogin = res.user.userName;
        this.form.departmentHead =
          res.user.nickName + "-" + res.user.dept.deptName;
        this.Fzr = res.roles.filter((item) => item == "chushifzr").length > 0;
      });
    },

    reset() {
      this.getUserInfo();
      this.form.ywSupervisionStartUserList = [];
    },
    SubmitSelect(selUsers) {
      this.form.params["toEmps"] = selUsers;
      if (selUsers != undefined && selUsers != "") {
        console.log(this.form);
      }
    },
  },
};
</script>

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