<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="108px"
    >
      <el-form-item label="常用联系人组" prop="groupName">
        <el-input
          v-model="queryParams.groupName"
          placeholder="请输入联系人组"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" size="mini" @click="handleQuery"
          ><el-icon><Search /></el-icon>搜索</el-button
        >
        <el-button size="mini" @click="resetQuery"
          ><el-icon><RefreshRight /></el-icon>重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:peoplegroup:add']"
          ><el-icon><Plus /></el-icon>新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:peoplegroup:edit']"
          ><el-icon><Edit /></el-icon>修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:peoplegroup:remove']"
          ><el-icon><DeleteFilled /></el-icon>删除</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="peoplegroupList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        type="index"
        width="105"
        label="序号"
        align="center"
        prop="id"
      />
      <el-table-column label="常用联系人组" align="center" prop="groupName" />

      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:peoplegroup:edit']"
            ><el-icon><Edit /></el-icon>编辑</el-button
          >
          <el-button
            size="mini"
            text
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:peoplegroup:remove']"
            ><el-icon><Delete /></el-icon>删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-right: 20px">
      <pagination
        style="margin-right: 20px"
        v-show="total1 > 0"
        :total="total1"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList1"
      />
    </div>

    <!-- 添加或修改常用联系人对话框(联系人组) -->
    <el-dialog
      :modal-append-to-body="false"
      :title="title"
      v-model="open"
      width="40%"
      style="min-height: 20vh"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <div style="display: flex">
          <el-form-item label="常用联系人组" prop="groupName">
            <el-input
              v-model="form.groupName"
              placeholder="请输入常用联系人组名称"
            />
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
        </div>

        <el-divider content-position="center">常用联系人信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" size="mini" @click="handleAddContacts"
              ><el-icon><Plus /></el-icon>添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" size="mini" @click="handleDeleteContacts"
              ><el-icon><DeleteFilled /></el-icon>删除</el-button
            >
          </el-col>
        </el-row>

        <el-dialog
          :append-to-body="true"
          v-model="dialogVisible"
          title="选择常用联系人"
          width="55%"
          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="queryParams1"
                ref="queryRef"
                :inline="true"
                v-show="showSearch1"
                label-width="68px"
                style="margin-bottom: 20px"
              >
                <el-form-item label="用户昵称" prop="nickName">
                  <el-input
                    v-model="queryParams1.nickName"
                    placeholder="请输入用户昵称"
                    clearable
                    style="width: 240px"
                    @keyup.enter="handleQuery1"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery1"
                    >搜索</el-button
                  >
                  <el-button @click="resetQuery1"
                    ><el-icon><RefreshRight /></el-icon>重置</el-button
                  >
                </el-form-item>
              </el-form>

              <el-table
                @getSelectionRows="getSelectionRows"
                v-loading="loading1"
                :row-key="getRowKeys"
                ref="multipleTable"
                :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="queryParams1.pageNum"
                  v-model:page-size="queryParams1.pageSize"
                  :page-sizes="[10, 20, 30, 50]"
                  :small="small"
                  :disabled="disabled"
                  :background="background"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total1"
                  @size-change="handleSizeChange1"
                  @current-change="handleCurrentChange1"
                />
              </div>
            </el-col>
          </el-row>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitUserList">
                确认
              </el-button>
            </span>
          </template>
        </el-dialog>
        <el-table
          style="min-height: 545px"
          :data="contactsList"
          :row-class-name="rowContactsIndex"
          @selection-change="handleContactsSelectionChange"
          ref="contacts"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            style="width: 10vw"
          />
          <el-table-column
            align="center"
            label="常用联系人"
            prop="nickName"
            style="width: 10vw"
          >
          </el-table-column>
        </el-table>
      </el-form>
      <div
        style="margin-left: 80vw; margin-top: 20px"
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="cancel">取 消</el-button>

        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPeoplegroup,
  getPeoplegroup,
  delPeoplegroup,
  addPeoplegroup,
  updatePeoplegroup,
  addPeople,
} from "@/api/system/contact";

