<template>
  <div class="bg-white p-[12px] h-full overflow-auto">
    <Back />
    <main class="m-auto max-w-[1012px]" v-loading="loading">
      <!-- 基本信息 -->
      <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"
        :rowspan-and-colspan="rowspanAndColspan"
        max-height="400px"
        row-key="ids"
        :pagination="pagination.total > 10 ? pagination : undefined"
      >
        <template v-for="col in columns" #[soltName(col)]="{ row }" :key="col.colKey">
          <template v-if="col.colKey == 'dataPermission'">
            <div class="cell-content">
              <p>地区：{{ dataPermissions(row).areaPermissionsTxt }}</p>
              <p>角色：{{ dataPermissions(row).rolePermissionsTxt }}</p>
            </div>
          </template>
          <template v-else-if="col.colKey == 'functionPermission'">
            <div class="cell-content">{{ functionPermission(row) || '-' }}</div>
          </template>
          <template v-else> {{ row[col.colKey as string] || '-' }} </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"
      >
      </t-table>
    </main>
  </div>
</template>

<script setup lang="tsx" name="users-detail">
import { useRoute } from 'vue-router'
import { PrimaryTableCol, PaginationProps, TableProps } from 'tdesign-vue-next'
import { useBasic } from '@/hooks/useBasic'
import { statusTxt } from '@/utils/status'
import { soltName } from '@/utils'
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 = () => {
  loading.value = true
  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 || []
      const tableDatas = list.map(
        (
          e: {
            menuPermission: {
              menuName: string
              buttonNames: string[]
              areaPermissions: { name: string }[]
              rolePermissions: { name: string }[]
            }[]
          },
          index: number
        ) => {
          let lists = []
          if (e.menuPermission.length) {
            lists = e.menuPermission.map((em, i: number) => {
              return { ...e, ...em, ids: `${index}-${i}`, rowspan: !i ? e.menuPermission.length : 0, serial: index + 1 }
            })
          } else {
            lists = [{ ...e, serial: index + 1, ids: `${index}-1` }]
          }

          return [...lists]
        }
      )
      tableData.value = tableDatas.flat()
    })
    .finally(() => {
      loading.value = false
    })
}

const dataPermissions = (row: ResUserList) => {
  const areaPermissions = row.areaPermissions || []
  const rolePermissions = row.rolePermissions || []
  const areaPermissionsTxt = areaPermissions.map((val: { name: string }) => val.name).join(';') || '-'
  const rolePermissionsTxt = rolePermissions.map((val: { name: string }) => val.name).join(';') || '-'

  return { areaPermissionsTxt, rolePermissionsTxt }
}

const functionPermission = (row: ResUserList) => {
  const buttonNames = row.buttonNames || []
  return row.menuName || '-' + (buttonNames.length ? '(' + buttonNames.join(';') + ')' : '')
}

// 合并单元格
const rowspanAndColspan: TableProps['rowspanAndColspan'] = ({ row, colIndex }) => {
  if (colIndex === 1 || colIndex === 0) {
    return {
      colspan: 1,
      rowspan: row?.rowspan
    }
  } else {
    return {
      colspan: 1,
      rowspan: 1
    }
  }
}

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',
    width: 70
  },
  { title: '角色名称', colKey: 'roleName' },
  { 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>
