<template>
  <el-dialog
    v-model="visible"
    :title="$t('page.form.titleEdit')"
    width="600px"
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" label-width="120px">
      <el-form-item :label="$t('page.form.labelTestCount')" prop="test_count">
        <el-input v-model="formData.test_count" :placeholder="$t('page.form.placeholderTestCount')" disabled />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelWeightSnapshot')" prop="weight_config_snapshot">
        <el-input v-model="formData.weight_config_snapshot" :placeholder="$t('page.form.placeholderWeightSnapshot')" disabled />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelResultCounts')" prop="result_counts">
        <el-input v-model="formData.result_counts" :placeholder="$t('page.form.placeholderResultCounts')" disabled />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">{{ $t('form.close') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import type { FormInstance } from 'element-plus'

  interface Props {
    modelValue: boolean
    dialogType: string
    data?: Record<string, any>
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    dialogType: 'edit',
    data: undefined
  })

  const emit = defineEmits<Emits>()

  const formRef = ref<FormInstance>()

  /**
   * 弹窗显示状态双向绑定
   */
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  /**
   * 初始数据
   */
  const initialFormData = {
    id: null,
    test_count: 100,
    weight_config_snapshot: '',
    result_counts: ''
  }

  /**
   * 表单数据
   */
  const formData = reactive({ ...initialFormData })

  /**
   * 监听弹窗打开，初始化表单数据（仅查看）
   */
  watch(
    () => props.modelValue,
    (newVal) => {
      if (newVal) {
        initPage()
      }
    }
  )

  /**
   * 初始化页面数据
   */
  const initPage = async () => {
    Object.assign(formData, initialFormData)
    if (props.data) {
      await nextTick()
      initForm()
    }
  }

  /**
   * 回填表单数据
   */
  const initForm = () => {
    if (props.data) {
      for (const key in formData) {
        if (props.data[key] != null && props.data[key] != undefined) {
          ;(formData as any)[key] = props.data[key]
        }
      }
    }
  }

  /**
   * 关闭弹窗
   */
  const handleClose = () => {
    visible.value = false
    formRef.value?.resetFields()
  }
</script>
