<template>
  <BodyPanlHeader>
    <a-button type="primary" @click="setRole()">新增角色</a-button>
    <div>
      <a-input-search
        v-model:value="params.roleName"
        style="width: 280px"
        placeholder="请输入角色名称"
        allow-clear
        @search="updateList"
      />
    </div>
  </BodyPanlHeader>

  <BodyPanlBody>
    <a-table
      :data-source="list"
      :columns="roleColumns"
      :pagination="pagination"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <div v-if="!record.defaultRole" class="table-actions">
            <a @click="setRole(record)">编辑</a>
            <a class="warn" @click="delRoleHandler(record)">删除</a>
          </div>
        </template>
      </template>
    </a-table>
  </BodyPanlBody>
</template>

<script lang="ts" setup>
import EditRole from './edit.vue'
import { computed, reactive } from 'vue'
import { BodyPanlHeader, BodyPanlBody } from '@/layout/panl'
import { usePaging } from '@/hook'
import { router } from '@/router'
import { renderModal } from '@/helper'
import { roleColumns as baseColumns } from './columns'
import { Modal } from 'ant-design-vue'
import { fetchRoles, addRole, updateRole, deleteRole } from '@/api'

import type { Role } from '@/api'

const roleColumns = [
  ...baseColumns,
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action'
  }
]

const params = reactive({
  roleName: '',
  projectId: computed(() => Number(router.currentRoute.value.params.id))
})

const { list, pagination, updateList } = usePaging(fetchRoles, params)

const setRole = (role?: Role) => {
  renderModal(EditRole, {
    role,
    async onSave(role) {
      if (role.roleId) {
        await updateRole(role as Role)
      } else {
        await addRole(params.projectId, role)
      }
      await updateList()
    }
  })
}

const delRoleHandler = (role: Role) => {
  Modal.confirm({
    content: '确定要删除此角色',
    title: '系统提示',
    width: '400px',
    okText: '删除',
    icon: null,
    cancelText: '取消',
    onOk: async () => {
      try {
        await deleteRole(role.roleId)
        await updateList()
      } catch {}
    }
  })
}
</script>
