<template>
  <el-dialog
    v-model="visible"
    :title="dialogType === 'add' ? $t('page.form.dialogTitleAdd') : $t('page.form.dialogTitleEdit')"
    width="600px"
    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('form.labelName')" prop="name">
        <el-input
          v-model="formData.name"
          :placeholder="$t('page.form.placeholderName')"
          :disabled="dialogType === 'edit'"
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.poolName')" prop="remark">
        <el-input
          v-model="formData.remark"
          :placeholder="$t('page.form.placeholderPoolName')"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      <el-form-item :label="$t('form.labelRemark')" prop="config_note">
        <el-input
          v-model="formData.config_note"
          type="textarea"
          :rows="3"
          :placeholder="$t('page.form.placeholderConfigNote')"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      <!-- dice_lottery_pool_config 已移除 type 字段，按 name 区分 default/killScore/up；name 在新增时填写，编辑时禁用 -->
      <el-form-item v-if="showSafetyLineField" :label="$t('page.form.safetyLine')" prop="safety_line">
        <el-input-number
          v-model="formData.safety_line"
          :min="0"
          :precision="2"
          style="width: 100%"
        />
        <div class="text-gray-500 text-xs mt-1">{{ $t('page.table.safetyLineTip') }}</div>
      </el-form-item>
      <el-form-item v-else-if="showSafetyLineReadonlyHint" :label="$t('page.form.safetyLine')">
        <el-alert
          type="info"
          :closable="false"
          show-icon
          :title="$t('page.form.safetyLineNotUsedReadonly')"
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.t1Weight')" prop="t1_weight">
        <el-slider v-model="formData.t1_weight" :min="0" :max="100" :step="0.01" show-input />
      </el-form-item>
      <el-form-item :label="$t('page.form.t2Weight')" prop="t2_weight">
        <el-slider v-model="formData.t2_weight" :min="0" :max="100" :step="0.01" show-input />
      </el-form-item>
      <el-form-item :label="$t('page.form.t3Weight')" prop="t3_weight">
        <el-slider v-model="formData.t3_weight" :min="0" :max="100" :step="0.01" show-input />
      </el-form-item>
      <el-form-item :label="$t('page.form.t4Weight')" prop="t4_weight">
        <el-slider v-model="formData.t4_weight" :min="0" :max="100" :step="0.01" show-input />
      </el-form-item>
      <el-form-item :label="$t('page.form.t5Weight')" prop="t5_weight">
        <el-slider v-model="formData.t5_weight" :min="0" :max="100" :step="0.01" show-input />
      </el-form-item>
      <el-form-item>
        <div class="text-gray-500 text-sm">
          {{ $t('page.form.weightsSumHint') }}<span :class="Math.abs(weightsSum - 100) > 0.01 ? 'text-red-500' : ''">{{
            weightsSum
          }}</span
          >{{ $t('page.form.weightsSumUnit') }}
        </div>
      </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/lottery_pool_config/index'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useI18n } from 'vue-i18n'
  import { useInjectedChannelDept, withChannelDeptParams } from '@/composables/useChannelDeptScope'

  const { t } = useI18n()

  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: 'add',
    data: undefined
  })

  const emit = defineEmits<Emits>()

  const formRef = ref<FormInstance>()

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

  /** 五个权重字段名，用于总和校验 */
  const WEIGHT_KEYS = ['t1_weight', 't2_weight', 't3_weight', 't4_weight', 't5_weight'] as const

  /** 五个池权重总和（用于展示与校验） */
  const weightsSum = computed(() => {
    return WEIGHT_KEYS.reduce((sum, key) => sum + Number(formData[key] ?? 0), 0)
  })

  function isDefaultPoolName(name: unknown): boolean {
    return String(name ?? '') === 'default'
  }

  const showSafetyLineField = computed(() => isDefaultPoolName(formData.name))

  const showSafetyLineReadonlyHint = computed(() => {
    const n = String(formData.name ?? '').trim()
    return n !== '' && !isDefaultPoolName(n)
  })

  /**
   * 表单验证规则
   */
  const rules = computed<FormRules>(() => {
    const base: FormRules = {
      name: [{ required: true, message: t('page.form.ruleNameRequired'), trigger: 'blur' }],
      t1_weight: [{ required: true, message: t('page.form.ruleT1Required'), trigger: 'blur' }],
      t2_weight: [{ required: true, message: t('page.form.ruleT2Required'), trigger: 'blur' }],
      t3_weight: [{ required: true, message: t('page.form.ruleT3Required'), trigger: 'blur' }],
      t4_weight: [{ required: true, message: t('page.form.ruleT4Required'), trigger: 'blur' }],
      t5_weight: [{ required: true, message: t('page.form.ruleT5Required'), trigger: 'blur' }]
    }
    if (showSafetyLineField.value) {
      base.safety_line = [
        { required: true, message: t('page.form.ruleSafetyLineRequired'), trigger: 'blur' }
      ]
    }
    return base
  })

  /**
   * 初始数据（权重为数字便于输入与校验）
   */
  const initialFormData = {
    id: null as number | null,
    dept_id: undefined as number | undefined,
    name: '',
    remark: '',
    config_note: '',
    safety_line: 0 as number,
    t1_weight: 0 as number,
    t2_weight: 0 as number,
    t3_weight: 0 as number,
    t4_weight: 0 as number,
    t5_weight: 0 as number
  }

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

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

  /**
   * 初始化页面数据
   */
  const initPage = async () => {
    // 先重置为初始值
    Object.assign(formData, initialFormData)
    // 如果有数据，则填充数据
    if (props.data) {
      await nextTick()
      initForm()
    }
  }

  /**
   * 初始化表单数据（数值字段转为 number 便于滑块/输入框回显与校验）
   */
  const initForm = () => {
    if (!props.data) return
    const numKeys = [
      'id',
      'dept_id',
      'safety_line',
      't1_weight',
      't2_weight',
      't3_weight',
      't4_weight',
      't5_weight'
    ]
    for (const key of Object.keys(formData)) {
      if (!(key in props.data)) continue
      const val = props.data[key]
      if (numKeys.includes(key)) {
        ;(formData as any)[key] =
          key === 'id' ? (val != null ? Number(val) || null : null) : Number(val) || 0
      } else {
        ;(formData as any)[key] = val ?? ''
      }
    }
  }

  /**
   * 关闭弹窗并重置表单
   */
  const handleClose = () => {
    visible.value = false
    formRef.value?.resetFields()
  }

  /**
   * 提交表单
   */
  const channelScope = useInjectedChannelDept()

  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      if (Math.abs(weightsSum.value - 100) > 0.01) {
        ElMessage.warning(t('page.form.msgWeightsMust100'))
        return
      }
      const submitData = withChannelDeptParams({
        ...formData,
        dept_id:
          formData.dept_id ??
          props.data?.dept_id ??
          channelScope?.selectedDeptId.value
      })
      const { safety_line, ...submitWithoutSafetyLine } = submitData
      const payload = isDefaultPoolName(submitData.name)
        ? submitData
        : submitWithoutSafetyLine
      if (props.dialogType === 'add') {
        await api.save(payload)
        ElMessage.success(t('page.form.msgAddSuccess'))
      } else {
        await api.update(payload)
        ElMessage.success(t('page.form.msgUpdateSuccess'))
      }
      emit('success')
      handleClose()
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }
</script>
