<script lang="ts" setup>
// @ts-nocheck
import {computed, ref} from 'vue'
import {useI18n} from 'vue-i18n'
import {z} from 'zod'
import {appCouponAddCouponPost} from '@/service'
import {Agreement} from '@/constant/enums'

const {t} = useI18n()

const couponTypes = computed(() => [
  {label: t('pages-user.coupons.discount'), value: 1},
  {label: t('pages-user.coupons.fullDiscount'), value: 2},
])

const formData = ref({
  nameZh: '',
  couponType: 1, // 1-折扣券, 2-满减券
  totalQuantity: '',
  discountValue: '', // 折扣值或减免金额
  minAmount: '', // 满减门槛
  validDays: '', // 有效天数
  distributionType: 1, // 1-直接领取, 2-兑换码
  issuerType: 2, // 1-平台发放, 2-商家发放
})

const isAgree = ref(false)
const submitting = ref(false)

const discountSchema = z.object({
  nameZh: z.string().min(1, t('pages-user.coupons.validation.nameRequired')),
  totalQuantity: z.string()
      .min(1, t('pages-user.coupons.validation.totalQuantityRequired'))
      .refine(
          (val) => /^\d+$/.test(val.trim()) && Number(val) > 0,
          {message: t('pages-user.coupons.validation.totalQuantityPositive') ?? '发放数量必须为大于0的整数'},
      ),
  validDays: z.string()
      .min(1, t('pages-user.coupons.validation.validDaysRequired'))
      .refine(
          (val) => /^\d+$/.test(val.trim()) && Number(val) > 0,
          {message: t('pages-user.coupons.validation.validDaysPositive') ?? '有效天数必须为大于0的整数'},
      ),
  discountValue: z.string()
      .min(1, t('pages-user.coupons.validation.discountValueRequired'))
      .refine((val) => {
        // 先检查是否为空
        if (!val || val.trim() === '') return false
        // 检查是否为纯数字（整数）
        if (!/^\d+$/.test(val.trim())) return false
        const num = Number(val)
        // 检查是否为整数且在1-100范围内
        return Number.isInteger(num) && num >= 1 && num <= 100
      }, {message: t('pages-user.coupons.validation.discountValueRange') ?? '请输入1-100之间的整数'})
})

const fullDiscountSchema = z.object({
  nameZh: z.string().min(1, t('pages-user.coupons.validation.nameRequired')),
  totalQuantity: z.string()
      .min(1, t('pages-user.coupons.validation.totalQuantityRequired'))
      .refine(
          (val) => /^\d+$/.test(val.trim()) && Number(val) > 0,
          {message: t('pages-user.coupons.validation.totalQuantityPositive') ?? '发放数量必须为大于0的整数'},
      ),
  validDays: z.string()
      .min(1, t('pages-user.coupons.validation.validDaysRequired') ?? '请输入有效期天数')
      .refine(
          (val) => /^\d+$/.test(val.trim()) && Number(val) > 0,
          {message: t('pages-user.coupons.validation.validDaysPositive') ?? '有效天数必须为大于0的整数'},
      ),
  minAmount: z.string()
      .min(1, t('pages-user.coupons.validation.minAmountRequired') ?? '请输入满减门槛')
      .refine((val) => Number(val) > 0, {message: t('pages-user.coupons.validation.minAmountRequired') ?? '请输入正确的满减门槛'}),
  discountValue: z.string()
      .min(1, t('pages-user.coupons.validation.discountValueRequired'))
      .refine((val) => Number(val) > 0, {message: t('pages-user.coupons.validation.discountValueRange') ?? '请输入正确的减免金额'})
})

const schema = computed(() => formData.value.couponType === 1 ? discountSchema : fullDiscountSchema)

function showToast(title: string) {
  uni.showToast({title, icon: 'none', duration: 2000})
}

function toggleType(type: number) {
  formData.value.couponType = type
  // 切换类型清空特定字段，避免串场
  formData.value.discountValue = ''
  formData.value.minAmount = ''
}

