<template>
  <div style="background-color: #f4f7fc; height: 72vh; padding: 20px">
    <el-row>
      <el-col :span="5"><div class="grid-content ep-bg-purple" /></el-col>
      <el-col :span="14"
        ><div
          class="grid-content ep-bg-purple-light"
          style="
            background-color: white;
            height: 68vh;
            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; height: 500px; margin-top: 20px">
            <el-form
              ref="ruleFormRef"
              :model="form1"
              :rules="formRules"
              label-width="9vw"
            >
              <div style="display: flex">
                <el-form-item prop="name" label="出差处室：">
                  <el-input
                    v-model="form1.outWorkDept"
                    style="width: 12vw"
                    :disabled="true"
                  />
                </el-form-item>
                <el-form-item label-width="7vw" prop="name" label="出差人：">
                  <el-input
                    v-model="form1.userName"
                    style="width: 12vw"
                    :disabled="true"
                  />
                </el-form-item>
              </div>
              <el-form-item prop="reason" label="出差事由：">
                <el-col :span="23">
                  <el-input
                    style="width: 31vw"
                    v-model="form1.reason"
                    type="textarea"
                  />
                </el-col>
              </el-form-item>
              <div style="display: flex">
                <el-form-item prop="provinceType" label="目的地：">
                  <el-radio-group v-model="form1.provinceType" class="ml-4">
                    <el-radio label="0" size="large">省内</el-radio>
                    <el-radio label="1" size="large">省外</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item prop="destination" label-width="20">
                  <el-input v-model="form1.destination" style="" />
                </el-form-item>
              </div>
              <el-form-item prop="dateRange1" label="出差起止日期：">
                <el-col :span="24">
                  <el-date-picker
                    style="width: 20vw"
                    v-model="form1.dateRange1"
                    type="daterange"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="至"
                    start-placeholder="请选择起始日期"
                    end-placeholder="请选择截止日期"
                    :size="size"
                  />
                </el-col>
              </el-form-item>
            </el-form>

            <div style="text-align: center">
              <el-form-item style="margin-left: 18vw">
                <el-button
                  style="padding: 0 30px; margin-top: 14vh"
                  type="primary"
                  @click="onSubmit"
                  >提交</el-button
                >
              </el-form-item>
            </div>
          </div>
        </div></el-col
      >
      <el-col :span="5"><div class="grid-content ep-bg-purple" /></el-col>
    </el-row>
    <select-user @ok="SubmitSelect" ref="selectRef"></select-user>
  </div>
</template>

<script>
import {
  groupList,
  getPeoplegroup,
  addGroup,
  addContacts,
  delPeople,
} from "@/api/email/write";
import { getJToken } from "@/utils/auth";
import selectUser from "@/views/clocking/selectUser.vue";
import { listPeoplegroup, delPeoplegroup } from "@/api/system/contact";
import { listUser, deptTreeSelect } from "@/api/system/user";
import { leave } from "@/api/clocking/leave";
import { startOutWork } from "@/api/office/work";
import { getInfo } from "@/api/login";
import { ElMessage } from "element-plus";

