<template>
  <Drawer :drawer-visible="drawerVisible" width="640" title="操作日志" :footer="false" @close="close">
    <SearchWithButton
      :loading="loading"
      placeholder="操作人姓名"
      v-model="condInputUserName"
      @on-search="handleSearch"
      @clear="handleSearch"
      class="mb-[18px]"
    />
    <t-table
      :data="tableData"
      :columns="columns"
      :loading="loading"
      @page-change="onPageChange"
      max-height="750px"
      :pagination="pagination"
    >
      <!-- 保留自定义列插槽 -->
      <template v-for="(_, name) in $slots" #[name]="scope">
        <slot :name="name" v-bind="scope" />
      </template>
    </t-table>
  </Drawer>
</template>

<script setup lang="tsx" name="menu-log">
import { PrimaryTableCol, PaginationProps } from 'tdesign-vue-next'
import { ResMenu } from '@/api/interface/menu/index'
import { getOperations } from '@/api/modules/menu'
import { menuLevelTxt } from '../utils'

const drawerVisible = ref(false)

const condInputUserName = ref('')
const loading = ref(false)
const tableData = ref<ResMenu[]>([])

const pagination = ref<PaginationProps>({
  current: 1,
  pageSize: 10,
  total: 0
})
// 表格columns配置
const columns: PrimaryTableCol[] = [
  {
    title: '序号',
    colKey: 'serial-number',
    width: 70
  },
  { title: '操作人', colKey: 'inputUserName' },
  { title: '操作时间', colKey: 'inputTime' },
  {
    title: '操作内容',
    colKey: 'content',
    width: 270,
    cell: (h, { row }: { row: any }) => {
      return (
        <div>
          <p>操作：{operateTypeTxt(row.operateType)}</p>
          <p>菜单名称：{row.menuName}</p>
          <p>路由名称：{row.router}</p>
          <p>菜单层级：{menuLevelTxt(row.menuLevel)}</p>
        </div>
      )
    }
  }
]

const getData = () => {
  getOperations({
    page: pagination.value.current as number,
    limit: pagination.value.pageSize as number,
    condInputUserName: condInputUserName.value
  })
    .then(res => {
      tableData.value = res.data
      pagination.value.total = res.recordsFiltered as number
    })
    .finally(() => {
      loading.value = false
    })
}

const operateTypeTxt = (key: number) => {
  const operateTypeMap = ['新增', '编辑', '启用', '停用', '删除']
  return operateTypeMap[key - 1] || '-'
}

// 表格分页
const onPageChange = (val: PaginationProps) => {
  pagination.value.current = val.current as number
  pagination.value.pageSize = val.pageSize as number
  getData()
}

const open = () => {
  drawerVisible.value = true
  getData()
}
const close = () => {
  pagination.value.current = 1
  pagination.value.pageSize = 10
  drawerVisible.value = false
}

const handleSearch = () => {
  pagination.value.current = 1
  getData()
}

defineExpose({
  open,
  close
})
</script>
