<template>
  <el-dialog :visible.sync="visible" v-bind="modalOptions">
    <el-form ref="formData" :model="formData" :rules="formRules" size="mini" label-suffix=":" label-width="150px">
      <el-form-item label="奖品名称" prop="prizeName">
        <el-input v-model="formData.prizeName" placeholder="请输入奖品名称" maxlength="30" show-word-limit />
      </el-form-item>
      <el-form-item label="关联活动" prop="lotteryId">
        <el-select v-model="formData.lotteryId" size="mini" placeholder="请选择关联平台组合活动" filterable>
          <el-option
            v-for="(item, index) in activityList" :key="item.id" :label="`${item.topic}（${item.id}）`"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="奖品类型" prop="prizeType">
        <el-select
          v-model="formData.prizeType" size="mini" placeholder="请选择奖品类型"
          @change="(e) => formData.prizeNum = ''"
        >
          <el-option label="谢谢参与" :value="-1" />
          <el-option label="普通奖品" :value="1" />
          <el-option label="唯一性奖品" :value="2" />
          <el-option label="代金券" :value="3" />
          <el-option label="消费金" :value="4" />
          <el-option label="现金余额" :value="5" />
          <el-option label="优惠券" :value="6" />
        </el-select>
      </el-form-item>
      <div>
        <el-form-item
          v-if="formData.prizeType === 6" :label="`${'num字段'}\n${'（优惠券活动ID）'}`" prop="prizeNum"
          style="white-space: pre-wrap;"
        >
          <el-select v-model="formData.prizeNum" size="mini" placeholder="请选择优惠券活动" filterable>
            <el-option
              v-for="(item, index) in couponDataList" :key="item.activityId" :label="`${item.activityName}（${item.activityId}）`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-else prop="prizeNum" label="num字段">
          <el-input v-model="formData.prizeNum" placeholder="请输入num字段（数量/商品ID）" style="width: 250px;"></el-input>
        </el-form-item>
      </div>
      <el-form-item prop="totalStock" label="总库存">
        <el-input v-model="formData.totalStock" placeholder="请输入总库存" style="width: 250px;"></el-input>
      </el-form-item>
      <el-form-item prop="validStock" label="可用库存">
        <el-input v-model="formData.validStock" placeholder="请输入可用库存" style="width: 250px;"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark" type="textarea" placeholder="请输入备注" maxlength="520"
          :rows="3"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="mini" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="mini" @click="handleSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { saveLotteryPrize, updateLotteryPrize, getByIdLotteryPrize } from '@/api/lotteryManagement/LotteryPrizes'
import { getPageLotteryActivities } from '@/api/lotteryManagement/lotteryActivities'
import { getCouponData } from '@/api/active/active_coupon.js'

export default {
  name: 'EditModal',
  components: {
  },
  data() {
    return {
      modalOptions: {
        closeOnClickModal: false,
        width: '820px',
        title: ''
      },
      visible: false,
      formData: {
        id: '',
        lotteryId: '',
        prizeName: '',
        prizeType: '',
        prizeNum: '',
        totalStock: '',
        validStock: '',
        remark: ''
      },
      formRules: {
        prizeName: [
          { required: true, message: '请输入抽奖奖品名称' }
        ],
        lotteryId: [
          { required: true, message: '请选择关联活动' }
        ],
        prizeType: [
          { required: true, message: '请选择奖品类型' }
        ],
        totalStock: [
          { required: false, message: '请输入总库存' },
          { pattern: /^(0|[1-9][0-9]*)$/, message: '请输入正整数' }
        ],
        validStock: [
          { required: false, message: '请输入可用库存' },
          { pattern: /^(0|[1-9][0-9]*)$/, message: '请输入正整数' }
        ]
      },
      activityList: [],
      couponDataList: []
    }
  },
  methods: {
    handleClose() {
      this.visible = false
    },
    async initList() {
      const res1 = await getPageLotteryActivities({ page: 1, pageSize: 9999 })
      this.activityList = res1.data.list
      const res2 = await getCouponData({ activityName: '', state: 3, page: 1, pageSize: 9999 })
      this.couponDataList = res2.data.list
    },
    handleOpen(params = {}) {
      this.modalOptions.title = params.id ? '编辑抽奖奖品' : '添加抽奖奖品'
      this.formData = Object.assign(this.$options.data().formData, params)
      this.visible = true
      this.initList()
      if (params.id) {
        this.getInfo(params.id)
      } else {
        this.$refs.formData && this.$refs.formData.resetFields()
      }
    },
    async getInfo(id) {
      const loading = this.$loading({ text: '加载中' })
      try {
        const res = await getByIdLotteryPrize({ id })
        this.formData = Object.assign(this.$options.data().formData, res.data, {
          id: res.data.id || '',
          lotteryId: res.data.lotteryId || '',
          prizeName: res.data.prizeName || '',
          prizeType: res.data.prizeType,
          prizeNum: res.data.prizeNum,
          totalStock: res.data.totalStock,
          validStock: res.data.validStock,
          remark: res.data.remark || ''
        })
        this.$nextTick(() => {
          this.$refs.formData && this.$refs.formData.validate()
        })
      } finally {
        loading.close()
      }
    },
    handleSubmit() {
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          const loading = this.$loading({ text: '加载中' })
          try {
            const { ...otps } = this.formData
            const params = {
              ...otps
            }
            this.formData.id ? await updateLotteryPrize(params) : await saveLotteryPrize(params)
            loading.close()
            this.$message({ message: `${this.formData.id ? '编辑' : '添加'}成功!`, type: 'success' })
            this.$emit('success')
            this.visible = false
          } catch (e) {
            loading.close()
          } finally {
            loading.close()
          }
        } else {
          this.$message({ message: '请输入相关信息', type: 'warning' })
          return false
        }
      })
    }
  }
}
</script>
