<!-- 添加商品 -->
<template>
  <el-dialog :title="form.id ? '编辑商品' : '添加商品'" top="4vh" width="600px" v-model="visible" @closed="reset">
    <div class="content">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="left">
        <el-form-item label="商品类型">
          <el-radio-group v-model="form.goodsCategory">
            <el-radio label="优惠券" value="优惠券"></el-radio>
            <el-radio label="其它商品" value="其它商品"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="赠送优惠券" v-if="form.goodsCategory == '优惠券'" prop="couponId">
          <el-select v-model="form.couponId" placeholder="请选择优惠券" style="width: 200px;" @change="selectCoupon">
            <el-option v-for="item in couponList" :key="item.id" :label="item.title" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" :maxlength="30" clearable
            style="width: 200px;"></el-input>
        </el-form-item>
        <div v-if="form.goodsCategory == '其它商品'">
          <el-form-item label="商品图片" prop="goodsImageUrl">
            <SingleImageUpload v-model="form.goodsImageUrl" />
          </el-form-item>
        </div>
        <el-form-item label="所需积分" prop="requiredPoints">
          <el-input v-model="form.requiredPoints" :maxlength="8"
            @input="e => form.requiredPoints = filterNumberInput(e, 1)" style="width: 200px;">
            <template #append>积分</template>
          </el-input>
        </el-form-item>
        <el-form-item label="额外价格">
          <el-input v-model="form.extraPrice" :maxlength="8" @input="e => form.extraPrice = filterNumberInput(e)"
            style="width: 200px;">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="form.quantity" :maxlength="8" @input="e => form.quantity = filterNumberInput(e, 1)"
            style="width: 200px;">
          </el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="form.sort" :maxlength="8" @input="e => form.sort = filterNumberInput(e, 0)"
            style="width: 200px;">
          </el-input>
        </el-form-item>
        <el-form-item label="是否上架">
          <div class="center">
            <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
            <!-- <span class="tips">开启后，所有用户可通过消费获得积分及可用积分抵扣支付</span> -->
          </div>
        </el-form-item>
        <el-form-item label="发放方式">
          <div class="center">
            <span class="tips" v-if="form.goodsCategory == '优惠券'">系统发放</span>
            <span class="tips" v-if="form.goodsCategory == '其它商品'">需要用户到店内领取核销</span>
          </div>
        </el-form-item>
        <el-form-item label="每人限购" prop="limitQuota">
          <div class="center">
            <el-switch v-model="limitQuotaSwitch" @change="limitQuotaSwitchChange" />
            <el-input v-model="form.limitQuota" placeholder="请输入限购数量"
              @input="e => form.limitQuota = filterNumberInput(e, 1)" v-if="limitQuotaSwitch"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="商品详情" v-if="form.goodsCategory == '其它商品'">
          <MultiImageUpload v-model="goodsDescription" @up-data-event="multiImgSuccess" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitHandle" :loading="confirmLoading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { pointsGoodsPost } from '@/api/points'
import couponApi from "@/api/market/coupon";
import { filterNumberInput } from '@/utils'
// 单图上传
import SingleImageUpload from '@/components/Upload/SingleImageUpload.vue';
// 多图上传
import MultiImageUpload from '@/components/Upload/MultiImageUpload.vue';

const visible = ref(false)

const formRef = ref(null)

const limitQuotaSwitch = ref(false)
const confirmLoading = ref(false)
const goodsDescription = ref([])
const formObj = {
  id: '',
  goodsCategory: '优惠券',       // 商品类型 优惠券 其它商品
  couponId: '',                 // 优惠券id
  goodsName: '',                // 商品名称/优惠券名称
  goodsImageUrl: '',            // 商品图片URL
  requiredPoints: '',            // 所需积分
  extraPrice: '',               // 额外价格
  quantity: '',                 // 数量
  sort: 0,
  status: 1,                    // 是否上架 1-是 0-否
  receiveType: '',              // 领取方式 店内自取、系统发放
  limitQuota: '',               // 限购数量
  goodsDescription: '',         // 商品详情
}
const form = ref({ ...formObj })

function reset() {
  limitQuotaSwitch.value = false
  goodsDescription.value = []
  form.value = { ...formObj }
}

const rules = ref({
  couponId: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.couponId === '') {
          return callback(new Error('请选择优惠券'))
        } else {
          return callback()
        }
      },
      blur: ['change']
    }
  ],
  goodsName: [
    {
      required: true,
      message: '请输入商品名称',
      blur: ['change']
    }
  ],
  goodsImageUrl: [
    {
      required: true,
      message: '请选择商品图片',
      blur: ['change']
    }
  ],
  requiredPoints: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.requiredPoints === '') {
          return callback(new Error('请输入所需积分'))
        } else {
          return callback()
        }
      },
      blur: ['blur']
    }
  ],
  quantity: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.quantity === '') {
          return callback(new Error('请输入数量'))
        } else {
          return callback()
        }
      },
      blur: ['blur']
    }
  ],
  limitQuota: [
    {
      validator: (rule, value, callback) => {
        if (limitQuotaSwitch.value && form.value.limitQuota === '') {
          return callback(new Error('请输入限购数量'))
        } else {
          return callback()
        }
      },
      blur: ['blur', 'change']
    }
  ]
})

const couponList = ref([])

// 选择优惠券
function selectCoupon(e) {
  let obj = couponList.value.find(item => item.id == e)
  form.value.goodsName = obj.title
}

function limitQuotaSwitchChange() {
  form.value.limitQuota = ''
}

// 多图片上传成功
async function multiImgSuccess(response) {
  if (!response && goodsDescription.value.length > 0) {
    await nextTick()
    form.value.goodsDescription = JSON.stringify(goodsDescription.value)
    console.log('onSuccess.selectItem.value', form.value);
  }
}

const emits = defineEmits(['success'])
function submitHandle() {
  try {
    formRef.value.validate(async vaild => {
      if (vaild) {
        confirmLoading.value = true
        await pointsGoodsPost(form.value)
        ElNotification({
          title: '注意',
          message: '保存成功',
          type: 'success'
        })
        visible.value = false
        emits('success')
      }
    })
  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    confirmLoading.value = false
  }, 500);
}

function show(obj) {
  visible.value = true
  if (obj && obj.id) {
    form.value = { ...obj }
    if (obj.goodsDescription !== '') {
      goodsDescription.value = JSON.parse(obj.goodsDescription)
    }
    if (obj.limitQuota !== '' && obj.limitQuota !== null) {
      limitQuotaSwitch.value = true
    } else {
      limitQuotaSwitch.value = false
    }
  }
}

defineExpose({
  show
})

onMounted(() => {
  couponApi.getList({ size: 999 }).then((res) => {
    if (res) {
      couponList.value = res.records || [];
    }
  });
});
</script>

<style scoped lang="scss">
.center {
  display: flex;
  align-items: center;
  gap: 10px;

  .tips {
    color: #666;
    font-size: 14px;
  }
}
</style>