import { mail, drafts, forward, editorMail } from "@/api/email/write";
import { useDict } from "@/utils/dict";
import { detail } from "@/api/email/inbox";
import { getToken } from "@/utils/auth";
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
  deptTreeSelect,
} from "@/api/system/user";
export default {
  name: "Peoplegroup",
  data() {
    return {
      getRowKeys(row) {
        return row.mailUserId;
      },
      userList: [],
      open1: false,
      loading1: true,
      showSearch1: true,
      ids1: [],
      single1: true,
      multiple: true,
      total1: 0,
      form1: {},
      dateRange: [],
      deptName: "",
      deptOptions: [],
      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 },
      ],
      queryParams1: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      ////////////////////////////////////////////
      formContact: {},
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedContacts: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 常用联系人表格数据
      peoplegroupList: [],
      // 常用联系人表格数据
      contactsList: [],
      // 弹出层标题
      title: "",
      title1: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: "1",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        groupName: [
          {
            required: true,
            message: "常用联系人组名称不能为空",
            trigger: "blur",
          },
        ],
      },
      rules1: {
        contactName: [
          { required: true, message: "联系人不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getList1();
    this.getDeptTree();

    const deptOptions = localStorage.getItem("deptOptions");
    if (deptOptions) {
      this.currentNodeKey = JSON.parse(deptOptions).id;
      this.expandedKeys = [JSON.parse(deptOptions).id];
    }
  },
  methods: {
    // // 多选框选中数据
    handleSelectionChange1(selection) {
      this.selection = [];
      this.selection = selection;

      this.single = this.selection.length !== 1;
    },
    //确认常用联系人
    submitUserList() {
      for (let i = 0; i < this.selection.length; i++)
        this.contactsList.push({
          userId: this.selection[i].userId,
          nickName: this.selection[i].nickName,
        });
      this.dialogVisible = false;
      //   await addPeople();
    },
    // /** 查询部门下拉树结构 */
    async getDeptTree() {
      await deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },

    // // 数据
    async getList1() {
      this.loading = true;
      await listUser(this.addDateRange(this.queryParams1, this.dateRange)).then(
        (res) => {
          this.loading1 = false;
          this.userList = res.rows;
          this.total1 = res.total;
        }
      );
      this.selection = [];
    },
    /** 查询常用联系人列表 */
    getList() {
      this.loading = false;
      this.loading = true;
      listPeoplegroup(this.queryParams).then((response) => {
        this.peoplegroupList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    //分页
    handleSizeChange1(newPage) {
      this.queryParams1.pageSize = newPage;
      this.getList1();
    },
    handleCurrentChange1(val) {
      this.queryParams1.pageNum = val;
      this.getList1();
    },
    //联系人表单重置
    reset1() {
      this.ruleForm = {
        name: [],
        mailUserIds: [],
        mainTitle: "",
        mailContent: "",
        selection: [],
        files: [],
        mailState: "1",
        filePath: null,
      };
      this.ids = [];
      this.idss = [];
      this.files = [];
      this.nickName = [];
      this.selection = [];
      this.getList();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        groupName: null,
        userId: null,
        createTime: null,
        createBy: null,
        remark: null,
      };
      this.contactsList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery1() {
      this.queryParams1.pageNum = 1;
      this.getList1();
    },
    // /** 重置按钮操作 */
    resetQuery1() {
      this.dateRange = [];
      this.resetForm("queryRef");
      this.queryParams1.deptId = undefined;
      this.$nextTick(() => {
        this.$refs.deptTreeRef.setCurrentKey(null);
      });

      this.handleQuery1();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加常用联系人";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      //   this.reset1();
      const id = row.id || this.ids;
      getPeoplegroup(id).then((response) => {
        this.form = response;
        this.contactsList = response.contactsList;
        this.open = true;
        this.title = "编辑常用联系人";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.contactsList = this.contactsList;
          if (this.form.id != null) {
            updatePeoplegroup(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPeoplegroup(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除该常用联系人组？")
        .then(function () {
          return delPeoplegroup(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 常用联系人序号 */
    rowContactsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 常用联系人添加按钮操作 */
    handleAddContacts() {
      this.dialogVisible = true;
      this.title1 = "添加常用联系人";
      this.getDeptTree();
      this.getList1();
      //   let obj = {};
      //   obj.userId = "";
      //   obj.remark = "";
      //   this.contactsList.push(obj);
    },
    //确认常用联系人
    submitContact() {
      addPeople(this.formContact).then((response) => {});
    },
    /** 常用联系人删除按钮操作 */
    handleDeleteContacts() {
      if (this.checkedContacts.length == 0) {
        this.$modal.msgError("请先选择要删除的常用联系人数据");
      } else {
        const contactsList = this.contactsList;
        const checkedContacts = this.checkedContacts;
        this.contactsList = contactsList.filter(function (item) {
          return checkedContacts.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中数据 */
    handleContactsSelectionChange(selection) {
      this.checkedContacts = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/peoplegroup/export",
        {
          ...this.queryParams,
        },
        `peoplegroup_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
::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;
}
</style>
