<template>
  <el-dialog
    v-model="visible"
    :title="dialogType === 'add' ? $t('page.form.titleAdd') : $t('page.form.titleEdit')"
    width="560px"
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item :label="$t('page.form.labelName')" prop="name">
        <el-input v-model="formData.name" disabled :placeholder="$t('page.form.placeholderNameAuto')" />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelTitle')" prop="title">
        <el-input v-model="formData.title" disabled :placeholder="$t('page.form.placeholderTitleAuto')" />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelMult')" prop="mult">
        <el-input-number
          v-model="formData.mult"
          :min="1"
          :step="1"
          style="width: 100%"
          @update:model-value="syncNameTitleFromMult"
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelIsDefault')" prop="is_default">
        <el-radio-group v-model="formData.is_default">
          <el-radio :value="1">{{ $t('page.table.defaultYes') }}</el-radio>
          <el-radio :value="0">{{ $t('page.table.defaultNo') }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="handleSubmit">{{ $t('table.form.submit') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import api from '../../../api/ante_config/index'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useI18n } from 'vue-i18n'
  import { withChannelDeptParams } from '@/composables/useChannelDeptScope'

  const { t } = useI18n()

  interface Props {
    modelValue: boolean
    dialogType: string
    data?: Record<string, unknown>
  }
  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }
  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    dialogType: 'add',
    data: undefined
  })
  const emit = defineEmits<Emits>()
  const formRef = ref<FormInstance>()

  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  const rules = computed<FormRules>(() => ({
    name: [{ required: true, message: t('page.form.ruleNameRequired'), trigger: 'blur' }],
    title: [{ required: true, message: t('page.form.ruleTitleRequired'), trigger: 'blur' }],
    mult: [{ required: true, message: t('page.form.ruleMultRequired'), trigger: 'blur' }],
    is_default: [{ required: true, message: t('page.form.ruleDefaultRequired'), trigger: 'change' }]
  }))

  interface AnteFormData {
    id: number | null
    name: string
    title: string
    mult: number
    is_default: number
  }

  const initialFormData: AnteFormData = {
    id: null,
    name: '',
    title: '',
    mult: 1,
    is_default: 0
  }

  const formData = reactive({ ...initialFormData })

  function syncNameTitleFromMult() {
    const mult = Number(formData.mult) || 1
    const label = `x${mult}`
    formData.name = label
    formData.title = label
  }

  watch(
    () => props.modelValue,
    async (newVal) => {
      if (!newVal) return
      Object.assign(formData, initialFormData)
      if (!props.data) return
      await nextTick()
      if (typeof props.data.id === 'number') formData.id = props.data.id
      if (typeof props.data.name === 'string') formData.name = props.data.name
      if (typeof props.data.title === 'string') formData.title = props.data.title
      formData.mult = Number(props.data.mult ?? 1) || 1
      formData.is_default = Number(props.data.is_default ?? 0) === 1 ? 1 : 0
      syncNameTitleFromMult()
    }
  )

  function handleClose() {
    visible.value = false
    formRef.value?.resetFields()
  }

  async function handleSubmit() {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      if (props.dialogType === 'add') {
        await api.save(withChannelDeptParams(formData))
        ElMessage.success(t('page.form.addSuccess'))
      } else {
        await api.update(withChannelDeptParams(formData))
        ElMessage.success(t('page.form.editSuccess'))
      }
      emit('success')
      handleClose()
    } catch (error) {
      console.log(error)
    }
  }
</script>