export default {
  name: "YinetoaLeaveApplication",
  components: { selectUser },
  selected: false,
  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 {
      selectedIndex: 0,
      dateRange1: [],
      showSearch: true,
      ids: [],
      deptOptions: [],
      fontIndex: 0,
      userList: [],
      delPeopleInfo: {
        groupId: undefined,
        userId: undefined,
      },
      dialogVisible2: false,
      dialogVisible1: false,
      contactsOptions: undefined,
      forwardInfo: {
        mailId: null,
        userIds: [],
      },
      groupInfo: {
        groupName: "",
      },
      Fzr: null,
      // 查询参数
      queryParams1: {
        pageNum: 1,
        pageSize: 50,
        userId: "1",
      },
      selection: [],
      contactsList: [],
      dialogVisible11: false,
      ruleForm: {
        mailUserIds: [],
        isRead: "N",
        isDel: "N",
        mailState: "1",
        mailType: null,
        sendTime: "",
        files: [],
      },
      mailUserIds: [],
      show: true,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
        nickName: undefined,
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 150,
      },
      queryParams3: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      peopleInfo: {
        groupId: null,
        userIds: [],
      },
      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 },
      ],
      ////////////////////
      input: "",
      form: {
        status: "1",
        params: {},
      },
      flowDatas: {},
      form1: {},
      leaveTime: "",
      formRules: {
        reason: [
          {
            required: true,
            message: "请输入出差事由",
            trigger: "change",
          },
        ],
        dateRange1: [
          {
            required: true,
            message: "请选择起止日期",
            trigger: "change",
          },
        ],
        destination: [
          {
            required: true,
            message: "请输入目的地",
            trigger: "change",
          },
        ],
        provinceType: [
          {
            required: true,
            message: "请选择省内外",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.getUserInfo();
  },
  mounted() {},

  methods: {
    SubmitSelect(selUsers) {
      this.form.params["toEmps"] = selUsers;
      if (selUsers != undefined && selUsers != "") {
        console.log("SubmitSelect", this.form);
        startOutWork(this.form).then((response) => {
          ElMessage({
            message:
              "已发送到" +
              response.data.VarToNodeName +
              "节点，接收人：" +
              response.data.VarAcceptersName,
            type: "success",
          });
          this.reset();
          this.$refs.ruleFormRef.resetFields();
          this.$emit("change1");
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      //console.log("row", row);
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除该常用联系组？")
        .then(function () {
          return delPeoplegroup(ids);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.$nextTick(() => {
            this.getContactsTree();
            // this.getPeoplegroup();
          });
        })
        .catch(() => {});
    },
    getUserInfo() {
      getInfo().then((res) => {
        this.form1.userName = res.user.nickName;
        this.form1.outWorkDept = res.user.dept.deptName;
        // this.Fzr = res.roles.filter((item) => item == "chushifzr").length > 0;
        this.Fzr = true;
        // console.log(this.Fzr);
      });
    },
    //删除常用联系人
    async delPeople(row) {
      //console.log("row", row);
      this.delPeopleInfo.groupId = this.peopleInfo.groupId;
      this.delPeopleInfo.userId = row.userId;
      let { code } = await delPeople(this.delPeopleInfo);
      if (code == 200) {
        this.$message.success("删除成功");
        this.getPeoplegroup();
      }
    },
    // // 多选框选中数据  常用联系人
    handleSelectionChange(selection) {
      this.selection = [];
      this.selection = selection;
      this.ids = [];
      this.ids.push(
        this.selection.map((item) => ({
          userId: item.userId,
          nickName: item.nickName,
        }))
      );
      selection = [];
      this.single = this.selection.length !== 1;
      this.multiple = !this.selection.length;
    },
    addContact() {
      this.dialogVisible1 = true;
    },
    // 勾选常用联系人
    handleSelectionChange1(selection) {
      this.selection1 = [];
      //console.log("selection", selection);
      this.selection1 = selection;
      this.ids = [];
      this.ids.push(
        this.selection.map((item) => ({
          userId: item.userId,
          nickName: item.nickName,
        }))
      );
      selection = [];
      this.single = this.selection.length !== 1;
      this.multiple = !this.selection.length;
      // this.$refs.multipleTable.toggleRowSelection(this.selection[0]);
    },
    //确认常用联系人
    async submitPeople() {
      this.peopleInfo.userIds = [];
      for (let i = 0; i < this.selection1.length; i++)
        this.peopleInfo.userIds.push(this.selection1[i].userId);
      let { code } = await addContacts(this.peopleInfo);
      if (code == 200) {
        this.$modal.msgSuccess("添加常用联系人成功");
        this.$refs.multipleTable3.clearSelection();
      }
      this.dialogVisible2 = false;
      this.getPeoplegroup();
    },
    // 添加常用联系人（回显）
    addContactPeople() {
      this.dialogVisible2 = true;

      this.$nextTick(() => {
        this.$refs.multipleTable3.clearSelection();
        this.contactsList.forEach((item) => {
          this.userList.forEach((item1) => {
            if (item.userId == item1.userId) {
              //console.log("11111111111");

              this.$refs.multipleTable3.toggleRowSelection(item1, true);
            }
          });
        });
      });
    },
    getRowKeys(row) {
      return row.userId;
    },
    //确认收件人
    submitUserList() {
      this.nickName = [];
      this.ruleForm.mailUserIds = [];
      for (let i = 0; i < this.ids[0].length; i++) {
        let item = this.ids[0][i];
        // //console.log("item", item);

        this.nickName.push(item.nickName);
        this.ruleForm.mailUserIds.push(item.userId);
        this.forwardInfo.userIds = this.ruleForm.mailUserIds;
      }
      // this.ruleForm.name = this.ids;
      this.dialogVisible11 = false;
    },
    //分页
    handleSizeChange(newPage) {
      this.queryParams.pageSize = newPage;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    // // 数据
    async getList() {
      this.loading = true;
      await listUser(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 = [];
    },
    // /** 节点单击事件 */
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },

    // /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // /** 查询部门下拉树结构 */
    async getDeptTree() {
      await deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    handleSelect() {
      //   this.mailUserIds = [];
      this.toggle(0);
      //console.log("11111111111111");
      this.getContactsTree();
      //console.log("2222");
      this.dialogVisible11 = true;
    },

    /** 查询常用联系人列表 */
    listPeoplegroup() {
      this.loading = false;
      this.loading = true;
      listPeoplegroup(this.queryParams1).then((response) => {
        this.peoplegroupList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //点击
    selectItem(val, index) {
      //console.log("val", val);
      //console.log("index", index);
      this.selectedIndex = index;
      this.peopleInfo.groupId = val.id;
      this.getPeoplegroup();
    },
    //常用联系人名单
    getPeoplegroup() {
      getPeoplegroup(this.peopleInfo.groupId).then((response) => {
        // //console.log("response", response.contactsList);
        this.contactsList = response.contactsList;
      });
    },

    // /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryRef");
      this.queryParams.deptId = undefined;
      this.$nextTick(() => {
        this.$refs.deptTreeRef.setCurrentKey(null);
      });
      this.handleQuery();
    },

    reset() {
      this.form1 = {
        userName: this.form.userName,
        outWorkDept: this.form.outWorkDept,
        userId: undefined,
        reason: undefined,
        destination: undefined,
        provinceType: undefined,
        dateRange1: [],
        params: {},
      };
    },
    onSubmit() {
      // this.$modal.loading("提交中...");
      console.log("this.form1.dateRange1", this.form1.dateRange1);
      this.form.startTime = this.form1.dateRange1[0];
      this.form.endTime = this.form1.dateRange1[1];
      this.form.outWorkDept = this.form1.outWorkDept;
      this.form.userName = this.form1.userName;
      this.form.reason = this.form1.reason;
      this.form.destination = this.form1.destination;
      this.form.provinceType = this.form1.provinceType;
      console.log("this.form", this.form);
      this.$refs["ruleFormRef"].validate((valid) => {
        if (valid) {
          if (this.Fzr) {
            this.flowDatas.token = getJToken();
            this.flowDatas.WorkID = this.workId;
            this.flowDatas.FK_Flow = "006";
            this.flowDatas.toNodeId = null;
            console.log(this.flowDatas);
            this.$refs["selectRef"].show1(this.flowDatas);
          } else {
          }
        } else {
          // this.$modal.closeLoading();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep img {
  max-width: 790px;
}
::v-deep .el-tree-node__content {
  display: flex;
  align-items: center;
  height: 26px;
  cursor: pointer;
  font-size: 16px;
}
::v-deep .el-dialog__body {
  padding: 20px 30px;
  color: var(--el-text-color-regular);
  font-size: var(--el-dialog-content-font-size);
  word-break: break-all;
}
.hover-li:hover {
  background-color: #f5f7fa;
}
.selected {
  font-size: 17px;
  margin-left: 25px;
  padding-right: 25px;
  border-right: 1px solid #e7eaec;
  color: #3792f4; // 字体颜色变为蓝色
}
.lineStyle.active {
  background-color: #ebf5ff;
}
#bg:hover {
  background-color: #f5f7fa;
}
</style>
