<template>
  <el-dialog
    v-model="dialogVisible"
    title="新增盒子"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
    @open="handleOpen"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="goods-form"
    >
      <!-- 盒子类型选择 -->
      <el-form-item label="盒子类型" prop="type">
        <el-radio-group v-model="formData.type" @change="handleTypeChange">
          <el-radio-button
            v-for="item in availableGoodsTypes"
            :key="item.value"
            :label="item.value"
          >
            {{ item.flName || item.name }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>

      <!-- 基础信息 -->
      <el-divider content-position="left">基础信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="盒子名称" prop="title">
            <el-input v-model="formData.title" placeholder="请输入盒子名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="fieldConfig.showPrice">
          <el-form-item label="盒子价格" prop="price">
            <el-input-number
              v-model="formData.price"
              :min="0"
              :precision="2"
              :step="1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="排序值" prop="sort">
            <el-input-number
              v-model="formData.sort"
              :min="0"
              :max="9999"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="抽奖门槛" prop="choujiangXianzhi">
            <el-input-number
              v-model="formData.choujiangXianzhi"
              :min="0"
              style="width: 100%"
              placeholder="消费满此金额才能抽奖"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 盒子描述（盲盒/福利屋显示） -->
      <el-form-item v-if="fieldConfig.showDescription" label="盒子描述">
        <el-input
          v-model="formData.goodsDescribe"
          type="textarea"
          :rows="2"
          placeholder="请输入盒子描述"
        />
      </el-form-item>

      <!-- 开关配置 - 当有任何开关需要显示时才显示此区块 -->
      <template v-if="fieldConfig.showShouZhe || fieldConfig.showShowIs || fieldConfig.showCoupon || fieldConfig.showIntegral">
        <el-divider content-position="left">开关配置</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8" v-if="fieldConfig.showShouZhe">
            <el-form-item label="首抽五折">
              <el-switch v-model="formData.isShouZhe" :active-value="1" :inactive-value="0" />
              <div class="form-tip">开启后，新用户首次抽奖的第一抽享受5折优惠（仅限从未下过单的用户）</div>
            </el-form-item>
          </el-col>
          <!-- 是否最新 - 已隐藏，前端未展示相关icon
          <el-col :span="8">
            <el-form-item label="是否最新">
              <el-switch v-model="formData.newIs" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          -->
          <el-col :span="8" v-if="fieldConfig.showShowIs">
            <el-form-item label="首页显示">
              <el-switch v-model="formData.showIs" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="fieldConfig.showCoupon || fieldConfig.showIntegral">
          <el-col :span="8" v-if="fieldConfig.showCoupon">
            <el-form-item label="发券开关">
              <el-switch v-model="formData.couponIs" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="fieldConfig.showIntegral">
            <el-form-item label="发积分开关">
              <el-switch v-model="formData.integralIs" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- 套数/库存配置（一番赏/幸运赏/福袋/盲盒） -->
      <template v-if="fieldConfig.showStock">
        <el-divider content-position="left">库存配置</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="套数" prop="stock">
              <el-input-number v-model="formData.stock" :min="1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="fieldConfig.showDailyLimit">
            <el-form-item label="每日限购">
              <el-input-number
                v-model="formData.dailyLimit"
                :min="0"
                style="width: 100%"
                placeholder="0表示不限制"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- 限购次数（福利屋） -->
      <el-form-item v-if="fieldConfig.showQuanjuXiangou" label="限购次数">
        <el-input-number
          v-model="formData.quanjuXiangou"
          :min="0"
          style="width: 200px"
          placeholder="每个箱子的限购次数"
        />
      </el-form-item>

      <!-- 锁箱配置（一番赏/幸运赏） -->
      <template v-if="fieldConfig.showLock">
        <el-divider content-position="left">锁箱配置</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="锁箱开关">
              <el-switch v-model="formData.lockIs" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.lockIs === 1">
            <el-form-item label="锁箱时间(秒)">
              <el-input-number v-model="formData.lockTime" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- 怒气值配置（无限赏/翻倍赏）- 已隐藏，功能暂不使用 -->
      <!-- <template v-if="fieldConfig.showRage">
        <el-divider content-position="left">怒气值配置</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="怒气值开关">
              <el-switch v-model="formData.rageIs" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="formData.rageIs === 1">
            <el-form-item label="怒气值">
              <el-input-number v-model="formData.rage" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="fieldConfig.showItemCard">
            <el-form-item label="道具卡">
              <el-select v-model="formData.itemCardId" placeholder="请选择道具卡" clearable style="width: 100%">
                <el-option label="无" :value="0" />
                <el-option label="道具卡1" :value="1" />
                <el-option label="道具卡2" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </template> -->

      <!-- 领主赏配置 -->
      <template v-if="fieldConfig.showLingzhu">
        <el-divider content-position="left">领主赏配置</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="领主开关">
              <el-switch v-model="formData.lingzhuIs" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="formData.lingzhuIs === 1">
            <el-form-item label="领主返还">
              <el-input-number v-model="formData.lingzhuFan" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="formData.lingzhuIs === 1">
            <el-form-item label="领主奖品">
              <el-select v-model="formData.lingzhuShangId" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in shangList" :key="item.id" :label="item.title" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- 连击赏配置 -->
      <template v-if="fieldConfig.showLianji">
        <el-divider content-position="left">连击赏配置</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="连击次数">
              <el-input-number v-model="formData.lianJiNum" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="连击奖品">
              <el-select v-model="formData.lianJiShangId" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in shangList" :key="item.id" :label="item.title" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- 福利屋时间配置 -->
      <template v-if="fieldConfig.showTimeConfig">
        <el-divider content-position="left">时间配置</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="开始时间" prop="flwStartTime">
              <el-date-picker
                v-model="formData.flwStartTime"
                type="datetime"
                placeholder="选择开始时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="flwEndTime">
              <el-date-picker
                v-model="formData.flwEndTime"
                type="datetime"
                placeholder="选择结束时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开奖时间" prop="openTime">
              <el-date-picker
                v-model="formData.openTime"
                type="datetime"
                placeholder="选择开奖时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- 自动下架配置 -->
      <template v-if="fieldConfig.showAutoXiajia">
        <el-divider content-position="left">自动下架配置</el-divider>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="自动下架">
              <el-switch v-model="formData.isAutoXiajia" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <template v-if="formData.isAutoXiajia === 1">
            <el-col :span="6">
              <el-form-item label="下架利润值(%)">
                <el-input-number v-model="formData.xiajiaLirun" :min="0" :max="100" style="width: 100%; min-width: 120px" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="下架抽数阈值">
                <el-input-number v-model="formData.xiajiaAutoCoushu" :min="0" style="width: 100%; min-width: 120px" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="下架金额">
                <el-input-number v-model="formData.xiajiaJine" :min="0" style="width: 100%; min-width: 120px" />
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </template>

      <!-- 解锁金额配置 -->
      <template v-if="fieldConfig.showUnlockAmount">
        <el-divider content-position="left">解锁配置</el-divider>
        <el-form-item label="解锁金额">
          <el-input-number
            v-model="formData.unlockAmount"
            :min="0"
            :precision="2"
            style="width: 200px"
          />
          <span class="form-tip">用户需要消费满此金额才能看到此盒子，0表示都能看到</span>
        </el-form-item>
      </template>

      <!-- 图片上传 -->
      <el-divider v-if="fieldConfig.showCoverImage || fieldConfig.showDetailImage" content-position="left">图片上传</el-divider>
      <el-row :gutter="20" v-if="fieldConfig.showCoverImage || fieldConfig.showDetailImage || fieldConfig.showBannerImage">
        <el-col :span="12" v-if="fieldConfig.showCoverImage">
          <el-form-item label="盒子封面图" prop="imgUrl">
            <ImageUpload
              v-model="formData.imgUrl"
              placeholder="点击上传封面图"
              tip="支持 jpg、png、gif、webp 格式，最大 10MB"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="fieldConfig.showDetailImage">
          <el-form-item label="盒子详情图" prop="imgUrlDetail">
            <ImageUpload
              v-model="formData.imgUrlDetail"
              placeholder="点击上传详情图"
              tip="支持 jpg、png、gif、webp 格式，最大 10MB"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="fieldConfig.showBannerImage">
        <el-col :span="12">
          <el-form-item label="商品详情页Banner图" prop="imgUrlBanner">
            <ImageUpload
              v-model="formData.imgUrlBanner"
              placeholder="点击上传Banner图"
              tip="支持 jpg、png、gif、webp 格式，最大 10MB"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="submitting" @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 { createGoods, type GoodsTypeItem, type GoodsCreateRequest } from '@/api/business/goods'
import { getFieldConfig } from '../config/typeFieldConfig'
import ImageUpload from '@/components/ImageUpload/index.vue'

interface Props {
  modelValue: boolean
  goodsTypes: GoodsTypeItem[]
}

const props = defineProps<Props>()

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

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

// 过滤掉 value=0 的"全部"类型，只保留可创建的盒子类型
const availableGoodsTypes = computed(() => {
  return props.goodsTypes.filter(item => item.value > 0)
})

const formRef = ref<FormInstance>()
const submitting = ref(false)

// 奖品列表（用于领主赏/连击赏选择）
const shangList = ref<{ id: number; title: string }[]>([
  { id: 34, title: '奖品A' },
  { id: 35, title: '奖品B' },
  { id: 36, title: '奖品C' },
  { id: 37, title: '奖品D' },
  { id: 38, title: '奖品E' },
])

// 表单数据
const formData = reactive({
  type: 1,
  title: '',
  price: 0,
  sort: 0,
  choujiangXianzhi: 0,
  goodsDescribe: '',
  isShouZhe: 0,
  newIs: 0,
  showIs: 0,
  couponIs: 0,
  integralIs: 0,
  stock: 1,
  dailyLimit: 0,
  quanjuXiangou: 0,
  lockIs: 0,
  lockTime: 0,
  rageIs: 0,
  rage: 0,
  itemCardId: 0,
  lingzhuIs: 0,
  lingzhuFan: 0,
  lingzhuShangId: 0,
  lianJiNum: 0,
  lianJiShangId: 0,
  flwStartTime: '',
  flwEndTime: '',
  openTime: '',
  isAutoXiajia: 0,
  xiajiaLirun: 0,
  xiajiaAutoCoushu: 0,
  xiajiaJine: 0,
  unlockAmount: 0,
  imgUrl: '',
  imgUrlDetail: '',
  imgUrlBanner: '',
  categoryId: 0,
  couponPro: 0,
})

// 表单验证规则 - 动态计算
const formRules = computed<FormRules>(() => {
  const rules: FormRules = {
    type: [{ required: true, message: '请选择盒子类型', trigger: 'change' }],
    title: [{ required: true, message: '请输入盒子名称', trigger: 'blur' }],
    stock: [{ required: true, message: '请输入套数', trigger: 'blur' }],
  }
  
  // 根据配置动态添加价格验证规则
  if (fieldConfig.value.showPrice) {
    rules.price = [{ required: true, message: '请输入盒子价格', trigger: 'blur' }]
  }
  
  // 根据配置动态添加图片验证规则
  if (fieldConfig.value.showCoverImage) {
    rules.imgUrl = [{ required: true, message: '请上传盒子封面图', trigger: 'change' }]
  }
  if (fieldConfig.value.showDetailImage) {
    rules.imgUrlDetail = [{ required: true, message: '请上传盒子详情图', trigger: 'change' }]
  }
  if (fieldConfig.value.showBannerImage) {
    rules.imgUrlBanner = [{ required: true, message: '请上传商品详情页Banner图', trigger: 'change' }]
  }
  
  // 福利屋时间验证
  if (fieldConfig.value.showTimeConfig) {
    rules.flwStartTime = [{ required: true, message: '请选择开始时间', trigger: 'change' }]
    rules.flwEndTime = [{ required: true, message: '请选择结束时间', trigger: 'change' }]
    rules.openTime = [{ required: true, message: '请选择开奖时间', trigger: 'change' }]
  }
  
  return rules
})

// 根据类型获取字段配置
const fieldConfig = computed(() => {
  return getFieldConfig(formData.type)
})

// 类型变更时重置相关字段
const handleTypeChange = (type: number) => {
  const config = getFieldConfig(type)
  
  // 重置不显示的字段
  if (!config.showStock) {
    formData.stock = 0
  } else if (formData.stock === 0) {
    formData.stock = 1
  }
  if (!config.showLock) {
    formData.lockIs = 0
    formData.lockTime = 0
  }
  if (!config.showRage) {
    formData.rageIs = 0
    formData.rage = 0
  }
  if (!config.showLingzhu) {
    formData.lingzhuIs = 0
    formData.lingzhuFan = 0
    formData.lingzhuShangId = 0
  }
  if (!config.showLianji) {
    formData.lianJiNum = 0
    formData.lianJiShangId = 0
  }
  if (!config.showTimeConfig) {
    formData.flwStartTime = ''
    formData.flwEndTime = ''
    formData.openTime = ''
  }
  if (!config.showCoupon) {
    formData.couponIs = 0
  }
  if (!config.showIntegral) {
    formData.integralIs = 0
  }
}

// 重置表单
const resetForm = () => {
  // 使用过滤后的类型列表
  const types = availableGoodsTypes.value
  formData.type = types.length > 0 ? types[0].value : 1
  formData.title = ''
  formData.price = 0
  formData.sort = 0
  formData.choujiangXianzhi = 0
  formData.goodsDescribe = ''
  formData.isShouZhe = 0
  formData.newIs = 0
  formData.showIs = 0
  formData.couponIs = 0
  formData.integralIs = 0
  formData.stock = 1
  formData.dailyLimit = 0
  formData.quanjuXiangou = 0
  formData.lockIs = 0
  formData.lockTime = 0
  formData.rageIs = 0
  formData.rage = 0
  formData.itemCardId = 0
  formData.lingzhuIs = 0
  formData.lingzhuFan = 0
  formData.lingzhuShangId = 0
  formData.lianJiNum = 0
  formData.lianJiShangId = 0
  formData.flwStartTime = ''
  formData.flwEndTime = ''
  formData.openTime = ''
  formData.isAutoXiajia = 0
  formData.xiajiaLirun = 0
  formData.xiajiaAutoCoushu = 0
  formData.xiajiaJine = 0
  formData.unlockAmount = 0
  formData.imgUrl = ''
  formData.imgUrlDetail = ''
  formData.imgUrlBanner = ''
  formData.categoryId = 0
  formData.couponPro = 0
  formRef.value?.resetFields()
}

const handleOpen = () => {
  resetForm()
}

const handleClose = () => {
  emit('update:modelValue', false)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  // 福利屋时间验证
  if (fieldConfig.value.showTimeConfig) {
    const startTime = new Date(formData.flwStartTime).getTime()
    const endTime = new Date(formData.flwEndTime).getTime()
    const openTime = new Date(formData.openTime).getTime()
    
    if (startTime >= endTime) {
      ElMessage.error('开始时间必须早于结束时间')
      return
    }
    if (endTime >= openTime) {
      ElMessage.error('结束时间必须早于开奖时间')
      return
    }
  }

  submitting.value = true
  try {
    const requestData: GoodsCreateRequest = {
      title: formData.title,
      price: formData.price,
      type: formData.type,
      imgUrl: formData.imgUrl,
      imgUrlDetail: formData.imgUrlDetail,
      imgUrlBanner: formData.imgUrlBanner || null,
      stock: formData.stock,
      sort: formData.sort,
      dailyLimit: formData.dailyLimit,
      lockIs: formData.lockIs,
      lockTime: formData.lockTime,
      integralIs: formData.integralIs,
      showIs: formData.showIs,
      couponIs: formData.couponIs,
      couponPro: formData.couponPro,
      flwStartTime: formData.flwStartTime || null,
      flwEndTime: formData.flwEndTime || null,
      openTime: formData.openTime || null,
      choujiangXianzhi: formData.choujiangXianzhi,
      categoryId: formData.categoryId,
      goodsDescribe: formData.goodsDescribe || null,
      newIs: formData.newIs,
      isShouZhe: formData.isShouZhe,
      rageIs: formData.rageIs,
      rage: formData.rage,
      lingzhuIs: formData.lingzhuIs,
      lingzhuFan: formData.lingzhuFan,
      isAutoXiajia: formData.isAutoXiajia,
      xiajiaLirun: formData.xiajiaLirun,
      xiajiaAutoCoushu: formData.xiajiaAutoCoushu,
      xiajiaJine: formData.xiajiaJine,
    }

    await createGoods(requestData)
    ElMessage.success('创建成功')
    emit('success')
    dialogVisible.value = false
  } catch (error: any) {
    ElMessage.error(error.message || '创建失败')
  } finally {
    submitting.value = false
  }
}

// 监听盒子类型列表变化，设置默认类型
watch(() => availableGoodsTypes.value, (types) => {
  if (types.length > 0 && !formData.type) {
    formData.type = types[0].value
  }
}, { immediate: true })
</script>

<style scoped>
.goods-form {
  max-height: 65vh;
  overflow-y: auto;
  padding-right: 10px;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}

:deep(.el-divider__text) {
  font-weight: 500;
  color: #303133;
}

:deep(.el-radio-button__inner) {
  padding: 8px 15px;
}
</style>
