<!--
 * @Author: xiejiang
 * @Date: 2024-11-28 15:01:02
 * @LastEditors: xiejiang
 * @LastEditTime: 2024-12-10 17:52:05
 * @Description: 用户管理
 * Copyright（c）2024 by 好老师教育科技有限公司 All right Reserved.
-->
<template>
  <div class="h-full">
    <PageContainer
      :filter-conditions="filterConditions"
      :table-data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      @search-change="handleSearch"
      @clear="handleClear"
      @page-change="handlePage"
    >
      <template #header-left>
        <SearchWithButton
          :loading="loading"
          placeholder="用户姓名/手机号码"
          v-model="mobileOrName"
          @clear="handleClear"
          @on-search="handleSearch(searchParams)"
      /></template>
      <template #header-right>
        <div class="flex items-center justify-end gap-2" v-if="buttonPms('user-add-btn')">
          <t-button shape="round" theme="primary" @click="handelEdit(null)">
            <template #icon><AddIcon /></template>
            添加用户</t-button
          >
        </div>
      </template>

      <template #operation="{ row }">
        <template v-if="row.userType === 2">-</template>
        <template v-else
          ><operate-btn v-if="row.status != 2" content="启用" @click="handelStatus(row, 2)"> </operate-btn>
          <operate-btn v-if="row.status != 1" content="详情" @click="handelDetail(row)"> </operate-btn>
          <operate-btn v-if="buttonPms('user-edit-btn')" content="编辑" @click="handelEdit(row)"> </operate-btn>
          <operate-btn v-if="row.status == 2" content="停用" @click="handelStatus(row, 3)"> </operate-btn>
          <operate-btn v-if="row.status != 2" content="删除" @click="handelDel(row)"></operate-btn
        ></template>
      </template>
    </PageContainer>

    <!-- 新增编辑用户 -->
    <UserEdit ref="userEditRef" @success="handleSearch(searchParams)" />
  </div>
</template>

<script setup lang="tsx" name="users">
import { useRouter } from 'vue-router'
import { PrimaryTableCol, MessagePlugin } from 'tdesign-vue-next'
import type { filterItemProp } from 'src/components/PageFilters/interface/index'
import type { Pagination } from 'src/components/PageContainer/interface/index'
import { statusTxt } from '@/utils/status'
import { buttonPms } from '@/utils'
import { useBasic } from '@/hooks/useBasic'
import MessageBox from '@/utils/messageBox'
import UserEdit from './page/user-edit.vue'
import { ResUserList } from '@/api/interface/user-roles/index'
import { getUserList, getUserOperate } from '@/api/modules/user-roles/index'

const { setBreadcrumb } = useBasic()
const router = useRouter()

// 初始加载
onMounted(() => {
  setBreadcrumb([
    {
      title: '系统权限'
    },
    {
      title: '用户管理'
    }
  ])
  getData()
})

// 加载状态
const loading = ref(false)
// 分页配置
const pagination = ref({
  page: 1,
  limit: 10,
  total: 0
})

const mobileOrName = ref('')

// 筛选项配置，type类型参考pageFilters组件下的ts定义
const filterConditions = computed<filterItemProp[]>(() => [
  {
    label: '用户状态',
    prop: 'status',
    type: 'select',
    selectData: [
      { label: '编辑中', value: 1 },
      { label: '启用', value: 2 },
      { label: '停用', value: 3 }
    ]
  }
])

