<template>
  <div style="width: 950px; margin-left: 50px">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="收件人：" prop="mailUserIds">
        <el-input
          v-model="nickName"
          style="width: 40vw; margin-right: 10px"
          placeholder="请选择收件人"
          :disabled="true"
          @click="handleSelect"
        >
        </el-input>
        <el-input v-model="ruleForm.mailUserIds" v-show="false"></el-input>
        <el-button
          @click="handleSelect"
          style="display: inline-block"
          type="primary"
          >选择</el-button
        >

        <el-dialog
          v-model="dialogVisible"
          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
                  @click="toggle(1)"
                  :class="{ selected: fontIndex === 1 }"
                  style="
                    font-size: 17px;
                    width: 110px;
                    margin-left: 20px;
                    border-right: 0;
                    height: 40px;
                    padding-right: 0;
                    cursor: pointer;
                  "
                >
                  常用联系组
                </div>
              </div>

              <div class="head-container"></div>

              <!-- 部门 -->
              <div v-if="show" 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>
              <!-- 常用联系人 -->
              <div v-if="!show">
                <div style="height: 64vh; min-height: 600px; overflow: auto">
                  <div
                    style="cursor: pointer"
                    id="bg"
                    v-for="(item, index) in contactsOptions"
                    :key="index"
                  >
                    <div
                      :class="selectedIndex == index ? 'active' : ''"
                      class="lineStyle"
                      style="padding-left: 20px; font-size: 16px"
                      @click="selectItem(item, index)"
                    >
                      {{ item.groupName }}
                      <div
                        style="
                          display: inline-block;
                          float: right;
                          margin-right: 12px;
                          cursor: pointer;
                        "
                        @click="handleDelete(item)"
                      >
                        <el-tooltip
                          class="box-item"
                          effect="dark"
                          content="删除"
                          placement="bottom"
                        >
                          <el-icon><Close /></el-icon>
                        </el-tooltip>
                      </div>
                    </div>
                  </div>
                </div>
                <!-- <el-tree
                  :data="contactsOptions"
                  node-key="id"
                  :props="{ label: 'label', children: 'children' }"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="tree"
                  default-expand-all
                  @node-click="contactsNodeClick"
                  show-checkbox
                  @check-change="handleCheck2"
                /> -->

                <div style="position: relative; bottom: 0px">
                  <el-button
                    @click="addContact"
                    size="large"
                    style="padding: 0 74px; margin-top: 1vh; text-align: center"
                    type="primary"
                    >添加常用联系组</el-button
                  >
                </div>
              </div>
            </el-col>
            <!-- 常用联系人 -->
            <el-col
              v-if="!show"
              style="margin-left: 40px; margin-top: 5px"
              :span="17"
              :xs="10"
            >
              <el-button
                @click="addContactPeople"
                type="primary"
                style="margin-bottom: 10px"
                >添加常用联系人</el-button
              >
              <!-- <el-button
                @click="delPeople"
                type="danger"
                style="margin-bottom: 10px"
                >删除</el-button
              > -->
              <el-table
                style="height: 650px; overflow: auto"
                :row-key="getRowKeys"
                v-loading="loading"
                ref="multipleTable"
                :data="contactsList"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  :selectable="getSelectable"
                  :reserve-selection="true"
                  type="selection"
                  width="30"
                  align="center"
                />
                <el-table-column
                  label="联系人"
                  align="center"
                  width="280"
                  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-column align="center" label="操作">
                  <template #default="scope">
                    <el-button
                      @click="delPeople(scope.row)"
                      type="danger"
                      text
                      plain
                      ><el-icon><Delete /></el-icon>删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            <!-- 所属部门 -->
            <el-col
              v-if="show"
              style="margin-left: 40px; margin-top: 5px"
              :span="17"
              :xs="10"
            >
              <el-form
                :model="queryParams"
                ref="queryRef"
                :inline="true"
                v-show="showSearch"
                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
                ref="multipleTable1"
                v-loading="loading"
                :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.dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitUserList">
                确认
              </el-button>
            </span>
          </template>
        </el-dialog>
      </el-form-item>
      <div style="display: flex">
        <el-form-item label="邮件标题：" prop="mainTitle">
          <el-input
            v-model="ruleForm.mainTitle"
            style="width: 35vw; margin-right: 10px"
            placeholder="请输入邮件标题"
          />
        </el-form-item>
        <el-form-item prop="mailState">
          <el-checkbox
            @change="checkboxStatus"
            style="width: 3vw"
            :v-model="ruleForm.mailState"
            label="紧急"
            size="large"
          />
        </el-form-item>
      </div>

      <el-form-item label="邮件正文：" prop="mailContent">
        <div style="width: 50vw">
          <Editor1 v-model="ruleForm.mailContent"></Editor1>
        </div>
      </el-form-item>
      <el-form-item label="附件：">
        <el-upload
          style="width: 15vw"
          class="upload-demo"
          :on-success="handleSuccessFiles"
          v-model:file-list="files"
          :headers="upload.headers"
          :action="upload.url"
          name="file"
          multiple
        >
          <template #trigger>
            <el-button>
              上传<el-icon><Upload /></el-icon>
            </el-button>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item style="">
        <div style="width: 50vw; text-align: center">
          <el-button type="primary" @click="submitEmail"
            ><el-icon><Promotion /></el-icon>发送</el-button
          >
          <el-button @click="saveEmail"
            ><el-icon><Checked /></el-icon>存为草稿</el-button
          >
        </div>
      </el-form-item></el-form
    >
    <el-dialog
      v-model="dialogVisible1"
      title="添加常用联系组"
      width="30%"
      :before-close="handleClose"
    >
      <el-form :model="groupInfo" label-width="120px">
        <el-form-item label="常用联系组">
          <el-input v-model="groupInfo.groupName" /> </el-form-item
      ></el-form>
      <template #footer>
        <span style="margin-right: 30px" class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="submitContactGroup">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 选择常用联系人 -->
    <el-dialog
      :append-to-body="true"
      v-model="dialogVisible2"
      title="选择常用联系人"
      width="65%"
      style="height: 850px"
      :before-close="handleClose1"
    >
      <el-row :gutter="20">
        <el-col :span="4" :xs="24">
          <div style="display: flex">
            <div
              style="font-size: 17px; margin-left: 10px; margin-bottom: 10px"
            >
              所属部门
            </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: 35px" :span="18" :xs="10">
          <!-- <el-form
            :model="queryParams"
            ref="queryRef"
            :inline="true"
            v-show="showSearch3"
            label-width="68px"
            style="margin-bottom: 20px"
          >
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                v-model="queryParams3.nickName"
                placeholder="请输入用户昵称"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery3"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery3"
                >搜索</el-button
              >
              <el-button @click="resetQuery3"
                ><el-icon><RefreshRight /></el-icon>重置</el-button
              >
            </el-form-item>
          </el-form> -->
          <!-- 联系人列表 -->
          <el-table
            v-loading="loading1"
            :row-key="getRowKeys"
            ref="multipleTable3"
            :data="userList"
            @selection-change="handleSelectionChange1"
          >
            <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
              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="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="submitPeople"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import Editor1 from "../../../../src/components/Editor1.vue";
