<!--
 * @Author: xiejiang
 * @Date: 2024-11-28 15:01:02
 * @LastEditors: xiejiang
 * @LastEditTime: 2024-12-11 20:01:18
 * @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(true)"
      @on-search="onSearch"
      @page-change="handlePage"
    >
      <template #header-left>
        <SearchWithButton
          :loading="loading"
          placeholder="搜索角色名称"
          v-model="roleName"
          @clear="handleClear(null)"
          @on-search="handleSearch(searchParams)"
      /></template>
      <template #header-right>
        <div class="flex items-center justify-end gap-2" v-if="buttonPms('role-add-btn')">
          <t-button theme="primary" @click="handelEdit(null)">
            <template #icon><AddIcon /></template>
            添加角色</t-button
          >
        </div>
      </template>

      <template #operation="{ row }">
        <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="row.status == 2" content="权限配置" @click="handelPermissions(row)"> </operate-btn>
        <operate-btn content="编辑" v-if="buttonPms('role-edit-btn')" @click="handelEdit(row)"> </operate-btn>
        <operate-btn v-if="row.status == 2" content="停用" @click="handelStatus(row, 1)"> </operate-btn>
        <operate-btn v-if="row.status != 2" content="删除" @click="handelDel(row)"></operate-btn>
      </template>
    </PageContainer>

    <RoleEdit ref="roleEditRef" @success="handleSearch(searchParams)" />
  </div>
</template>

<script setup lang="tsx">
import { useRouter } from 'vue-router'
import { PrimaryTableCol, MessagePlugin } from 'tdesign-vue-next'
import type { filterItemProp } from '@/components/PageFilters/interface/index'
import type { Pagination } from '@/components/PageContainer/interface/index'
import { statusTxt } from '@/utils/status'
import { buttonPms } from '@/utils'
import { useBasic } from '@/hooks/useBasic'
import MessageBox from '@/utils/messageBox'
import RoleEdit from './page/role-edit.vue'
import { ResRoleList } from '@/api/interface/user-roles/index'
import { getRolePage, getRoleOperate } from '@/api/modules/user-roles/index'

defineOptions({
  name: 'role'
})

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

// 初始加载
onMounted(() => {
  setBreadcrumb([
    {
      title: '系统权限'
    },
    {
      title: '平台角色',
      name: 'role'
    }
  ])
})

onActivated(() => {
  getData()
})

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

const roleName = ref('')

// 筛选项配置，type类型参考pageFilters组件下的ts定义
const filterConditions = ref<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: 'roleName' },
  { title: '角色描述', colKey: 'description' },
  {
    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',
    width: 120,
    cell: (h, { row }) => {
      return (
        <div class='flex items-center justify-between'>
          <t-tooltip content={row.inputUserName}>
            <div class={row.inputUserDelFlag ? 'w-[calc(100%-58px)] ellipsis' : ''}>
              <span>{row.inputUserName || '-'}</span>
            </div>
          </t-tooltip>
          {row.inputUserDelFlag ? <span class='inputUserName-del'>已删除</span> : ''}
        </div>
      )
    }
  },
  { title: '操作', colKey: 'operation', fixed: 'right', width: 240 }
]

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

const searchParams = ref<Record<string, any>>({}) // 搜索筛选

// 处理搜索条件
const handleSearch = (params: Record<string, any>) => {
  pagination.value.page = 1
  searchParams.value = params
  getData()
}

// 搜索
const onSearch = (params: Record<string, any>) => {
  searchParams.value = params
}

// 清空搜索条件
const handleClear = (flge: boolean | null) => {
  if (flge) {
    searchParams.value = {}
  }
  roleName.value = ''
  pagination.value.page = 1
  getData()
}

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

// 获取表格数据接口
const getData = () => {
  loading.value = true
  const postData = {
    ...pagination.value,
    roleName: roleName.value,
    ...searchParams.value
  }
  getRolePage(postData)
    .then(res => {
      tableData.value = res.data
      pagination.value.total = res?.recordsFiltered as number
    })
    .finally(() => {
      loading.value = false
    })
}
// 查看详情
const handelDetail = (row: ResRoleList) => {
  router.push({
    name: 'role-detail',
    query: {
      roleId: row.roleId
    }
  })
}
// 编辑新增
const roleEditRef = ref()
const handelEdit = (row: ResRoleList | null) => {
  roleEditRef.value?.open(row)
}

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

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

// 权限
const handelPermissions = (row: ResRoleList) => {
  router.push({
    name: 'authority',
    query: {
      roleId: row.roleId
    }
  })
}
</script>
