<template>
  <AFormPanel
    ref="formPanel"
    v-bind="formPanelProps">
    <template #default="formData">
      <div class="form-items">
        <ElFormItem label="角色代码">
          <ElInput
            v-model="formData.roleCode"
            placeholder="角色代码"/>
        </ElFormItem>
        <ElFormItem label="角色名称">
          <ElInput
            v-model="formData.roleName"
            placeholder="角色名称"/>
        </ElFormItem>
        <ElFormItem label="备注">
          <ElInput
            v-model="formData.memo"
            placeholder="备注"/>
        </ElFormItem>
      </div>
    </template>
  </AFormPanel>
</template>
<script lang="ts" setup>
import RoleApi from '@/pages/sys/role/role-api.ts'
import Strings from '@/common/utils/strings.ts'
import AFormPanel, {
  type AFormPanelInstance,
  buildFormPanelProps,
} from '@/components/a-form-panel/AFormPanel.tsx'

const props = withDefaults(defineProps<{
  research?: () => void
}>(), {
  research: () => {
  },
})
const status = ref<'add' | 'modify'>('add')
const formPanelIns = useTemplateRef<AFormPanelInstance>('formPanel')
const formPanelProps = buildFormPanelProps<RoleTypes.SearchRoleResult>({
  detailsLoader(id?: string) {
    if (Strings.isBlank(id)) {
      status.value = 'add'
      return Promise.resolve()
    } else {
      status.value = 'modify'
      return RoleApi.detail(id!)
        .then(res => {
          return {
            ...res.data,
          }
        })
    }
  },
  doSubmit(data) {
    if (status.value === 'add') {
      return RoleApi.add(data)
        .then(props.research)
    } else {
      return RoleApi.modify(data)
        .then(props.research)
    }
  },
})

watchEffect(() => {
  formPanelProps.title = status.value === 'add' ? '新建角色' : '修改角色'
})

defineExpose({
  open(data?: RoleTypes.SearchRoleResult) {
    formPanelIns.value?.open(data?.id)
  },
})
</script>
<style lang="stylus" scoped>
.sys_role-form {
  padding 20px
}
</style>
