<template>
  <div class="bg-white p-[12px] h-full overflow-auto">
    <Back />
    <main class="m-auto max-w-[1012px]">
      <!-- 基本信息 -->
      <PageTitle title="基本信息" class="mb-[24px] mt-[12px]" />
      <div class="flex flex-wrap">
        <DetailTable :label="'用户名'" :value="detailData?.userName" />
        <DetailTable :label="'手机号码'" :value="detailData?.mobile" />
        <DetailTable label="状态">
          <span>
            {{ statusTxt(detailData?.status as number)?.title }}
          </span>
        </DetailTable>
        <DetailTable :label="'添加时间'" :value="detailData?.inputTime" />
        <DetailTable :label="'添加人'" width="100%" :value="detailData?.inputUserName" />
        <DetailTable :label="'用户备注'" width="100%" :value="detailData?.remark" />
      </div>

      <!--    用户角色与权限     -->
      <PageTitle title="用户角色与权限" class="my-[24px]" />
      <t-table
        :data="tableData"
        :columns="columns"
        :loading="loading"
        @page-change="onPageChange"
        max-height="400px"
        :pagination="pagination.total > 10 ? pagination : undefined"
      >
        <!-- 保留自定义列插槽 -->
        <template v-for="(_, name) in $slots" #[name]="scope">
          <slot :name="name" v-bind="scope" />
        </template>
        <template v-for="col in columns" #[col.colKey]="{ row }" :key="col.colKey">
          <template v-if="col.colKey != 'operation'">
            <div class="cell-content">{{ row[col.colKey] || '-' }}</div>
          </template>
        </template>
      </t-table>

      <!--    登录日志     -->
      <PageTitle title="登录日志" class="my-[24px]" />
      <t-table
        :data="tableDataLog"
        :columns="columnsLog"
        :loading="loading"
        max-height="400px"
        @page-change="onLogsPageChange"
        :pagination="paginationLog.total > 10 ? paginationLog : undefined"
      >
        <!-- 保留自定义列插槽 -->
        <template v-for="(_, name) in $slots" #[name]="scope">
          <slot :name="name" v-bind="scope" />
        </template>
        <template v-for="col in columns" #[col.colKey]="{ row }" :key="col.colKey">
          <template v-if="col.colKey != 'operation'">
            <div class="cell-content">{{ row[col.colKey] || '-' }}</div>
          </template>
        </template>
      </t-table>
    </main>
  </div>
</template>

<script setup lang="tsx" name="users-detail">
import { useRoute } from 'vue-router'
import { PrimaryTableCol, PaginationProps } from 'tdesign-vue-next'
import { useBasic } from '@/hooks/useBasic'
import { statusTxt } from '@/utils/status'
import { getUserDetail, getLogs } from '@/api/modules/user-roles/index'
import { ResUserList, ResLog } from '@/api/interface/user-roles/index'

const { setBreadcrumb } = useBasic()

const route = useRoute()

const loading = ref(false)
const detailData = ref<ResUserList>()

// 获取用户详情
const getData = () => {
  getUserDetail({
    userId: route.query.userId as string,
    ...pagination.value
  }).then(res => {
    detailData.value = res.data
    pagination.value.total = res.data?.roleNames?.total as number
    const list = res.data?.roleNames?.list || []
    tableData.value = list.map(
      (e: {
        menuPermission: {
          menuName: string
          buttonNames: string[]
          areaPermissions: { areaName: string }[]
          rolePermissions: { roleName: string }[]
        }[]
      }) => {
        // 匹配对应格式
        let functionPermission: string[] = []
        let dataPermission: string[] = []
        e.menuPermission.map(
          (em: {
            menuName: string
            buttonNames: string[]
            areaPermissions: { areaName: string }[]
            rolePermissions: { roleName: string }[]
          }) => {
            functionPermission.push(em.menuName + em.buttonNames.join(','))
            dataPermission.push(
              em.areaPermissions.map((val: { areaName: string }) => val.areaName).join(',') +
                '-' +
                em.rolePermissions.map((val: { roleName: string }) => val.roleName).join(',')
            )
          }
        )

        return { ...e, functionPermission: functionPermission.join(';'), dataPermission: dataPermission.join(';') }
      }
    )
  })
}

const onPageChange = (val: PaginationProps) => {
  pagination.value.page = val.current as number
  pagination.value.limit = val.pageSize as number
  getData()
}

//   登录日志
const GetLogs = () => {
  getLogs({
    userId: route.query.userId as string,
    ...paginationLog.value
  }).then(res => {
    tableDataLog.value = res.data
    paginationLog.value.total = res.recordsFiltered as number
  })
}

const onLogsPageChange = (val: PaginationProps) => {
  paginationLog.value.page = val.current as number
  paginationLog.value.limit = val.pageSize as number
  GetLogs()
}

// 权限
const tableData = ref<ResUserList[]>([])
const pagination = ref({
  page: 1,
  limit: 10,
  total: 0
})
// 表格columns配置
const columns: PrimaryTableCol[] = [
  {
    title: '序号',
    colKey: 'serial-number',
    width: 70
  },
  { title: '角色名称', colKey: 'userName' },
  { title: '功能权限', colKey: 'functionPermission' },
  { title: '数据权限', colKey: 'dataPermission' }
]

// 日志
const tableDataLog = ref<ResLog[]>([])
const paginationLog = ref({
  page: 1,
  limit: 10,
  total: 0
})
const columnsLog: PrimaryTableCol[] = [
  {
    title: '序号',
    colKey: 'serial-number',
    width: 70
  },
  { title: '登录时间', colKey: 'loginTime' },
  { title: '登录地点', colKey: 'loginAddress' },
  { title: '登录IP', colKey: 'loginIp' },
  { title: '登录设备类型', colKey: 'device' }
]

onMounted(() => {
  setBreadcrumb([
    {
      title: '系统权限'
    },
    {
      title: '用户管理',
      name: 'users'
    },
    {
      title: '用户详情'
    }
  ])
  getData()
  GetLogs()
})
</script>
