<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="180px"
      v-loading="formLoading"
    >
      <el-form-item label="活动名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入活动名称" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择类型" clearable>
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.PROMOTION_LUCK_LOTTERY_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value.toString()" />
        </el-select>
      </el-form-item>
      <el-form-item label="抽奖消耗" prop="factor">
        <el-select v-model="formData.factor" placeholder="请选择抽奖消耗" clearable @change="handleSelectFactor">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.PROMOTION_LUCK_LOTTERY_FACTOR)" :key="dict.value" :label="dict.label" :value="dict.value.toString()" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="isShowSpu" label="商品" prop="factorInfo">
        <div v-if="formData.factorInfo && formData.factorInfo.length" style=" display: flex;width: 100%; flex-wrap: wrap;" class="mb-10px">
          <img v-for="val in formData.factorInfo" :key="val.id" :src="val.picUrl" alt="" class="h-70px w-70px mr-10px mb-5px" />
        </div>
        <el-button :icon="Plus" type="primary" @click.stop="showSpu = true">选择商品</el-button>
      </el-form-item>
      <el-form-item label="获取一次抽奖的条件数量" prop="factorNum">
        <el-input-number v-model="formData.factorNum" :min="1" />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker v-model="formData.startTime" type="date" value-format="x" placeholder="选择开始时间" />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker v-model="formData.endTime" type="date"  value-format="x" placeholder="选择结束时间" />
      </el-form-item>
      <!-- <el-form-item label="活动文案" prop="content">
        <Editor v-model="formData.content" height="150px" />
      </el-form-item> -->
      <!-- <el-form-item label="中奖记录展示" prop="isAllRecord">
        <el-switch v-model="formData.isAllRecord" />
      </el-form-item>
      <el-form-item label="个人中奖纪录展示" prop="isPersonalRecord">
        <el-switch v-model="formData.isPersonalRecord" />
      </el-form-item>
      <el-form-item label="活动规格是否展示" prop="isContent">
        <el-switch v-model="formData.isContent" />
      </el-form-item> -->
      <!-- <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入排序" />
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value.toString()" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <Dialog title="商品列表" v-model="showSpu" style="width: 70%;">
    <div style="display: inline-block; width: 100%;">
      <!-- <SpuList ref="spuRef" :multiple="true" :select="formData.factorInfo" /> -->
      <SpuList @select="handleSelectSpu" />
    </div>
    <template #footer>
      <el-button @click="handleSubmitSpu" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="showSpu = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
  import { Plus } from '@element-plus/icons-vue'
  import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
  import { LuckLotteryApi, LuckLotteryVO } from '@/api/mall/promotion/lottery/config'
  import SpuList from './components/spuList.vue'
              
  /** 幸运抽奖-活动 表单 */
  defineOptions({ name: 'LuckLotteryForm' })

  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗

  const spuRef = ref()
  const dialogVisible = ref(false) // 弹窗的是否展示
  const dialogTitle = ref('') // 弹窗的标题
  const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
  const formType = ref('') // 表单的类型：create - 新增；update - 修改
  const formData = ref({
    id: undefined,
    name: undefined,
    type: undefined,
    factor: undefined,
    factorNum: 1,
    startTime: undefined,
    endTime: undefined,
    lotteryNumTerm: 1,
    lotteryNum: 1,
    isAllRecord: true,
    isPersonalRecord: true,
    isContent: true,
    content: undefined,
    sort: undefined,
    status: undefined,
    factorInfo: []
  })
  const formRules = reactive({
    name: [{ required: true, message: '活动名称不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '类别不能为空', trigger: 'change' }],
    factor: [{ required: true, message: '抽奖消耗不能为空', trigger: 'blur' }],
    factorNum: [{ required: true, message: '获取一次抽奖的条件数量不能为空', trigger: 'blur' }],
    startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
    endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  })
  const formRef = ref() // 表单 Ref

  // 抽奖消耗选择
  const showSpu = ref(false)
  const isShowSpu = ref(false)
  const handleSelectFactor = (val: string) => {
    isShowSpu.value = val === '6' // 指定商品下单支付成功选项方展示商品选择
  }
              
  /** 打开弹窗 */
  const open = async (type: string, id?: number) => {
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)
    formType.value = type
    resetForm()
    // 修改时，设置数据
    if (id) {
      formLoading.value = true
      try {
        formData.value = await LuckLotteryApi.getLuckLottery(id)
        formData.value.factorInfo = formData.value.spuList
        isShowSpu.value = formData.value.factor === '6'
      } finally {
        formLoading.value = false
      }
    }
  }
  defineExpose({ open }) // 提供 open 方法，用于打开弹窗

  // 商品选中
  const handleSubmitSpu = () => {
    const spu = spuRef.value.spuListRef.getSelectionRows()
    if (!spu.length) return message.warning('请选择商品')
    formData.value.factorInfo = spu
    showSpu.value = false
  }

  const handleSelectSpu = (row: any) => {
    formData.value.factorInfo[0] = row
    showSpu.value = false
  }

  /** 提交表单 */
  const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
  const submitForm = async () => {
    // 校验表单
    await formRef.value.validate()
    formData.value.factorInfo = formData.value.factorInfo.map(e => e.id)
    // 提交请求
    formLoading.value = true
    try {
      const data = formData.value as unknown as LuckLotteryVO
      if (formType.value === 'create') {
        await LuckLotteryApi.createLuckLottery(data)
        message.success(t('common.createSuccess'))
      } else {
        await LuckLotteryApi.updateLuckLottery(data)
        message.success(t('common.updateSuccess'))
      }
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  }

  /** 重置表单 */
  const resetForm = () => {
    formData.value = {
      id: undefined,
      name: undefined,
      type: undefined,
      factor: undefined,
      factorNum: 1,
      startTime: undefined,
      endTime: undefined,
      lotteryNumTerm: 1,
      lotteryNum: 1,
      isAllRecord: true,
      isPersonalRecord: true,
      isContent: true,
      content: undefined,
      sort: undefined,
      status: undefined,
      factorInfo: []
    }
    formRef.value?.resetFields()
  }
</script>