import contactPeople from "../../contact/index.vue";
import { parseTime } from "@/utils/ruoyi.js";
import { listUser2, deptTreeSelect2 } from "@/api/system/user";
import {
  listPeoplegroup,
  delPeoplegroup,
  addPeoplegroup,
  updatePeoplegroup,
  addPeople,
} from "@/api/system/contact";
import { selectUsers } from "@/api/email/drafts";
import {
  mail,
  drafts,
  forward,
  editorMail,
  groupList,
  getPeoplegroup,
  addGroup,
  addContacts,
  delPeople,
} from "@/api/email/write";
import { useDict } from "@/utils/dict";
import { detail } from "../../../api/email/inbox";

import { treeselect } from "@/api/system/dept";

export default {
  // props: ["writeValueId"],
  props: {
    writeValueId: Number,
    writeValueId1: Number,
    writeValueId2: Number,
    typeEmail: Number,
    typeEmail1: Number,
  },
  selected: false,
  checked1: false,
  fontIndex: 0,
  formSize: "default",
  components: {
    Editor1,

    contactPeople,
  },
  watch: {
    writeValueId: {
      handler(newValue, oldValue) {
        if (newValue) {
          this.mailId = newValue;
          this.recover();
        }
      },
      deep: true,
      immediate: true,
    },
    writeValueId1: {
      handler(newValue, oldValue) {
        if (newValue) {
          this.mailId1 = newValue;
          this.forwardEmail();
        }
      },
      deep: true,
      immediate: true,
    },
    writeValueId2: {
      handler(newValue, oldValue) {
        if (newValue) {
          this.mailId2 = newValue;
          this.editorMail();
          this.selectUsers();
        }
      },
      deep: true,
      immediate: true,
    },
    typeEmail: {
      handler(newValue, oldValue) {
        if (newValue) {
          this.typeEmail2 = newValue;
          //console.log("this.typeEmail1", this.typeEmail1);
        }
      },
      deep: true,
      immediate: true,
    },
    typeEmail1: {
      handler(newValue, oldValue) {
        if (newValue) {
          this.typeEmail3 = newValue;
          //console.log("this.typeEmail2", this.typeEmail2);
        }
      },
      deep: true,
      immediate: true,
    },
    /** 人员选择器中的 筛选 */
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },

  created() {
    this.recoverId();
    this.forwardId();
    this.getList();
    this.getDeptTree();
    this.listPeoplegroup();

    // const deptOptions = localStorage.getItem("deptOptions");
    // // //console.log("deptOptions", deptOptions);
    // if (deptOptions) {
    //   this.currentNodeKey = JSON.parse(deptOptions).id;
    //   this.expandedKeys = [JSON.parse(deptOptions).id];
    // }
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.mailId = null;
    //   this.mailId2 = null;
    //   this.mailId1 = null;
    // });
  },

  data() {
    return {
      dialogVisible1: false,
      typeEmail3: null,
      typeEmail2: null,
      selectedIndex: 0,

      show: true,
      contactId: null,
      upload: {
        headers: { Authorization: "Bearer " + getToken() },
        url: import.meta.env.VITE_APP_BASE_API + "/system/file/fileupload",
      },
      forwardInfo: {
        mailId: null,
        userIds: [],
      },
      open1: false,

      ruleForm: {
        mailUserIds: [],
        isRead: "N",
        isDel: "N",
        mailState: "1",
        mailType: null,
        sendTime: "",
        files: [],
      },

      fileList: [],
      tctitle: "",
      sys_normal_disable: useDict("sys_normal_disable").sys_normal_disable,
      sys_user_sex: useDict("sys_user_sex").sys_user_sex,
      mail_state: [
        { label: "一般邮件", value: "1" },
        { label: "紧急邮件", value: "2" },
        { label: "特急邮件", value: "3" },
      ],
      dialogVisible: false,
      dialogVisible2: false,
      total: 0,
      title: "",
      open: false,
      userList: [],
      showSearch: true,
      loading: true,
      ids: [],
      idss: [],
      nickName: [],
      single: true,
      multiple: true,
      dateRange: [],
      deptName: "",
      deptOptions: [],
      initPassword: undefined,
      postOptions: [],
      roleOptions: [],
      // 部门id
      depid: [],
      depname: [],
      files: [],
      filterText: "", //人员选择器中的 筛选
      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 },
      ],
      form: {},
      selection: [],
      contactsList: [],
      delIds: [],
      mailUserIds: [],
      // 常用联系人表格数据
      peoplegroupList: [],
      queryParams3: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      contactsOptions: undefined,
      // 查询参数
      queryParams1: {
        pageNum: 1,
        pageSize: 50,
        userId: "1",
      },
      selection1: [],
      groupInfo: {
        groupName: "",
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
        nickName: undefined,
      },
      delPeopleInfo: {
        groupId: undefined,
        userId: undefined,
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 300,
      },
      peopleInfo: {
        groupId: null,
        userIds: [],
      },
      name: [],
      rules: {
        mailUserIds: [
          {
            required: true,
            message: "请选择收件人",
            trigger: "blur",
          },
        ],
        mainTitle: [
          {
            required: true,
            message: "请输入邮件标题",
            trigger: "blur",
          },
        ],
        mailContent: [
          {
            required: true,
            message: "邮件内容不可为空",
            trigger: "blur",
          },
        ],
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "用户名称长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],

        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  methods: {
    //删除常用联系人
    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();
      }
    },
    /** 删除按钮操作 */
    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(() => {});
    },
    // 勾选常用联系人
    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 = [];
      // this.contactsList = [];
      //console.log("this.peopleInfo.userIds1", this.peopleInfo.userIds);

      for (let i = 0; i < this.selection1.length; i++)
        this.peopleInfo.userIds.push(this.selection1[i].userId);
      //console.log("this.peopleInfo.userIds1", this.peopleInfo.userIds);
      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;

      //console.log("888588989", this.contactsList);
      //console.log("5788588", this.userList);

      this.$nextTick(() => {
        this.$refs.multipleTable3.clearSelection();
        this.contactsList.forEach((item) => {
          this.userList.forEach((item1) => {
            if (item.userId == item1.userId) {
              this.$refs.multipleTable3.toggleRowSelection(item1, true);
            }
          });
        });
      });
    },
    //常用联系人名单
    getPeoplegroup() {
      //console.log("this.peopleInfo.groupId", this.peopleInfo.groupId);
      getPeoplegroup(this.peopleInfo.groupId).then((response) => {
        // //console.log("response", response.contactsList);
        this.contactsList = [];
        this.contactsList = response.contactsList;
      });
    },
    //点击
    selectItem(val, index) {
      //console.log("val", val);
      //console.log("index", index);
      this.selectedIndex = index;
      this.peopleInfo.groupId = val.id;
      this.getPeoplegroup();
    },
    //添加常用联系人组
    async submitContactGroup() {
      const isDuplicate = this.contactsOptions.some((v) => {
        return v.groupName === this.groupInfo.groupName;
      });
      //console.log("11111111");
      if (isDuplicate) {
        this.$modal.msgError("已有该常用联系组，请添加其他常用联系组");
      } else {
        let { code } = await addGroup(this.groupInfo);
        if (code == 200) {
          this.$modal.msgSuccess("添加常用联系组成功");
          this.groupInfo.groupName = "";
          this.getContactsTree();
          this.dialogVisible1 = false;
        }
      }
    },

    /** 查询常用联系人列表 */
    listPeoplegroup() {
      this.loading = false;
      this.loading = true;
      listPeoplegroup(this.queryParams1).then((response) => {
        this.peoplegroupList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    addContact() {
      this.dialogVisible1 = true;
    },
    getRowKeys(row) {
      return row.userId;
    },
    //紧急
    checkboxStatus(val) {
      //console.log(val);
      if (val == true) {
        this.ruleForm.mailState = "3";
      } else if (val == false) {
        this.ruleForm.mailState = "1";
      }
    },
    recoverId() {
      // //console.log("8488", this.$route.query.mailId);
      if (this.$route.query.mailId !== undefined) {
        this.mailId = this.$route.query.mailId;
        this.recover();
      }
    },
    forwardId() {
      if (this.$route.query.mailId1 !== undefined) {
        this.mailId1 = this.$route.query.mailId1;
        //console.log("8488", this.mailId1);
        this.forwardEmail();
      }
    },
    async selectUsers() {
      let res = await selectUsers(this.mailId2);
      this.nickName = res;
    },

    //常用联系人
    toggle(numType) {
      this.fontIndex = numType;
      if (numType == 0) {
        this.getDeptTree();
        this.show = true;
      } else if (numType == 1) {
        this.getContactsTree();
        this.resetQuery();
        this.show = false;
        // this.getPeoplegroup();
      }
    },
    // 常用联系人分组树形结构
    async getContactsTree() {
      let { rows } = await groupList(this.queryParams2);
      this.contactsOptions = rows;

      this.peopleInfo.groupId = rows[0].id;
      this.getPeoplegroup();
    },
    ////////////////////////////////////
    //编辑
    async editorMail() {
      this.reset();
      let { data } = await detail(this.mailId2);
      this.ruleForm.sendTime = data.sendTime;
      // this.nickName = data.sendUserName;
      this.ruleForm.mailUserIds = [data.senderUserId];
      this.ruleForm.mailContent = data.mailContent;
      this.ruleForm.mainTitle = data.mainTitle;
      this.files = data.files == null ? [] : data.files;
      this.ruleForm.mailState = data.mailState;
      this.getImagesFromData(data.mailContent);

      this.ruleForm.mailId = data.mailId;
    },
    // //回复
    async recover() {
      this.reset();
      let { data } = await detail(this.mailId);
      // //console.log("data", data);
      // this.userList = data;
      this.ruleForm.sendTime = data.sendTime;
      this.nickName = data.sendUserName;
      this.ruleForm.mailUserIds = [data.senderUserId];
      //console.log("1111111111", this.ruleForm.mailUserIds);
      for (let i = 0; i < [data.senderUserId].length; i++) {
        this.mailUserIds.push({ userId: [data.senderUserId][i] });
      }

      this.ruleForm.mailContent =
        "\n------------------------ 回复邮件信息 -----------------------" +
        "<br>" +
        "<br>" +
        "发件人：" +
        data.sendUserName +
        "<br>" +
        "<br>" +
        "发送时间：" +
        parseTime(data.sendTime, "{y}-{m}-{d} {h}:{i}:{s}") +
        "<br>" +
        "<br>" +
        "主题：" +
        data.mainTitle +
        "<br>" +
        "<br>" +
        "<br>" +
        data.mailContent +
        "<br>" +
        "<br>" +
        "\n--------------------------- 原始邮件 -------------------------" +
        "<br>" +
        "<br>";
      this.ruleForm.mainTitle = "回复：" + data.mainTitle;
      this.files = data.files == null ? [] : data.files;
      this.ruleForm.mailState = data.mailState;
      this.getImagesFromData(data.mailContent);
    },
    // //转发
    async forwardEmail() {
      this.reset();
      //console.log("this.mailId1", this.mailId1);
      let { data } = await detail(this.mailId1);
      this.forwardInfo.mailId = this.mailId1;
      this.ruleForm.sendTime = data.sendTime;
      this.ruleForm.sendUserName = data.sendUserName;
      this.ruleForm.mailUserIds = [data.mailUserIds];
      this.ruleForm.mailContent =
        "\n------------------------ 转发邮件信息 -----------------------" +
        "<br>" +
        "<br>" +
        "发件人：" +
        data.sendUserName +
        "<br>" +
        "<br>" +
        "发送时间：" +
        parseTime(data.sendTime, "{y}-{m}-{d} {h}:{i}:{s}") +
        "<br>" +
        "<br>" +
        "主题：" +
        data.mainTitle +
        "<br>" +
        "<br>" +
        "<br>" +
        data.mailContent +
        "<br>" +
        "<br>" +
        "\n--------------------------- 原始邮件 -------------------------" +
        "<br>" +
        "<br>";
      this.ruleForm.mainTitle = "转发：" + data.mainTitle;
      this.files = data.files == null ? [] : data.files;
      this.ruleForm.mailState = data.mailState;
      this.getImagesFromData(data.mailContent);
    },
    async forward() {
      await forward(this.forwardInfo);
    },
    getImagesFromData(data) {
      // 在这里解析数据，提取图片信息并返回一个包含图片相关属性的数组
      // 例如，假设数据中的图片信息是以<img>标签的形式呈现的：
      const imagePattern =
        /<img\s*src="([^"]+)"\s*alt="([^"]+)"\s*width="(\d+)"\s*height="(\d+)"\s*\/?>/g;
      const images = [];
      let match;
      while ((match = imagePattern.exec(data)) !== null) {
        const src = match[1];
        const alt = match[2];
        const width = parseInt(match[3], 10);
        const height = parseInt(match[4], 10);
        images.push({ src, alt, width, height });
      }
      return images;
    },
    //获取token
    getToken() {
      return getToken();
    },
    // 获取当前时间
    currentTime() {
      var date = new Date();
      this.ruleForm.sendTime = date;
    },
    handleSelect() {
      this.mailUserIds = [];
      this.toggle(0);
      this.getContactsTree();
      this.dialogVisible = true;
    },

    //附件上传
    handleSuccessFiles(response, file, fileList) {
      // //console.log("files", this.files);
      // // 使用map函数遍历fileList，提取每个item的fileId
      // const fileIds = this.fileList.map((item) => {
      //   // //console.log("item", item);
      //   return item.fileId; // 返回每个item的fileId
      // });
      // // //console.log("aaaaaaaaaaaa", fileIds);
      // // 将fileIds数组转换为以逗号分隔的字符串
      // this.ruleForm.filePath = fileIds.join(",");
    },
    submitEmail1() {
      this.$emit("updateUnreadAndDrafts");
    },
    //发布
    submitEmail() {
      this.currentTime();
      //console.log("this.mailId1", this.mailId1);
      this.$refs["ruleFormRef"].validate((valid) => {
        if (valid) {
          //console.log("this.files", this.files);
          if (this.files !== null) {
            for (var i = 0; i < this.files.length; i++) {
              // //console.log("111", this.files[i].response.data);
              if (this.files[i].response == undefined) {
                this.ruleForm.files.push(this.files[i]);
              } else {
                this.ruleForm.files.push(this.files[i].response.data);
              }
            }
          }
          //console.log("mailId1", this.forwardInfo.mailId);
          this.ruleForm.mailType = "2";
          if (this.typeEmail2 == 1) {
            // if (this.forwardInfo.userIds.length == 0) {
            //   this.$modal.msgError("请选择收件人");
            // } else {
            this.forwardInfo.mailId = this.mailId1;
            forward(this.forwardInfo).then((response) => {
              //console.log("转发", response);
              this.$modal.msgSuccess("发送成功");
              this.reset();
              this.$emit("updateUnreadAndDrafts");
            });
            // }
          } else if (this.typeEmail3 == 3) {
            this.ruleForm.mailType = "2";
            editorMail(this.ruleForm).then((response) => {
              this.$modal.msgSuccess("发送成功");
              this.reset();
              this.$emit("updateUnreadAndDrafts");
            });
          } else {
            mail(this.ruleForm).then((response) => {
              //console.log("发布", this.ruleForm);
              this.$modal.msgSuccess("发送成功");
              this.reset();
              this.$emit("updateUnreadAndDrafts");
              this.$refs.multipleTable1.clearSelection();
              this.$refs.multipleTable3.clearSelection();
            });
          }

          this.$emit("updateUnreadAndDrafts");
        }
      });
    },
    //存为草稿
    saveEmail() {
      this.currentTime();
      this.$refs["ruleFormRef"].validate((valid) => {
        if (valid) {
          for (var i = 0; i < this.files.length; i++) {
            if (this.files[i].response == undefined) {
              this.ruleForm.files.push(this.files[i]);
            } else {
              this.ruleForm.files.push(this.files[i].response.data);
            }
          }
          this.ruleForm.mailType = "1";
          //console.log("this.typeEmail1", this.typeEmail2);
          if (this.typeEmail1 == 3) {
            editorMail(this.ruleForm).then((response) => {
              this.$modal.msgSuccess("存为草稿成功");
              this.reset();
              this.$emit("updateUnreadAndDrafts");
            });
          } else {
            drafts(this.ruleForm).then((response) => {
              // //console.log("存为草稿", response);
              this.$modal.msgSuccess("存为草稿成功");
              this.reset();
              this.$emit("updateUnreadAndDrafts");
            });
          }
        }
      });
    },
    //重置
    reset() {
      this.ruleForm = {
        name: [],
        mailUserIds: [],
        mainTitle: "",
        mailContent: "",
        selection: [],
        files: [],
        mailState: "1",
        filePath: null,
      };
      this.ids = [];
      this.idss = [];
      this.files = [];
      this.nickName = [];
      this.selection = [];
      this.getList();
    },
    //分页
    handleSizeChange(newPage) {
      this.queryParams.pageSize = newPage;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    // // 数据
    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 = [];
    },
    /** * 表格单行返回是否可以勾选 */
    getSelectable(row) {
      return row.status !== "REJECT";
    },
    // /** 节点单击事件 */
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },

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

    // /** 查询部门下拉树结构 */
    async getDeptTree() {
      await deptTreeSelect2().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // // 多选框选中数据  常用联系人
    handleSelectionChange(selection) {
      console.log(selection);
      this.selection = [];
      this.selection = selection;
      this.ids = [];
      this.delIds = selection.map((item) => item.userId);
      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;
    },
    //确认收件人
    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.dialogVisible = false;
    },
  },
};
</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>
