<script lang="ts" setup>
import { ref, unref } from 'vue'
import { updateWarnForm } from './warn.data'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { BasicForm, useForm } from '@/components/Form'
import { BasicModal, useModalInner } from '@/components/Modal'
import { getWarn, updateWarn } from '@/api/alert/warn/index'

defineOptions({ name: 'WarnUpdateModal' })

const emit = defineEmits(['success', 'register'])
const { t } = useI18n()
const { createMessage } = useMessage()
const isUpdate = ref(true)

const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  labelWidth: 120,
  baseColProps: { span: 24 },
  schemas: updateWarnForm,
  showActionButtonGroup: false,
  actionColOptions: { span: 23 },

})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields()
  setModalProps({ useWrapper: true, minHeight: 180, confirmLoading: false })
  // 如果是修改modal，则赋值给表单
  isUpdate.value = !!data?.isUpdate
  if (unref(isUpdate)) {
    const res = await getWarn(data.record.id)
    setFieldsValue({ ...res })
  }
  // // 获取下拉框的数据
  // const versionData = await getModelVersionList({ modelId: data?.record.modelId })
  // const versionList = [] as any
  // // // 组名下拉框问题
  // versionData.forEach((item) => {
  //   versionList.push({ label: item.version, value: item.id })
  // })
  // const calcGroupData = await getCalcGroupList({ unitId: data?.record.unitId })
  // const calcGroupList = [] as any
  // // // 组名下拉框问题
  // calcGroupData.forEach((item) => {
  //   calcGroupList.push({ label: item.groupName, value: item.id })
  // })

  // // 将数据放入下拉框中
  // updateSchema({
  //   field: 'modelVersionId',
  //   componentProps: {
  //     options: versionList,
  //   },
  // })
  // updateSchema({
  //   field: 'calcGroup',
  //   componentProps: {
  //     options: calcGroupList,
  //   },
  // })
})

async function handleSubmit() {
  try {
    const values = await validate()
    setModalProps({ confirmLoading: true })
    if (unref(isUpdate))
      await updateWarn(values)

    closeModal()
    emit('success')
    createMessage.success(t('common.saveSuccessText'))
  }
  finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>

<template>
  <BasicModal v-bind="$attrs" :title="isUpdate ? t('action.edit') : t('action.create')" @register="registerModal" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
