<template>
  <div style="display: flex; gap: 20px">
    <div
      v-if="userType === 3 && (userLevel === 2 || userLevel === 3)"
      style="width: 300px"
    >
      <app-area-view-tree
        :default-expanded-keys="code"
        @node-click="fnNavigation({ code: $event.bianma, level: $event.level })"
      />
    </div>
    <div style="flex: 1">
      <app-search v-model="searchForm" :options @submit="resetPagination" />
      <app-table
        ref="tableRef"
        v-model:pagination="pagination"
        :data="list"
        row-key="userId"
        show-selection
        @get-data="getData"
      >
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="roleName" label="角色" />
        <el-table-column v-slot="{ row }" label="部门">
          {{ row.DEPARTMENT_FULL_NAME.replace(",", "/") }}
        </el-table-column>
        <el-table-column prop="dutyName" label="职务" />
        <el-table-column v-slot="{ row }" label="用户类别" width="90">
          <div v-if="row.type === 1">安委会用户</div>
          <div v-else-if="row.type === 2">行业用户</div>
          <div v-else-if="row.type === 3">
            <div v-if="row.grid === '0'">
              <div v-if="row.gridLevel === '1'">一级网格长</div>
              <div v-else-if="row.gridLevel === '2'">二级网格长</div>
              <div v-else-if="row.gridLevel === '3'">三级网格长</div>
            </div>
            <div v-else-if="row.grid === '1'">网格员</div>
            <div v-else>属地用户</div>
          </div>
          <div v-else>其它用户</div>
        </el-table-column>
        <el-table-column prop="lastLogin" label="最近登录" width="140" />
        <el-table-column prop="ip" label="上次登录IP" width="120" />
        <el-table-column v-slot="{ row }" label="操作" width="150">
          <el-button
            type="primary"
            text
            link
            @click="
              router.push({
                url: '/user_management/user/add',
                query: { userId: row.userId },
              })
            "
          >
            修改
          </el-button>
          <el-button
            type="primary"
            text
            link
            @click="fnResetPassword(row.userId, row.username)"
          >
            重置密码
          </el-button>
          <el-button
            type="danger"
            text
            link
            @click="fnDelete(row.userId, row.username)"
          >
            删除
          </el-button>
        </el-table-column>
        <template #button>
          <el-button
            type="primary"
            @click="router.push({ path: '/user_management/user/add' })"
          >
            新建
          </el-button>
          <el-button type="danger" @click="fnDelete('', '')">
            批量删除
          </el-button>
        </template>
      </app-table>
    </div>
  </div>
</template>

<script setup>
import AppSearch from "@/components/search/index.vue";
import { useUserStore } from "@/pinia/user.js";
import { getRoleListAll } from "@/request/system_management.js";
import { ref } from "vue";
import AppAreaViewTree from "@/components/area_view_tree/index.vue";
import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";
import useListData from "@/hooks/useListData.js";
import {
  getUserList,
  setUserDelete,
  setUserResetPassword,
} from "@/request/user_management.js";
import AppTable from "@/components/table/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { DEPARTMENT_CATEGORY_LIST } from "@/assets/js/constant.js";

const userStore = useUserStore();
const {
  rolesId,
  userId,
  type: userType,
  level: userLevel,
} = userStore.getUserInfo;
const router = useRouter();
const route = useRoute();
const defaultQuery = {
  code: "",
  level: "",
};
const code = ref(route.query.code || defaultQuery.code);
const level = ref(route.query.level || defaultQuery.level);
const roleList = ref([]);
const { list, pagination, searchForm, getData, resetPagination, tableRef } =
  useListData(getUserList, {
    params: () => ({
      code: code.value,
      level: level.value,
    }),
  });
const options = [
  { key: "roleName", label: "关键字", tip: "帐号、姓名、手机号" },
  {
    key: "type",
    label: "部门类别",
    type: "select",
    options: DEPARTMENT_CATEGORY_LIST,
    hidden: !(rolesId?.indexOf("1") !== -1 || userId === "1"),
  },
  { key: "departmentName", label: "部门名称" },
  {
    key: "roleId",
    label: "角色",
    type: "select",
    options: roleList,
    valueKey: "roleId",
    labelKey: "roleName",
  },
];
(async () => {
  const resData = await getRoleListAll();
  roleList.value = resData.roleList;
})();
const fnResetPassword = async (userId, name) => {
  await ElMessageBox.confirm(
    `"确定要将【${name}】的密码重置为[Aqsc@0335]吗?"`,
    { type: "warning" }
  );
  await setUserResetPassword({ userId });
  ElMessage.success("重置成功");
  resetPagination();
};
const fnDelete = async (userId, name) => {
  let ids = [];
  if (userId) {
    await ElMessageBox.confirm(`"确定要删除【${name}】吗?"`, {
      type: "warning",
    });
    ids.push(userId);
  } else {
    ids = tableRef.value.getSelectionRows();
    if (ids.length === 0) {
      return ElMessage.error("请选择要删除的数据");
    }
    await ElMessageBox.confirm(
      `"确定要删除【${ids.map((item) => item.username).join("、")}】吗?"`,
      {
        type: "warning",
      }
    );
  }
  await setUserDelete({ ids });
  ElMessage.success("删除成功");
  resetPagination();
};
onBeforeRouteUpdate((to) => {
  code.value = to.query.code || defaultQuery.code;
  level.value = to.query.level || defaultQuery.level;
  resetPagination();
});
const fnNavigation = (query) => {
  router.push({
    path: "/user_management/user",
    query: {
      ...route.query,
      ...query,
    },
  });
};
</script>

<style scoped></style>
