<template>
  <div class="purchase-discount-page">
    <!-- 头部导航 -->
    <s-header :name="$t('discountCode.applDiscCode')" :noback="false" />

    <!-- 主要内容区域 -->
    <div class="purchase-container">
      <!-- 添加方式选择 -->
      <div class="form-section">
        <div class="section-header">
          <van-icon name="setting" class="section-icon" />
          <span>{{ $t("discountCode.addMode") }}</span>
        </div>

        <van-radio-group v-model="addMode" class="mode-selector">
          <van-radio name="1" icon-size="22px" class="mode-radio">
            <div class="mode-content">
              <div class="mode-icon">
                <van-icon name="setting" size="24" />
              </div>
              <div class="mode-text">
                <div class="mode-title">{{ $t("discountCode.randomAdd") }}</div>
              </div>
            </div>
          </van-radio>

          <div class="divider"></div>

          <van-radio name="2" icon-size="22px" class="mode-radio">
            <div class="mode-content">
              <div class="mode-icon">
                <van-icon name="setting-o" size="24" />
              </div>
              <div class="mode-text">
                <div class="mode-title">{{ $t("discountCode.oneceAdd") }}</div>
              </div>
            </div>
          </van-radio>
        </van-radio-group>
      </div>

      <!-- 优惠码详细信息表单 -->
      <van-form @submit="onSubmit" class="purchase-form">
        <!-- 随机生成数量 -->
        <div class="form-section" v-if="addMode === '1'">
          <div class="section-header">
            <van-icon name="records" class="section-icon" />
            <span>{{ $t("discountCode.numberOfDiscountCodesLabel") }}</span>
          </div>

          <van-field
            v-model="number"
            name="number"
            type="number"
            :placeholder="$t('discountCode.numberOfDiscountCodesPlaceholder')"
          >
            <template #extra>
              <div class="field-hint">
                {{ $t("discountCode.aSingleGenerationCannotExceed") }}
              </div>
            </template>
          </van-field>
        </div>

        <!-- 手动输入优惠码 -->
        <div class="form-section" v-if="addMode === '2'">
          <div class="section-header">
            <van-icon name="records" class="section-icon" />
            <span>{{ $t("discountCode.codeNum") }}</span>
          </div>

          <van-field
            v-model="codeNum"
            type="number"
            maxlength="6"
            :placeholder="$t('discountCode.codeNumPlaceholder')"
          />
        </div>

        <!-- 有效期设置 -->
        <div class="form-section">
          <div class="section-header">
            <van-icon name="clock" class="section-icon" />
            <span>{{ $t("discountCode.termOfValidity") }}</span>
          </div>

          <van-field
            v-model="month"
            name="month"
            type="number"
            :placeholder="$t('discountCode.pleaseEnterTheValidityPeriod')"
          >
            <template #extra>
              <div class="field-hint">
                {{ $t("discountCode.Months") }}
                <span class="highlight">{{
                  $t("discountCode.noMoreThanMonths")
                }}</span>
              </div>
            </template>
          </van-field>
        </div>

        <!-- 优惠类型选择 -->
        <div class="form-section">
          <div class="section-header">
            <van-icon name="discount" class="section-icon" />
            <span>{{ $t("discountCode.type") }}</span>
          </div>

          <div class="discount-type">
            <van-radio-group v-model="type" class="type-selector">
              <div class="type-option">
                <van-radio name="0" class="type-radio">
                  <div class="type-content">
                    <div class="type-icon">
                      <van-icon name="coupon" color="#4b6ad1" />
                    </div>
                    <div class="type-text">
                      <div class="type-title">
                        {{ $t("discountCode.discount2") }}
                      </div>
                    </div>
                  </div>
                </van-radio>
              </div>

              <div class="type-option">
                <van-radio name="1" class="type-radio">
                  <div class="type-content">
                    <div class="type-icon">
                      <van-icon name="coupon" color="#e59a6d" />
                    </div>
                    <div class="type-text">
                      <div class="type-title">
                        {{ $t("discountCode.deductionRoll") }}
                      </div>
                    </div>
                  </div>
                </van-radio>
              </div>
            </van-radio-group>
          </div>
        </div>

        <!-- 折扣/抵扣金额 -->
        <div class="form-section">
          <div class="section-header">
            <van-icon name="discount" class="section-icon" />
            <span>{{
              type === "0"
                ? $t("discountCode.discount") + " (0-10)"
                : $t("discountCode.deductionPriceLabdel")
            }}</span>
          </div>

          <van-field
            v-model="discount"
            type="number"
            name="discount"
            :placeholder="
              type === '0'
                ? $t('discountCode.enterNumber')
                : $t('discountCode.deductionPricePlaceholder')
            "
          >
            <template
              #extra
              v-if="user.ifForeign === '1' && discount !== '' && type === '0'"
            >
              <div class="discount-equivalent">
                {{ $t("discountCode.sameAs") }}
                <span class="highlight">{{ (10 - discount) * 10 }}% off</span>
              </div>
            </template>
          </van-field>
        </div>

        <!-- 支付方式选择 -->
        <div
          class="form-section"
          v-if="type === '0' && discount === '0' && promoCodeOpen !== '0'"
        >
          <div class="section-header">
            <van-icon name="card" class="section-icon" />
            <span>{{ $t("discountCode.paymentMethod") }}</span>
          </div>

          <div class="discount-type">
            <van-radio-group v-model="frpCode" class="type-selector">
              <div class="type-option">
                <van-radio name="WEIXIN_NATIVE" class="type-radio">
                  <div class="type-content">
                    <div class="type-icon">
                      <van-icon name="wechat" color="#07c160" />
                    </div>
                    <div class="type-text">
                      <div class="type-title">
                        {{ $t("discountCode.weChat") }}
                      </div>
                    </div>
                  </div>
                </van-radio>
              </div>

              <div class="type-option">
                <van-radio name="ALIPAY_NATIVE" class="type-radio">
                  <div class="type-content">
                    <div class="type-icon">
                      <van-icon name="alipay" color="#1775f9" />
                    </div>
                    <div class="type-text">
                      <div class="type-title">
                        {{ $t("discountCode.alipay") }}
                      </div>
                    </div>
                  </div>
                </van-radio>
              </div>
            </van-radio-group>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="submit-section">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            icon="success"
            size="large"
            class="submit-button"
          >
            {{ $t("discountCode.apply") }}
          </van-button>
        </div>
      </van-form>
    </div>

    <!-- 支付二维码弹窗 -->
    <van-popup
      v-model:show="payCodeType"
      round
      class="payment-popup"
    >
      <div class="payment-details">
        <div class="payment-item">
          <span class="payment-label">价格</span>
          <span class="payment-value">{{ ("￥" + ewmObj.price) || "" }}</span>
        </div>

        <div class="qrcode-container">
          <img :src="ewmObj.image" class="qrcode-image" alt="支付二维码" />
          <div class="payment-tips">支付二维码</div>
        </div>

        <div class="close-button">
          <van-button round plain type="default" @click="payCodeClose">
            关闭
          </van-button>
        </div>
      </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, showToast } 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({
      addMode: "1", // 生成方式
      codeNum: "", // 优惠码
      number: "", // 优惠码个数
      month: "", // 有效期
      type: "0", // 优惠卷类型
      discount: "", // 折扣
      frpCode: "WEIXIN_NATIVE", // 支付方式
    });
    const payCodeType = ref(false);
    const ewmObj = ref(null);
    const promoCodeOpen = ref(""); // 0折优惠码开通状态
    const user = getLoginUser();

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

    // 申请优惠码
    const onSubmit = async () => {
      if (payParams.addMode === "1") {
        payParams.codeNum = "";
        if (payParams.number === "") {
          showToast(t("discountCode.numberOfDiscountCodesPlaceholder"));
          return;
        }
      } else {
        payParams.number = "1";
        if (payParams.codeNum.length != 6) {
          showToast(t("discountCode.codeNumPlaceholder"));
          return;
        }
      }
      if (payParams.month === "") {
        showToast(t("discountCode.pleaseEnterTheValidityPeriod"));
        return;
      }
      if (payParams.type === "1" && payParams.discount === "") {
        showToast(t("discountCode.deductionPricePlaceholder"));
        return;
      }
      if (payParams.type === "0" && payParams.discount === "") {
        showToast(t("discountCode.pleaseEnterDiscount"));
        return;
      }
      if (parseInt(payParams.number) > 200) {
        showToast(t("discountCode.theNumberOfDiscountCodesCannotExceed"));
        return;
      }
      if (parseInt(payParams.month) > 3) {
        showToast(t("discountCode.theValidityPeriodCannotExceedMonths"));
        return;
      }
      if (payParams.type === "0" && parseInt(payParams.discount) > 10) {
        showToast(t("discountCode.discountCannotBeGreaterThan"));
        return;
      }
      if (payParams.type === "1" && payParams.discount == 0) {
        showToast(t("discountCode.deductionRollNoZero"));
        return;
      }
      console.log("payParams", payParams);
      const { data } = await addCode(Object.assign({}, payParams));
      if (
        payParams.type === "0" &&
        payParams.discount === "0" &&
        promoCodeOpen.value != "0"
      ) {
        console.log("data", data);
        ewmObj.value = data.data;
        payCodeType.value = true;
      } else {
        console.log("data", data);
        if (data.code === "00000") {
          showSuccessToast(
            t("discountCode.successfulProductionOfDiscountCode")
          );
          // router.push({ path: '/discountCode' });
          setTimeout(() => {
            router.go(-1);
          }, 1500);
        } else {
          if (data.code === "A0002") {
            showFailToast(t("discountCode.existsCode"));
          } else {
            showFailToast(data.message);
          }
        }
      }
    };
    const payCodeClose = () => {
      payCodeType.value = false;
    };
    // 有效天数
    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,
      user,
    };
  },
};
</script>