// 表格columns配置
const columns: PrimaryTableCol[] = [
  {
    title: '序号',
    colKey: 'serial-number',
    width: 70
  },
  { title: '用户姓名', colKey: 'userName' },
  { title: '手机号码', colKey: 'mobile' },
  {
    title: '用户角色',
    width: 220,
    colKey: 'roles',
    ellipsis: true,
    cell: (h, { row }) => {
      const roles = row.roles || []
      return (
        <t-tooltip
          content={roles.map((e: { name: string }) => e.name).join(';') || '-'}
          placement='top'
          theme='light'
          overlay-class-name='custom-tooltip'
        >
          <p class='ellipsis'>{roles.map((e: { name: string }) => e.name).join(';') || '-'}</p>
        </t-tooltip>
      )
    }
  },
  {
    title: '状态',
    colKey: 'status',
    cell: (h, { row }) => {
      return (
        <div class='flex items-center'>
          <div class={'dot ' + statusTxt(row.status)?.class}></div>
          <span class={statusTxt(row.status)?.class}>{statusTxt(row.status)?.title}</span>
        </div>
      )
    }
  },
  { title: '添加时间', colKey: 'inputTime' },
  {
    title: '添加人',
    colKey: 'inputUserName',
    cell: (h, { row }) => {
      return (
        <div class='flex items-center justify-between'>
          <div class={row.inputUserDelFlag ? 'w-[calc(100%-58px)] ellipsis text-[var(--td-font-gray-3)]' : ''}>
            <span class={row.inputUserDelFlag ? 'text-[var(--td-font-gray-3)]' : ''}>{row.inputUserName || '-'}</span>
          </div>
          {row.inputUserDelFlag ? <span class='inputUserName-del'>已删除</span> : ''}
        </div>
      )
    }
  },
  { title: '操作', colKey: 'operation', fixed: 'right', width: 220 }
]

// 表格数据，自行规范ts
const tableData = ref<ResUserList[]>([])

// 获取表格数据接口
const getData = () => {
  loading.value = true
  const postData = {
    ...pagination.value,
    mobileOrName: mobileOrName.value,
    ...searchParams.value
  }
  getUserList(postData)
    .then(res => {
      tableData.value = res.data
      pagination.value.total = res?.recordsFiltered as number
    })
    .finally(() => {
      loading.value = false
    })
}
const searchParams = ref<Record<string, any>>({}) // 搜索筛选
// 处理搜索条件
const handleSearch = (params: Record<string, any>) => {
  pagination.value.page = 1
  searchParams.value = params
  getData()
}

// 清空搜索条件
const handleClear = () => {
  mobileOrName.value = ''
  pagination.value.page = 1
  getData()
}

// 处理分页
const handlePage = (pageInfo: Pagination) => {
  pagination.value = { ...pagination.value, ...pageInfo }
  getData()
}

// 查看详情
const handelDetail = (row: ResUserList) => {
  router.push({
    name: 'users-detail',
    query: {
      userId: row.userId
    }
  })
}
// 编辑新增
const userEditRef = ref()
const handelEdit = (row: ResUserList | null) => {
  userEditRef.value?.open(row)
}

// 状态
const handelStatus = (row: ResUserList, status: number) => {
  const dialog = MessageBox(status, {
    onConfirm: () => {
      // 请求成功后，销毁弹框
      dialog.update({ confirmBtn: { content: '确定', loading: true } })
      getUserOperate({
        userId: row?.userId,
        operateType: status
      })
        .then(() => {
          getData()
          MessagePlugin.success('操作成功')
          dialog.hide()
        })
        .catch(() => {
          MessagePlugin.error('操作失败')
        })
        .finally(() => {
          dialog.update({ confirmBtn: { content: '确定', loading: false } })
        })
    }
  })
}

// 删除
const handelDel = (row: ResUserList) => {
  const dialog = MessageBox(3, {
    onConfirm: () => {
      // 请求成功后，销毁弹框
      dialog.update({ confirmBtn: { content: '确定', loading: true } })
      getUserOperate({
        userId: row?.userId,
        operateType: 1
      })
        .then(() => {
          getData()
          MessagePlugin.success('操作成功')
          dialog.hide()
        })
        .catch(() => {
          MessagePlugin.error('操作失败')
        })
        .finally(() => {
          dialog.update({ confirmBtn: { content: '确定', loading: false } })
        })
    }
  })
}
</script>
