<template>
  <BodyPanlHeader>
    <a-button type="primary" @click="setRole()">{{ $t('role.add') }}</a-button>
    <div>
      <a-input-search
        v-model:value="params.roleName"
        style="width: 280px"
        :placeholder="$t('role.roleNameRule')"
        allow-clear
        @search="updateList"
      />
    </div>
  </BodyPanlHeader>

  <BodyPanlBody>
    <a-table
      :scroll="{ x: '100%', y: 350 }"
      :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)">{{ $t('sys.edit') }}</a>
            <a class="warn" @click="delRoleHandler(record)">{{
              $t('sys.del')
            }}</a>
          </div>
        </template>
      </template>
    </a-table>
  </BodyPanlBody>
</template>

<script lang="ts" setup>
import EditRole from './edit.vue'
import { computed, onDeactivated, reactive, watch } 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'
import { ui18n } from '@/lang'

const roleColumns = [
  ...baseColumns,
  {
    title: ui18n.t('sys.oper'),
    dataIndex: 'action',
    key: 'action'
  }
]

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

onDeactivated(() => {
  params.roleName = ''
})
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()
    }
  })
}

watch(
  () => params.roleName,
  () => (pagination.current = 1),
  { flush: 'sync' }
)
const delRoleHandler = (role: Role) => {
  Modal.confirm({
    content: ui18n.t('role.delMsg'),
    title: ui18n.t('sys.tipTitle'),
    width: '400px',
    okText: ui18n.t('sys.del'),
    icon: null,
    cancelText: ui18n.t('sys.cancel'),
    onOk: async () => {
      try {
        await deleteRole(role.roleId, params.projectId)
        await updateList()
      } catch {}
    }
  })
}
</script>
