<template>
  <div class="app-container">
    <el-dialog
      title="选择值班人员"
      :modelValue="true"
      width="60%"
      :show-close="false"
      @close="() => emit('canal')"
    >
      <el-row :gutter="20">
        <el-col style="overflow-x: scroll" :span="6">
          <div style="display: flex">
            <div
              style="font-size: 17px; margin-left: 10px; margin-bottom: 10px"
            >
              所属部门
            </div>
          </div>

          <div class="head-container">
            <el-tree
              style="font-size: 15px; width: 235px"
              :reserve-selection="false"
              :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="padding-left: 80px; margin-top: 32px" :span="16">
          <!-- 联系人列表 -->
          <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                v-model="queryParams.nickName"
                placeholder="请输入用户昵称"
                clearable
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" size="mini" @click="handleQuery11"
                ><el-icon><Search /></el-icon>搜索</el-button
              >
              <el-button size="mini" @click="resetQuery11"
                ><el-icon><RefreshRight /></el-icon>重置</el-button
              >
            </el-form-item>
          </el-form>
          <el-table
            style="height: 350px; overflow: auto"
            v-loading="loading"
            :row-key="(row) => row.userId"
            ref="multipleTableRef"
            :data="userList"
            @selection-change="handleSelectionChangeEdit"
          >
            <el-table-column
              :selectable="getSelectable"
              :reserve-selection="true"
              type="selection"
              width="50"
              align="center"
            />
            <el-table-column
              label="用户昵称"
              align="center"
              key="nickName"
              prop="nickName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="所属部门"
              align="center"
              key="deptName"
              prop="dept.deptName"
              :show-overflow-tooltip="true"
            />
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>
      <span style="margin-left: 46vw; margin-top: 50px" class="dialog-footer">
        <el-button @click="$emit('canal')">取 消</el-button>
        <el-button
          type="primary"
          @click="
            $emit('submit1', selectUserListEdit);
            selectUserListEdit = [];
            queryParams.nickName = '';
            multipleTableRef.clearSelection();
          "
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script setup name="selectPersonnel">
import { onMounted, ref } from "vue";
import { deptTreeSelect2, listUser } from "@/api/system/user";
import { addDateRange } from "@/utils/ruoyi";
// 部门
const deptOptions = ref([]);
// 用户
const userList = ref([]);
const loading = ref(false);
const total = ref(0);
// 查询条件
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  peopleStatus: 0,
  nickName: "",
});

const selectUserList = ref([]);
const selectUserListEdit = ref([]);
const multipleTableRef = ref(null);

let props = defineProps(["type", "selectedList", "selectNow"]);
const emit = defineEmits(["getList"]);

const selectedItems = ref([]);
const userNames = ref(undefined);
const Names = ref(undefined);
const single = ref(undefined);
const multiple = ref(undefined);

function handleSelectionChangeEdit(users) {
  console.log("users", users);
  // let users1 = [];

  const startIndex = users.findIndex((item) => item.sex !== undefined);

  const users1 = startIndex !== -1 ? users.slice(startIndex) : [];

  console.log("users1", users1);
  userNames.value = [];
  Names.value = [];
  const uniqueArray = [...new Set(users1)];
  if (uniqueArray.length != 0) {
    userNames.value = uniqueArray.map((item) => item.userId).join(",");
    Names.value = uniqueArray
      .map((item) => {
        const sexPart =
          item.sex == 0 || item.sex == 1
            ? `(${item.sex == 1 ? "女" : "男"})`
            : "";
        return item.nickName + sexPart;

        // 检查 item.sex 是否存在，如果存在，根据其值决定拼接"女"或"男"
      })
      .join(",");
    selectUserListEdit.value = [];

    selectUserListEdit.value.push({
      userName: Names.value,
      userIds: userNames.value,
      type: props.type,
    });
    console.log("selectUserListEdit", selectUserListEdit.value);
  }
}

// 节点点击
function handleNodeClick(data) {
  queryParams.value.deptId = data.id;
  handleQuery();
  selectUserListEdit.value = [];
}
function handleQuery11() {
  getList();
}
function handleQuery() {
  queryParams.value.pageNum = 1;
  // queryParams.value.sex = props.sex;
  getList();
}

// 查询部门
async function getDeptTree() {
  const { data } = await deptTreeSelect2();
  deptOptions.value = data;
}

async function getList() {
  loading.value = true;
  let res = await listUser(addDateRange(queryParams.value, []));
  loading.value = false;
  userList.value = res.rows;
  total.value = res.total;
  let arrUserIds = [];
  arrUserIds = props.selectNow.userIds.split(",");
  let arrUserName = [];
  arrUserName = props.selectNow.userName.split(",");
  if (arrUserIds.length > 0) {
    let combinedArray = [];
    combinedArray = arrUserIds.map((id, index) => {
      return {
        userId: id,
        nickName: arrUserName[index],
      };
    });

    combinedArray.forEach((item) => {
      // multipleTableRef.value.toggleRowSelection(item, true);
    });
  }
}

onMounted(() => {
  getDeptTree();
  handleQuery();
});

// let map = [];
// map = props.selectedList;
// props.selectedList.forEach((row) => {
//   map = row;
//   console.log("map", map);
//   // console.log("map[row.userId]", map[row.userId]);
// });
/** * 表格单行返回是否可以勾选 */
function getSelectable(row) {
  return row.status !== "REJECT";
}
</script>
<style scoped>
::v-deep .el-checkbox__input.is-disabled .el-checkbox__inner {
  background-color: #dbe0e6;
  border-color: #d2d5dd;
  cursor: not-allowed;
}
</style>
