<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" v-loading="formLoading">
      <el-form-item prop="templateCode">
        <template #label>
          <span>
            {{ t('TemplateManagement.PrintTemplate.templateCode') }}
            <el-tooltip :content="t('TemplateManagement.PrintTemplate.templateCodeTooltip')" placement="top">
              <Icon icon="ep:question-filled" />
            </el-tooltip>
          </span>
        </template>
        <el-row :gutter="10" style="width: 100%;">
          <el-col :xs="24" :sm="18" :md="16" :lg="14" :xl="12">
            <el-input v-model="formData.templateCode" :placeholder="t('TemplateManagement.PrintTemplate.placeholderTemplateCode')" :disabled="formData.isAutoCode || formType === 'update'" />
          </el-col>
          <el-col :xs="24" :sm="6" :md="4" :lg="3" :xl="2">
            <el-switch v-model="formData.isAutoCode" :disabled="formType === 'update'" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item :label="t('TemplateManagement.PrintTemplate.templateName')" prop="templateName">
        <el-input v-model="formData.templateName" :placeholder="t('TemplateManagement.PrintTemplate.placeholderTemplateName')" />
      </el-form-item>
      <el-form-item :label="t('TemplateManagement.PrintTemplate.templateBizType')" prop="templateBizType">
        <el-radio-group v-model="formData.templateBizType">
          <el-radio value="1">{{ t('TemplateManagement.PrintTemplate.bizTypePrint') }}</el-radio>
          <el-radio value="2">{{ t('TemplateManagement.PrintTemplate.bizTypeReport') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('TemplateManagement.PrintTemplate.templateType')" prop="templateType">
        <el-select v-model="formData.templateType" :placeholder="t('TemplateManagement.PrintTemplate.placeholderTemplateType')" class="!w-full">
          <el-option v-for="dict in templateTypeDictOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('TemplateManagement.PrintTemplate.isEnable')" prop="isEnable">
        <el-switch v-model="formData.isEnable" />
      </el-form-item>
      <el-form-item :label="t('TemplateManagement.PrintTemplate.remark')" prop="remark">
        <el-input v-model="formData.remark" :placeholder="t('TemplateManagement.PrintTemplate.placeholderRemark')" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('common.ok') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { PrintTemplateApi, PrintTemplateVO } from '@/api/mes/printtemplate'
import { getIntDictOptions } from '@/utils/dict'

defineOptions({ name: 'PrintTemplateForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  id: undefined,
  templateCode: undefined,
  isAutoCode: true,
  templateName: undefined,
  templateType: undefined,
  templateBizType: '1',
  remark: undefined,
  isEnable: true,
})
const formRules = computed(() => ({
  templateCode: formData.value.isAutoCode ? [] : [{ required: true, message: t('TemplateManagement.PrintTemplate.validatorCodeRequired'), trigger: 'blur' }],
  templateName: [{ required: true, message: t('TemplateManagement.PrintTemplate.validatorNameRequired'), trigger: 'blur' }],
  templateType: [{ required: true, message: t('TemplateManagement.PrintTemplate.validatorTypeRequired'), trigger: 'change' }],
  templateBizType: [{ required: true, message: '请选择模板分类', trigger: 'change' }],
}))
const formRef = ref()

const templateTypeDictOptions = computed(() => {
  const dictType = formData.value.templateBizType === '2' ? 'report_template_type' : 'print_template_type'
  return getIntDictOptions(dictType)
})

watch(() => formData.value.templateBizType, () => {
  formData.value.templateType = undefined
})

const open = async (type: string, id?: number, bizType?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (bizType) {
    formData.value.templateBizType = bizType
  }
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PrintTemplateApi.getPrintTemplate(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = formData.value as unknown as PrintTemplateVO
    const { isAutoCode, ...submitData } = data as any
    if (isAutoCode) {
      delete submitData.templateCode
    }
    if (formType.value === 'create') {
      await PrintTemplateApi.createPrintTemplate(submitData)
      message.success(t('common.createSuccess'))
    } else {
      await PrintTemplateApi.updatePrintTemplate(submitData)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    templateCode: undefined,
    isAutoCode: true,
    templateName: undefined,
    templateType: undefined,
    templateBizType: '1',
    remark: undefined,
    isEnable: true,
  }
  formRef.value?.resetFields()
}
</script>