<style lang="less" scoped>
@primary-color: #4d6add;
@error-color: #ff4d4f;
.purchase-discount-page {
  background-color: #f5f7fa;
  min-height: 100vh;
}

.purchase-container {
  background: #f5f6fa;
  height: calc(100% - 50px);
  overflow: auto;
  overflow-x: hidden;
}

.form-section {
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 16px;
  margin: 12px;
}

.section-header {
  display: flex;
  align-items: center;
  padding-bottom: 12px;
  margin-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 16px;
  font-weight: 500;
  color: #333;

  .section-icon {
    margin-right: 10px;
    color: @primary-color;
    font-size: 18px;
  }
}

.mode-selector {
  width: 100%;
  display: flex;
  flex-direction: column;

  .mode-radio {
    margin-bottom: 12px;
    padding: 0;

    :deep(.van-radio__label) {
      width: 100%;
      margin-left: 30px;
    }
  }

  .mode-content {
    display: flex;
    align-items: center;
    width: 100%;
  }

  .mode-icon {
    flex: 0 0 40px;
    height: 40px;
    border-radius: 10px;
    background-color: #f0f5ff;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;

    .van-icon {
      color: @primary-color;
    }
  }

  .mode-title {
    font-size: 15px;
    font-weight: 500;
    color: #333;
    margin-bottom: 4px;
  }

  .mode-desc {
    font-size: 12px;
    color: #999;
    line-height: 1.4;
  }

  .divider {
    height: 1px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
}

.purchase-form {
  // margin: 12px;

  .van-cell {
    border-radius: 10px;
    background-color: #fafafa;
    margin-bottom: 12px;
  }

  .field-hint {
    font-size: 12px;
    color: #999;

    .highlight {
      color: @error-color;
      font-weight: 500;
    }
  }
}

.discount-type {
  padding: 0 5px;

  .type-option {
    background-color: #f9fafb;
    border-radius: 10px;
    overflow: hidden;
    margin-bottom: 12px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .type-radio {
    width: 100%;
    padding: 12px 15px;
  }

  .type-content {
    display: flex;
    align-items: center;
  }

  .type-icon {
    flex: 0 0 40px;
    height: 40px;
    border-radius: 10px;
    background-color: rgba(75, 106, 209, 0.1);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;

    .van-icon {
      font-size: 20px;
    }
  }

  .type-text {
    flex: 1;
    width: 200px;
  }

  .type-title {
    font-size: 15px;
    font-weight: 500;
    color: #333;
  }

  .type-desc {
    font-size: 12px;
    color: #888;
    margin-top: 4px;
  }
}

.discount-equivalent {
  font-size: 13px;
  color: #666;

  .highlight {
    color: @primary-color;
    font-weight: 500;
  }
}

.payment-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.payment-option {
  flex: 1 1 45%;

  :deep(.van-radio__label) {
    padding: 0;
    margin: 0;
  }

  .payment-content {
    background: #f9fafb;
    border-radius: 10px;
    padding: 15px;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .payment-icon {
    width: 40px;
    height: 40px;
    margin-bottom: 8px;
  }
}

.submit-section {
  margin: 20px 10px;

  .submit-button {
    height: 50px;
    font-size: 16px;
    font-weight: 500;
    box-shadow: 0 4px 12px rgba(75, 106, 209, 0.3);

    &:active {
      opacity: 0.9;
    }
  }
}

.payment-popup {
  width: 90%;
  max-width: 300px;
  padding: 20px;

  .payment-details {
    text-align: center;
  }

  .payment-item {
    margin-bottom: 12px;

    .payment-label {
      font-weight: 500;
      color: #666;
      margin-right: 8px;
    }

    .payment-value {
      font-weight: 600;
      color: @primary-color;
    }
  }

  .qrcode-container {
    margin: 20px auto;
    padding: 10px;
    border: 1px solid #f0f0f0;
    border-radius: 8px;
    max-width: 250px;
  }

  .qrcode-image {
    width: 100%;
    max-width: 200px;
    height: auto;
  }

  .payment-tips {
    font-size: 14px;
    color: #666;
    margin-top: 10px;
  }

  .close-button {
    margin-top: 20px;

    .van-button {
      padding: 0 25px;
    }
  }
}

@media (max-width: 480px) {
  .payment-option {
    flex: 1 1 100%;
  }
}
</style>
