<template>
  <!-- 购买优惠码 -->
  <div class="discountCodePage flex-col">
    <s-header :name="$t('discountCode.applDiscCode')" :noback="false"></s-header>
    <div class="discountCodeBox flex-col">
      <van-form @submit="onSubmit">
        <van-field v-model="number" name="number" :label="$t('discountCode.numberOfDiscountCodesLabel')"
          :placeholder="$t('discountCode.numberOfDiscountCodesPlaceholder')">
          <template #button>
            <span>{{ $t('discountCode.aSingleGenerationCannotExceed') }}</span>
          </template>
        </van-field>
        <van-field v-model="month" name="number" :label="$t('discountCode.termOfValidity')"
          :placeholder="$t('discountCode.pleaseEnterTheValidityPeriod')">
          <template #button>
            <span>{{ $t('discountCode.Months') }}<span>{{ $t('discountCode.noMoreThanMonths') }}</span></span>
          </template>
        </van-field>
        <van-field readonly v-model="validDays" :label="$t('discountCode.validDays')" placeholder="" />
        <div class="van-cell van-field">
          <div class="van-cell__title van-field__label"><span>{{ $t('discountCode.type') }}</span></div>
          <div class="van-cell__value van-field__value radioBox">
            <van-radio-group v-model="type" direction="horizontal">
              <van-radio name="1" icon-size="18px">{{ $t('discountCode.deductionRoll') }}</van-radio>
              <van-radio name="0" icon-size="18px">{{ $t('discountCode.discount2') }}</van-radio>
            </van-radio-group>
          </div>
        </div>
        <van-field v-if='type === "1"' v-model="discount" name="number" :label="$t('discountCode.deductionPriceLabdel')"
          :placeholder="$t('discountCode.deductionPricePlaceholder')">
        </van-field>
        <van-field v-if='type === "0"' v-model="discount" name="number" :label="$t('discountCode.discount')"
          :placeholder="$t('discountCode.enterNumber')">
          <template #button>
            <span>0-10</span>
          </template>
        </van-field>
        <div class="van-cell van-field" v-if='type === "0" && discount === "0" && promoCodeOpen != "0"'>
          <div class="van-cell__title van-field__label"><span>{{ $t('discountCode.paymentMethod') }}</span></div>
          <div class="van-cell__value van-field__value radioBox">
            <van-radio-group v-model="frpCode" direction="horizontal">
              <van-radio name="WEIXIN_NATIVE" icon-size="18px">{{ $t('discountCode.weChat') }}</van-radio>
              <van-radio name="ALIPAY_NATIVE" icon-size="18px">{{ $t('discountCode.alipay') }}</van-radio>
            </van-radio-group>
          </div>
        </div>
        <van-row justify="space-around" style="padding: 1em;">
          <van-button span="5" round type="primary" style="height: 2em; padding: 0 2em;" native-type="submit">{{
            $t('discountCode.apply') }}</van-button>
        </van-row>
      </van-form>
    </div>
    <van-popup v-model:show="payCodeType" round class="payCodePopup" @close="payCodeClose">
      <div style="text-align: center; font-size: 14px; padding: 1em; line-height: 1.8;">
        <div>price: {{ ewmObj.price || '' }}</div>
        <div>sn: {{ ewmObj.sn || '' }}</div>
        <img :src="ewmObj.image" />
      </div>
    </van-popup>
  </div>
</template>

<script>
import sHeader from "@/components/SimpleHeader";
import { onMounted, reactive, toRefs, ref, watch } from "vue";
import { getLoginUser, Format_calcuDecial, styleUrl } from "@/common/js/utils";
import { showFailToast, showSuccessToast } from "vant";
import { addCode } from "@/service/discountCode";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

export default {
  name: "payCode",
  components: { sHeader },
  setup() {
    // 引入语言
    const { t } = useI18n();
    const router = useRouter();
    let payParams = reactive({
      number: '', // 优惠码个数
      month: '', // 有效期
      type: '1', // 优惠卷类型
      discount: '', // 折扣
      frpCode: 'WEIXIN_NATIVE', // 支付方式
    });
    const payCodeType = ref(false);
    const ewmObj = ref(null);
    const promoCodeOpen = ref(''); // 0折优惠码开通状态


    // 初始化页面
    onMounted(async () => {
      //加载样式
      styleUrl('discountCode');
      payCodeType.value = false;
      payParams.number = '';
      payParams.month = '';
      payParams.type = '1';
      payParams.discount = '';
      payParams.frpCode = 'WEIXIN_NATIVE';
      const user = getLoginUser();
      if (user) {
        payParams.adminId = user.id;
        promoCodeOpen.value = user.promoCodeOpen;
        // console.log("promoCodeOpen",promoCodeOpen.value);
      }
    });

    // 提交搜索表单触发搜索
    const onSubmit = async () => {
      if (payParams.number === '') { showFailToast(t('discountCode.numberOfDiscountCodesPlaceholder')); return; }
      if (payParams.month === '') { showFailToast(t('discountCode.pleaseEnterTheValidityPeriod')); return; }
      if (payParams.type === '1' && payParams.discount === '') { showFailToast(t('discountCode.deductionPricePlaceholder')); return; }
      if (payParams.type === '0' && payParams.discount === '') { showFailToast(t('discountCode.pleaseEnterDiscount')); return; }
      if (parseInt(payParams.number) > 200) { showFailToast(t('discountCode.theNumberOfDiscountCodesCannotExceed')); return; }
      if (parseInt(payParams.month) > 3) { showFailToast(t('discountCode.theValidityPeriodCannotExceedMonths')); return; }
      if (payParams.type === '0' && parseInt(payParams.discount) > 10) { showFailToast(t('discountCode.discountCannotBeGreaterThan')); return; }
      const { data } = await addCode(Object.assign({}, payParams));
      if (payParams.type === '0' && payParams.discount === '0' && promoCodeOpen.value != '0') {
        ewmObj.value = data.data;
        payCodeType.value = true;
      } else {
        if (data.code === '00000') {
          showSuccessToast(t('discountCode.successfulProductionOfDiscountCode'));
          setTimeout(() => {
            router.go(-1);
          }, 1500);
        } else {
          showFailToast(data.message);
        }
      }
    }
    const payCodeClose = () => { router.go(-1); }
    // 有效天数
    const validDays = ref('0'+ t('discountCode.days'));
    // 监听有效期，计算有效天数
    watch(() => payParams.month, (newVal) => {
      validDays.value = Format_calcuDecial(newVal, 30) + t('discountCode.days');
    }, { immediate: true, deep: true });
    return {
      ...toRefs(payParams),
      payCodeType,
      ewmObj,
      onSubmit,
      payCodeClose,
      validDays,
      promoCodeOpen
    };
  },
};
</script>

<style lang="less" scoped>
@import "../../common/style/common.less";
</style>
