<template>
  <div class="user-page">
    <SearchForm
      ref="searchFormRef"
      :departmentList="departmentList"
      :roleData="roleData"
      @get-table-data="onSearchCommit"
      @reset-form="onResetForm"
    />
    <el-card>
      <template #header>
        <el-space align="center">
          <el-button @click="openAddAdminDrawer" v-if="!isSysTenant && isCanAddTenant && hasAddPermission()">
            <template #icon>
              <el-icon>
                <Plus />
              </el-icon>
            </template>
            添加租户管理员
          </el-button>
          <el-button type="primary" @click="openAddSingleDrawer" v-permission="{ action: [PERM_USER.ACCOUNT_ADD] }">
            <template #icon>
              <el-icon>
                <Plus />
              </el-icon>
            </template>
            添加用户
          </el-button>
          <el-button color="#1890FF" @click="openAddMultipleDrawer" style="margin-left: 18px" plain  v-permission="{ action: [PERM_USER.ACCOUNT_ADD] }">
            <template #icon>
              <el-icon>
                <DocumentAdd />
              </el-icon>
            </template>
            批量导入
          </el-button>
        </el-space>
      </template>

      <el-table height="calc(100vh - 340px)" :data="userList" row-key="id">
        <el-table-column label="工号" prop="staffNo">
          <template #default="scope">
            <div>
              <span style="margin-left: 10px">{{ scope.row.staffNo }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="登录账号" prop="username" width="150">
          <template #default="scope">
            <div class="account">
              {{ scope.row.username }}
              <el-tooltip
                class="box-item"
                effect="dark"
                content="租户管理员账号，自动拥有全部相机查看权限及功能权限"
                placement="top-start"
                v-if="scope.row.roleType === RoleTypeEnum.TENANT_ADMIN"
              >
                <el-icon color="#409efc">
                  <Stamp />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="姓名" prop="realname" />
        <el-table-column label="手机" prop="mobile" />
        <el-table-column label="状态" prop="isDisabled">
          <template #default="scope">
            <div>
              <el-tag :type="!scope.row.isDisabled ? 'success' : 'danger'">
                {{ !scope.row.isDisabled ? '正常' : '锁定' }}</el-tag
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="角色" prop="roleList">
          <template #default="scope">
            <div>
              {{ tranformRoleList(scope.row.roleList) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="组织" prop="deptList">
          <template #default="scope">
            <div>
              {{ tranformDeptList(scope.row.deptList) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="认证方式" prop="certify" />
        <el-table-column label="创建时间" prop="createdAt" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-space v-if="scope.row.roleType !== RoleTypeEnum.SUPER_ADMIN">
              <div class="el-space el-space--horizontal">
                <div
                  class="el-space__item"
                  @click="handleEdit(scope.row)"
                  v-permission="{ action: [PERM_USER.ACCOUNT_EDIT] }"
                >
                  <div><img :src="editIcon" class="el-tooltip__trigger" /></div>
                </div>
                <div
                  class="el-space__item"
                  @click="handleDelete(scope.row)"
                  v-permission="{ action: [PERM_USER.ACCOUNT_DELETE] }"
                >
                  <div><img :src="deleteIcon" class="el-tooltip__trigger" /></div>
                </div>
                <div
                  class="el-space__item"
                  v-if="visibleRestPassBtn(scope.row.roleType) && hasResetPasswordPermission()"
                  @click="handleResetCode(scope.row)"
                >
                  <div class="tooltip__password">重置密码</div>
                </div>
              </div>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <section class="mt-4 flex justify-end">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :page-sizes="[10, 30, 50]"
          :total="total"
          v-model:page-size="params.pageSize"
          v-model:current-page="params.pageNumber"
          @change="loadPageData"
        />
      </section>
    </el-card>
    <CreateDrawer
      ref="createDrawerRef"
      :title="drawerTitle"
      @change="reloadTable"
      :departmentList="departmentList"
      :roleData="roleData"
      :width="450"
    />
    <ResetCodeDrawer ref="ResetCodeDrawerRef" :title="drawerTitle" @change="reloadTable" />
    <CreateAdminDrawer
      ref="createAdminDrawerRef"
      :title="createAdminTitle"
      @change="reloadTable"
      :editType="createAdminType"
      :roleData="roleData"
      :width="450"
      :isCanAddTenant="isCanAddTenant"
      :isSysTenant="isSysTenant"
      :departmentList="departmentList"
    />
    <AddUser
      v-if="showAddPopover"
      :colseAddUser="setShowAddPopoverFalse"
      v-model="showAddPopover"
      class="add-popover"
      @change="reloadTable"
    />
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue';
  import { storeToRefs } from 'pinia';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Plus, DocumentAdd, Edit, Delete, Stamp } from '@element-plus/icons-vue';
  import { EditType, OptionsProps, SearchParamsProps } from './types';
  import { RoleTypeEnum } from '@/types/role/constants';
  import useSceneInfos from '@/hooks/useSceneInfos';
  import { getAllDepartments } from '@/api/auth/dept';
  import { getRoles } from '@/api/system/role';
  import { getUserList, UserLisItem, deleteUser } from '@/api/system/user-operate';
  import { ResultEnum } from '@/enums/httpEnum';
  import { useTargetTenantIdSetting } from '@/utils/useTargetTenantIdSetting';
  import { useUserStore } from '@/store/modules/user';
  import type { RoleListItem } from '@/api/system/user-operate';
  import type { DeptTreeItem } from '@/api/system/user-query';
  import SearchForm from './component/SearchForm.vue';
  import AddUser from './component/AddUser.vue';
  import CreateDrawer from './CreateDrawer.vue';
  import ResetCodeDrawer from './ResetCodeDrawer.vue';
  import CreateAdminDrawer from './CreateAdminDrawer.vue';
  import editIcon from '@/assets/images/reportmessage/edit.png';
  import deleteIcon from '@/assets/images/reportmessage/delete.png';
  import { SYS_TENANT_ID } from '@/utils/useTargetTenantIdSetting';
  import { PERM_USER } from '@/types/permission/constants';

  const userStore = useUserStore();
  const { getUserInfo } = storeToRefs(userStore);
  const sceneInfos = useSceneInfos();
  const { calculateTreeData } = sceneInfos;
  const userList = ref<UserLisItem[]>([]);
  const searchFormRef = ref<InstanceType<typeof SearchForm>>();
  const createDrawerRef = ref<InstanceType<typeof CreateDrawer>>();
  const ResetCodeDrawerRef = ref<InstanceType<typeof ResetCodeDrawer>>();
  const createAdminDrawerRef = ref<InstanceType<typeof CreateAdminDrawer>>();
  const drawerTitle = ref('添加用户');
  const createAdminTitle = ref('添加租户管理员');
  const roleData = ref<OptionsProps[]>([]);
  const departmentList = ref<OptionsProps[]>([]);
  const createAdminType = ref(EditType.create);
  const { isSysTenant } = useTargetTenantIdSetting();

  function reloadTable() {
    loadPageData();
  }

  const hasResetPasswordPermission = () => userStore.checkPermission(PERM_USER.ACCOUNT_RESET_PASSWORD);
  const hasAddPermission = () => userStore.checkPermission(PERM_USER.ACCOUNT_ADD);
  // 当前用户类型
  const currrentRoleType = getUserInfo.value.roleType;
  const currrentTenantId = getUserInfo.value.tenantId;
  // 是否拥有添加租户管理人员权限，条件：1.系统用户，2.选择租户切换到租户选项
  const isCanAddTenant = Number(currrentRoleType) !== RoleTypeEnum.TENANT_ADMIN && currrentTenantId === SYS_TENANT_ID;
  const openAddSingleDrawer = () => {
    drawerTitle.value = '添加用户';
    if (isSysTenant) {
      createAdminTitle.value = '添加用户';
      createAdminType.value = EditType.create;
      createAdminDrawerRef.value?.openDrawer();
    } else {
      createDrawerRef.value?.openDrawer();
    }
  };
  const openAddAdminDrawer = () => {
    createAdminTitle.value = '添加租户管理员';
    createAdminDrawerRef.value?.openDrawer();
    createAdminType.value = EditType.create;
  };

  const showAddPopover = ref<boolean>(false);
  const openAddMultipleDrawer = () => {
    showAddPopover.value = true;
  };

  //传个方法到子组件，当上传成功后把showAddPopover的值改为false；
  const setShowAddPopoverFalse = () => {
    showAddPopover.value = false;
  };

  function handleEdit(record: Recordable) {
    drawerTitle.value = '编辑用户';
    if (record.roleType === RoleTypeEnum.TENANT_ADMIN || isSysTenant) {
      createAdminDrawerRef.value?.openDrawer(record.id);
      createAdminType.value = EditType.edit;
    } else {
      createDrawerRef.value?.openDrawer(record.id);
    }
  }

  function handleResetCode(record: Recordable) {
    drawerTitle.value = '重置密码';
    ResetCodeDrawerRef.value?.openDrawer(record.username, record.id);
  }

  function handleDelete(record: Recordable) {
    ElMessageBox.confirm('确认要删除该用户吗', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        deleteUser({ userId: record.id }).then((res) => {
          if (res.code === ResultEnum.SUCCESS) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            });
            loadPageData();
          }
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        });
      });
  }

  /* 是否能重置密码 */
  const visibleRestPassBtn = (type: RoleTypeEnum): boolean => {
    if (isSysTenant || (!isSysTenant && type !== RoleTypeEnum.TENANT_ADMIN) || currrentTenantId === SYS_TENANT_ID) {
      return true;
    }
    return false;
  };

  onMounted(async () => {
    loadPageData();
    getAllDepartments().then((res) => {
      departmentList.value = calculateTreeData(res, { level: 10, valueKey: 'id', labelKey: 'deptName' }, 1);
    });
    const res = (await getRoles()) || [];
    roleData.value = res.map((item: any) => {
      return {
        value: item.id,
        label: item.roleName,
      };
    });
  });

  // 基本参数
  const params = reactive<SearchParamsProps>({
    pageNumber: 1,
    pageSize: 10,
    queryParam: {},
  });

  // 获取页面数据
  const total = ref(0);
  const loadPageData = () => {
    const searchFormData = searchFormRef.value?.getSearchFromData();
    if (searchFormData) {
      const { queryType, queryTypeContent } = searchFormData;
      Object.entries(searchFormData).forEach(([key, value]) => {
        if (value) {
          if (['deptId', 'roleId'].includes(key)) {
            params.queryParam[key] = value;
          }
          if (queryType) {
            params.queryParam[queryType] = queryTypeContent;
          }
        }
      });

      // 删除多余参数
      delteExtraParams(queryType);
      getUserList(params).then((res) => {
        userList.value = res.records;
        userList.value.forEach((item) => {
          item.certify = '本地认证';
        });
        total.value = res.totalRow;
      });
    }
  };

  const extraParams = ['realname', 'mobile', 'staffNo'];
  const delteExtraParams = (type) => {
    const needDeleteArr = extraParams.filter((item) => item !== type);
    needDeleteArr.forEach((item) => {
      delete params.queryParam[item];
    });
  };

  //  获取列表数据
  const onSearchCommit = () => {
    loadPageData();
  };

  // 重置列表数据
  const onResetForm = () => {
    params.pageNumber = 1;
    params.pageSize = 10;
    params.queryParam = {};
    loadPageData();
  };

  const tranformRoleList = (arr: RoleListItem[]) => {
    if (arr && arr.length === 0) return '--';
    return arr?.map((item) => item.roleName).join(',');
  };

  const tranformDeptList = (arr: DeptTreeItem[]) => {
    if (arr && arr.length === 0) return '--';
    return arr.at(-1)?.deptName;
  };
</script>
<style scoped>
  .user-page {
    position: relative;
    height: calc(100vh - 64px - 12px);
    background-color: #ffffff;
  }

  .user-list {
    padding: 0 21px;
  }

  .add-popover {
    position: absolute;
    width: 593px;
    height: 435px;
    left: 50%;
    top: 50%;
    margin-top: -218px;
    margin-left: -297px;
    z-index: 99;
  }

  .el-space--horizontal {
    align-items: center;
    gap: 0px 20px;
  }

  .el-tooltip__trigger {
    width: 16px;
  }

  .tooltip__password {
    color: var(--el-color-primary);
  }

  .box-item {
    position: absolute;
    top: 0;
    left: 0;
  }

  .el-space__item:hover {
    cursor: pointer;
  }

  .account {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
</style>
