<template>
  <div class="main-box">
    <TreeFilter
      v-if="false"
      ref="treeFilterRef"
      title="部门列表"
      :request-api="getUserDepartment"
      :default-value="initParam.deptId"
      @change="changeTreeFilter"
    />
    <div class="table-box">
      <ProTable
        ref="proTable"
        :columns="columns"
        :request-api="getTableList"
        :init-param="initParam"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button v-auth="['system:user:add']" type="primary" :icon="CirclePlus" @click="openDialog()">新增</el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <template v-if="!scope.row.admin">
            <el-button v-auth="['system:user:edit']" type="primary" link :icon="EditPen" @click="openDialog(scope.row.userId)">
              编辑
            </el-button>
            <el-button v-auth="['system:user:resetPwd']" type="primary" link :icon="Refresh" @click="resetPass(scope.row)">
              重置密码
            </el-button>
            <el-button v-auth="['system:user:remove']" type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">
              删除
            </el-button>
          </template>
        </template>
      </ProTable>
      <ResetPwd ref="resetPwdRef" />
      <UserDialog ref="dialogRef" />
    </div>
  </div>
</template>
<script setup lang="ts" name="accountManage">
import { ref, reactive, provide } from "vue";
import { ElMessage } from "element-plus";
import { User } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import ResetPwd from "@/components/ResetPwd/index.vue";
import UserDialog from "./components/UserDialog.vue";
import { getDictOptions } from "@/api/modules/common";
import { getUserList, deleteUser, getUserDepartment } from "@/api/modules/system/user";
import { CirclePlus, Delete, EditPen, Refresh } from "@element-plus/icons-vue";

// ProTable 实例
const proTable = ref<ProTableInstance>();
const resetPwdRef = ref<typeof ResetPwd>();
const treeFilterRef = ref<typeof TreeFilter>();
provide("getDeptTree", () => {
  return treeFilterRef.value?.treeAllData.filter((item: any) => item.id > 0);
});

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ deptId: "" });

// 树形筛选切换
const changeTreeFilter = (val: string) => {
  proTable.value!.pageable.pageNum = 1;
  initParam.deptId = val;
};

// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { prop: "userId", label: "用户编号", width: 100 },
  { prop: "userName", label: "用户名", search: { el: "input" } },
  { prop: "nickName", label: "姓名" },
  { prop: "deptId", label: "部门", render: scope => scope.row.dept?.deptName || "-" },
  { prop: "phonenumber", label: "手机号码", search: { el: "input" } },
  {
    prop: "status",
    label: "状态",
    sortable: true,
    enum: () => getDictOptions("sys_normal_disable"),
    search: { el: "select" },
    fieldNames: { label: "dictLabel", value: "dictValue" }
  },
  { prop: "createTime", label: "创建时间", search: { el: "date-range-picker", custom: true } },
  { prop: "operation", label: "操作", width: 330, fixed: "right" }
]);
// 分页列表获取数据
const getTableList = (params: User.ReqUserParams) => {
  if (params.createTime) {
    const [beginTime, endTime] = params.createTime;
    params.params = {
      beginTime,
      endTime
    };
    delete params.createTime;
  }
  return getUserList(params);
};

// 删除用户信息
const deleteAccount = async (params: User.ResUserList) => {
  await useHandleData(deleteUser, [params.userId], `删除用户【${params.userName}】`);
  proTable.value?.getTableList();
};

// 重置用户密码
const resetPass = async (params: User.ResUserList) => {
  await resetPwdRef.value?.open(params);
  proTable.value?.getTableList();
  ElMessage.success("重置成功");
};

// 打开 drawer(新增、查看、编辑)
const dialogRef = ref<InstanceType<typeof UserDialog> | null>(null);
const openDialog = (userId?: number) => {
  dialogRef.value?.open(userId).then(proTable.value?.getTableList);
};
</script>
