<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button @click="showModalFn" class="ml-3"><PlusOutlined />新增权限组</a-button>
      </template>
    </BasicTable>
    <BasicModal @register="registerModal" :title="modalTitle" @ok="modalConfirm">
      <BasicForm @register="registerForm" ref="formElRef" />
    </BasicModal>
  </div>
</template>
<script lang="ts">
  import { computed, defineComponent, nextTick, ref, toRaw } from 'vue'
  import { BasicTable, useTable } from '/@/components/Table'
  import { getTableColumns, getPermSchemas } from './tableData'
  import { PlusOutlined } from '@ant-design/icons-vue'
  import { addPermGroup, getPermGroupList, updatePermGroup } from '/@/api/sys/manager'
  import { BasicForm, FormActionType, useForm } from '/@/components/Form'
  import { BasicModal, useModal } from '/@/components/Modal'
  import { PermGroupItem } from '/@/api/sys/model/managerModel'

  export default defineComponent({
    name: 'PermList',
    components: {
      BasicTable,
      PlusOutlined,
      BasicModal,
      BasicForm
    },
    setup() {
      const formElRef = ref<Nullable<FormActionType>>(null)
      const modalType = ref<'create' | 'update'>('create')
      const [registerModal, { openModal }] = useModal()
      const [registerForm] = useForm({
        schemas: getPermSchemas(),
        showActionButtonGroup: false
      })

      function reloadTableData() {
        return reload()
      }

      async function setFormInstanceValue(item: PermGroupItem) {
        modalType.value = 'update'
        openModal()
        await nextTick()
        formElRef.value?.setFieldsValue({ ...item })
      }
      const [registerTable, { reload }] = useTable({
        api: getPermGroupList,
        columns: getTableColumns(reloadTableData, (item: PermGroupItem) => setFormInstanceValue(item)),
        showTableSetting: true,
        canResize: true,
        bordered: true
      })

      async function showModalFn() {
        modalType.value = 'create'
        openModal(true)
        await nextTick()
        formElRef.value?.resetFields()
      }

      async function onSubmit(values) {
        try {
          if (modalType.value === 'create') {
            await addPermGroup(toRaw(values))
          } else {
            await updatePermGroup(toRaw(values))
          }
        } catch (error) {
          return false
        }
        return true
      }
      function modalConfirm() {
        formElRef.value?.validate().then(async values => {
          const result = await onSubmit(values)
          if (result) {
            await reload()
            openModal(false)
          }
        })
      }

      const modalTitle = computed(() => (modalType.value === 'create' ? '新增权限组' : '编辑权限组'))
      return { formElRef, registerModal, registerForm, registerTable, showModalFn, modalConfirm, modalTitle }
    }
  })
</script>
