<script lang="ts" setup>
import { h, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useMessage } from '@/hooks/web/useMessage'
import { BasicForm, useForm } from '@/components/Form'
import { BasicModal, useModalInner } from '@/components/Modal'
import { createTopic, updateTopic } from '@/api/product/topic'
import type { Topic } from '@/api/product/types'
import { useSystemEnumStore } from '@/store/modules/systemEnum'

defineOptions({ name: 'CustomTopicFormModal' })

const emit = defineEmits(['success', 'register'])

const isUpdate = ref(false)
const { getSystemEnums } = useSystemEnumStore()
const [registerForm, { setFieldsValue, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: [
    {
      field: 'id',
      show: false,
      component: 'Input',
    },
    {
      field: 'topic',
      label: 'Topic',
      required: true,
      // eslint-disable-next-line no-template-curly-in-string
      helpMessage: 'Topic必须包含/${deviceSn}/占位符',
      component: 'Input',
      rules: [
        // eslint-disable-next-line no-template-curly-in-string
        { pattern: /\/\$\{.+?\}\//, message: h('span', 'Topic必须包含/${deviceSn}/占位符') },
      ],
      dynamicDisabled: () => isUpdate.value,
    },
    {
      field: 'topicType',
      label: '操作权限',
      required: true,
      component: 'Select',
      componentProps: {
        options: getSystemEnums('eProductTopicType'),
      },
      dynamicDisabled: () => isUpdate.value,
    },
    {
      field: 'topicDesc',
      label: '描述',
      component: 'InputTextArea',
    },
  ],
  showActionButtonGroup: false,
  actionColOptions: { span: 23 },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data: Topic) => {
  isUpdate.value = true
  setFieldsValue({ ...data })
})

const route = useRoute()
async function handleSubmit() {
  try {
    const values = await validate<Topic>()
    setModalProps({ confirmLoading: true })
    values.productId = route.params.id as string
    await (isUpdate.value ? updateTopic(values) : createTopic(values))
    closeModal()
    emit('success')
    useMessage().createMessage.success('保存成功')
  }
  finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>

<template>
  <BasicModal
    v-bind="$attrs"
    width="30%"
    :min-height="100"
    :title="isUpdate ? '编辑' : '新增'"
    :after-close="() => isUpdate = false"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