async function handleSubmit() {
  console.log(formData.value)
  if (submitting.value) return

  if (!isAgree.value) {
    showToast(t('pages-user.coupons.validation.agreeAgreementFirst'))
    return
  }

  try {
    schema.value.parse(formData.value)
  } catch (error) {
    if (error instanceof z.ZodError) {
      const firstError = error.errors[0]
      showToast(firstError.message)
      return
    }
  }

  submitting.value = true
  try {
    const payload = {
      ...formData.value,
      // 固定值：直接领取、商家发放
      distributionType: 1,
      issuerType: 2,
      isValid: 2,
      // 满减时默认门槛；折扣券无门槛则置 0
      minAmount: formData.value.couponType === 1 ? 0 : Number(formData.value.minAmount),
      // 折扣券：用户输入1-100，转换为 1 - (x/100)，例如90 -> 0.1
      // 满减券：直接使用输入的金额
      discountValue: formData.value.couponType === 1
          ? Number((1 - (Number(formData.value.discountValue) / 100)).toFixed(2))
          : Number(formData.value.discountValue),
      totalQuantity: Number(formData.value.totalQuantity),
      validDays: Number(formData.value.validDays),
    }
    const res = await appCouponAddCouponPost({body: payload as any})
    if (res?.code === 200) {
      showToast(t('pages-user.coupons.validation.createSuccess'))
      uni.navigateBack()
    } else {
      showToast(res?.msg || t('common.prompt.request-incorrect'))
    }
  } catch (error) {
    showToast(t('common.prompt.request-failed-please-try-again-later'))
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <view>
    <navbar :title="t('pages-user.coupons.addCoupon')"/>

    <view class="px-30rpx">
      <!-- 优惠券名称 -->
      <view class="mt-44rpx">
        <view class="field-label">{{ t('pages-user.coupons.name') }}:</view>
        <view class="field">
          <wd-input
              v-model="formData.nameZh"
              :focus-when-clear="false"
              :maxlength="20"
              :placeholder="t('common.placeholder.pleaseEnter')"
              clearable
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholderStyle="font-size: 30rpx;color: #999;"
          />
        </view>
      </view>

      <!-- 发放数量 -->
      <view class="mt-44rpx">
        <view class="field-label">{{ t('pages-user.coupons.totalQuantity') }}:</view>
        <view class="field">
          <wd-input
              v-model="formData.totalQuantity"
              :focus-when-clear="false"
              :placeholder="t('common.placeholder.pleaseEnter')"
              clearable
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholderStyle="font-size: 30rpx;color: #999;"
              type="number"
          />
        </view>
      </view>

      <!-- 类型切换 -->
      <view class="mt-44rpx flex-center-sb">
        <view class="field-label">{{ t('pages-user.coupons.type') }}:</view>
        <view class="flex items-center gap-40rpx">
          <view
              v-for="item in couponTypes"
              :key="item.value"
              class="flex items-center gap-16rpx"
              @click="toggleType(item.value)"
          >
            <view v-if="formData.couponType !== item.value" class="i-carbon:checkbox"></view>
            <view v-else class="i-carbon:checkbox-checked-filled"></view>
            <text class="text-30rpx lh-30rpx text-#333">{{ item.label }}</text>
          </view>
        </view>
      </view>

      <!-- 折扣券：折扣比例 -->
      <view v-if="formData.couponType === 1" class="mt-44rpx">
        <view class="field-label">{{ t('pages-user.coupons.discountRatio') }}:</view>
        <view class="field">
          <wd-input
              v-model="formData.discountValue"
              :focus-when-clear="false"
              :max="100"
              :min="1"
              :placeholder="t('common.placeholder.pleaseEnter')"
              clearable
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholderStyle="font-size: 30rpx;color: #999;"
              type="number"
          />
        </view>
      </view>

      <!-- 满减券：门槛与减免 -->
      <template v-else>
        <view class="mt-44rpx row-field">
          <view class="field-label !mb-0 shrink-0 mr-30rpx">{{ t('pages-user.coupons.spendOver') }}</view>
          <view class="field field-narrow">
            <wd-input
                v-model="formData.minAmount"
                :focus-when-clear="false"
                :placeholder="t('common.placeholder.pleaseEnter')"
                clearable
                custom-class="!text-30rpx !bg-transparent flex-1"
                no-border
                placeholderStyle="font-size: 30rpx;color: #999;"
                type="digit"
            />
          </view>
        </view>

        <view class="mt-32rpx row-field">
          <view class="field-label !mb-0 shrink-0">{{ t('pages-user.coupons.andReceiveDiscount') }}</view>
          <view class="field field-narrow">
            <wd-input
                v-model="formData.discountValue"
                :focus-when-clear="false"
                :placeholder="t('common.placeholder.pleaseEnter')"
                clearable
                custom-class="!text-30rpx !bg-transparent flex-1"
                no-border
                placeholderStyle="font-size: 30rpx;color: #999;"
                type="digit"
            />
          </view>
        </view>
      </template>

      <!-- 有效天数 -->
      <view class="mt-44rpx">
        <view class="field-label">{{ t('pages-user.coupons.validityDays') }}:</view>
        <view class="field flex-center-sb">
          <wd-input
              v-model="formData.validDays"
              :focus-when-clear="false"
              :placeholder="t('common.placeholder.pleaseEnter')"
              clearable
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholderStyle="font-size: 30rpx;color: #999;"
              type="number"
          />
          <text class="text-30rpx lh-30rpx text-#333 shrink-0 ml-12rpx">{{ t('pages-user.coupons.days') }}</text>
        </view>
      </view>

      <!-- 协议 -->
      <view class="px-10rpx flex items-center mt-80rpx" @click="isAgree = !isAgree">
        <image
            :src="isAgree ? '/static/images/chef/152.png' : '/static/images/chef/134.png'"
            class="w-28rpx h-28rpx shrink-0 mr-10rpx"
            mode="aspectFit"
        />
        <view class="text-28rpx lh-28rpx text-#333">
          {{ t('pages-user.coupons.agreeText') }}
          <text
              class="text-#00A76D"
              @click.stop="uni.navigateTo({url: '/pages/agreement/index?code=' + Agreement.CHEF_M_CODE_AGREEMENT})"
          >
            《{{ t('pages-user.coupons.couponAgreement') }}》
          </text>
        </view>
      </view>

      <view class="h-120rpx"/>
    </view>

    <fixed-bottom-large-btn
        :loading="submitting"
        :text="t('pages-user.coupons.publishNow')"
        class="z-100"
        fixed
        @click="handleSubmit"
    />
  </view>
</template>
<style>
page {
  background-color: #fff;
}
</style>
<style lang="scss" scoped>
.field-label {
  font-size: 36rpx;
  line-height: 36rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 20rpx;
}

.field {
  height: 98rpx;
  padding: 0 24rpx;
  border-radius: 16rpx;
  background: #F6F6F6;
  display: flex;
  align-items: center;
}

.row-field {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20rpx;
}

.field-narrow {
  width: 480rpx;
}
</style>