<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑盒子类型' : '新增盒子类型'"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="类型名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入类型名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型Key" prop="value">
            <el-input-number
              v-model="formData.value"
              :min="1"
              :max="999"
              :disabled="isEdit"
              placeholder="请输入类型Key"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="排序" prop="sortOrder">
            <el-input-number
              v-model="formData.sortOrder"
              :min="0"
              :max="9999"
              placeholder="请输入排序"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类名称" prop="flName">
            <el-input v-model="formData.flName" placeholder="请输入分类名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="首页显示" prop="isShow">
            <el-switch
              v-model="formData.isShow"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="支付方式" prop="payMethods">
        <el-checkbox-group v-model="payMethods">
          <el-checkbox label="wechat">微信支付</el-checkbox>
          <el-checkbox label="balance">余额支付</el-checkbox>
          <el-checkbox label="currency">积分支付</el-checkbox>
          <el-checkbox label="currency2">积分2支付</el-checkbox>
          <el-checkbox label="coupon">优惠券支付</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="支付类型" prop="isDeduction">
        <el-radio-group v-model="formData.isDeduction">
          <el-radio :value="0">支付模式</el-radio>
          <el-radio :value="1">抵扣模式</el-radio>
        </el-radio-group>
        <div class="form-tip">
          <el-text type="info" size="small">
            支付模式：用户选择一种支付方式完成支付；抵扣模式：积分/优惠券可抵扣部分金额
          </el-text>
        </div>
      </el-form-item>

      <el-form-item label="角标文字" prop="cornerText">
        <el-input
          v-model="formData.cornerText"
          placeholder="请输入角标文字（如：热门、新品）"
          maxlength="10"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  createGoodsType,
  updateGoodsType,
  type GoodsTypeItem,
  type GoodsTypeCreateRequest
} from '@/api/business/goods'

const props = defineProps<{
  modelValue: boolean
  typeData: GoodsTypeItem | null
  isEdit: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 表单引用
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 支付方式多选
const payMethods = ref<string[]>([])

// 表单数据
const formData = reactive<GoodsTypeCreateRequest>({
  name: '',
  value: 1,
  sortOrder: 0,
  isShow: 1,
  isFenlei: 1,
  flName: '',
  cornerText: '',
  payWechat: 0,
  payBalance: 0,
  payCurrency: 0,
  payCurrency2: 0,
  payCoupon: 0,
  isDeduction: 0,
  remark: ''
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入类型名称', trigger: 'blur' },
    { min: 1, max: 20, message: '类型名称长度在1-20个字符', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入类型Key', trigger: 'blur' }
  ],
  flName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ]
}

// 监听支付方式变化，同步到表单数据
watch(payMethods, (methods) => {
  formData.payWechat = methods.includes('wechat') ? 1 : 0
  formData.payBalance = methods.includes('balance') ? 1 : 0
  formData.payCurrency = methods.includes('currency') ? 1 : 0
  formData.payCurrency2 = methods.includes('currency2') ? 1 : 0
  formData.payCoupon = methods.includes('coupon') ? 1 : 0
})

// 监听弹窗打开，初始化数据
watch(() => props.modelValue, (visible) => {
  if (visible) {
    if (props.isEdit && props.typeData) {
      // 编辑模式：回显数据
      Object.assign(formData, {
        name: props.typeData.name,
        value: props.typeData.value,
        sortOrder: props.typeData.sortOrder,
        isShow: props.typeData.isShow,
        isFenlei: props.typeData.isFenlei,
        flName: props.typeData.flName,
        cornerText: props.typeData.cornerText || '',
        payWechat: props.typeData.payWechat,
        payBalance: props.typeData.payBalance,
        payCurrency: props.typeData.payCurrency,
        payCurrency2: props.typeData.payCurrency2,
        payCoupon: props.typeData.payCoupon,
        isDeduction: props.typeData.isDeduction,
        remark: props.typeData.remark || ''
      })
      // 初始化支付方式多选
      const methods: string[] = []
      if (props.typeData.payWechat === 1) methods.push('wechat')
      if (props.typeData.payBalance === 1) methods.push('balance')
      if (props.typeData.payCurrency === 1) methods.push('currency')
      if (props.typeData.payCurrency2 === 1) methods.push('currency2')
      if (props.typeData.payCoupon === 1) methods.push('coupon')
      payMethods.value = methods
    } else {
      // 新增模式：重置数据
      resetForm()
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    value: 1,
    sortOrder: 0,
    isShow: 1,
    isFenlei: 1,
    flName: '',
    cornerText: '',
    payWechat: 0,
    payBalance: 0,
    payCurrency: 0,
    payCurrency2: 0,
    payCoupon: 0,
    isDeduction: 0,
    remark: ''
  })
  payMethods.value = []
  formRef.value?.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
  } catch {
    return
  }

  submitLoading.value = true
  try {
    const submitData: GoodsTypeCreateRequest = {
      ...formData,
      cornerText: formData.cornerText || undefined,
      remark: formData.remark || undefined
    }

    if (props.isEdit && props.typeData) {
      await updateGoodsType(props.typeData.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await createGoodsType(submitData)
      ElMessage.success('创建成功')
    }

    emit('success')
    handleClose()
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped>
.form-tip {
  margin-top: 4px;
}
</style>
