<template>
  <FormPage
    ref="formPage"
    :action-column="actionColumn"
    :left-tools="leftTools"
    :paging="paging">
    <template #searchFormItem="{ searchForm }">
      <ElFormItem label="角色代码">
        <ElInput
          v-model="searchForm.roleCode"
          placeholder="角色代码"/>
      </ElFormItem>
      <ElFormItem label="角色名称">
        <ElInput
          v-model="searchForm.roleName"
          placeholder="角色名称"/>
      </ElFormItem>
      <ElFormItem label="备注">
        <ElInput
          v-model="searchForm.memo"
          placeholder="备注"/>
      </ElFormItem>
    </template>
    <template #columns>
      <ElTableColumn label="角色代码" prop="roleCode"/>
      <ElTableColumn label="角色名称" prop="roleName"/>
      <ElTableColumn label="备注" prop="memo"/>
    </template>
    <RoleForm ref="roleForm" @edit-succ="research"/>
    <BindRes ref="bindRes"/>
  </FormPage>
</template>
<script lang="ts" setup>
import RoleApi from '@/pages/sys/role/role-api.ts'
import RoleForm from '@/pages/sys/role/RoleForm.vue'
import { ElMessage } from 'element-plus'
import BindRes from '@/pages/sys/role/BindRes.vue'
import FormPage from '@/components/page/FormPage.vue'
import type {
  ActionColumnType,
  ToolType,
} from '@/components/page/a-page-type.ts'
import type { ComponentExposed } from 'vue-component-type-helpers'

const roleFormIns = useTemplateRef<InstanceType<typeof RoleForm>>('roleForm')
const bindResIns = useTemplateRef<InstanceType<typeof BindRes>>('bindRes')
const formPageIns = useTemplateRef<ComponentExposed<typeof FormPage>>('formPage')

const actionColumn = reactive<ActionColumnType<RoleTypes.SearchRoleResult>>({
  tableActions: [
    {
      tooltip: '资源',
      icon: 'ScaleToOriginal',
      action({row}: { row: RoleTypes.SearchRoleResult }) {
        bindResIns.value?.open(row.id!)
      },
    },
    {
      tooltip: '编辑',
      icon: 'Edit',
      show({row}) {
        return row.id != '1'
      },
      action({row}: { row: RoleTypes.SearchRoleResult }) {
        if (row.id == '1') {
          ElMessage.error('不能操作管理员')
          return
        }
        roleFormIns.value?.open(row)
      },
    },
    {
      icon: 'Delete',
      loading: false,
      type: 'danger',
      tooltip: '删除',
      confirm: {
        title: '是否删除当前数据',
      },
      action({row}: { row: RoleTypes.SearchRoleResult }) {
        if (row.id == '1') {
          ElMessage.error('不能操作管理员')
          return Promise.resolve(false)
        }
        return RoleApi.del([ row.id! ])
          .then(() => {
            ElMessage.success('删除成功')
            return true
          })
      },
    },
  ],
})
const leftTools: ToolType[] = [
  {
    icon: 'Plus',
    label: '新建',
    action() {
      roleFormIns.value?.open()
    },
  },
]

function research() {
  formPageIns.value?.doSearch()
}

function paging(params: RoleTypes.SearchRoleParam) {
  return RoleApi.paging(params)
}
</script>
