<script lang="ts" setup>
import {z} from 'zod'
import dayjs from 'dayjs'
import {appCouponAddCouponPost, appCouponCouponCostPost, appUserCardSelectDefaultPost} from "@/service";
import {Agreement, EventEnum} from "@/constant/enums";

const {t} = useI18n()

const formData = ref({
  nameZh: '',
  couponType: 1,// 1-折扣券, 2-满减券
  minAmount: 0, // 最低消费额度
  discountValue: '', // 优惠值
  issuerType: 2, // 1-平台发放, 2-商家发放
  distributionType: 2, // 1-直接领取, 2-兑换码
  validStart: '', // 生效时间
  validEnd: '', // 失效时间
  totalQuantity: '', // 总数量
})

// Zod 校验 schema
const formSchema = z.object({
  nameZh: z.string().min(1, t('pages-user.coupons.validation.nameRequired')),
  // couponType: z.number().min(1, '请选择优惠券类型'),
  // minAmount: z.string().min(1, '最低消费额度不能为空'),
  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之间的整数'}),
  validStart: z.union([z.string().min(1, t('pages-user.coupons.validation.validStartRequired')), z.number().min(1, t('pages-user.coupons.validation.validStartRequired'))]),
  validEnd: z.union([z.string().min(1, t('pages-user.coupons.validation.validEndRequired')), z.number().min(1, t('pages-user.coupons.validation.validEndRequired'))]),
  totalQuantity: z.string().min(1, t('pages-user.coupons.validation.totalQuantityRequired')),
})

const isAgree = ref(false)
const dateType = ref('') // 'start' 表示生效日期, 'end' 表示失效日期

function changeCouponType(type: number) {
  formData.value.couponType = type
}

function openHours(type: string) {
  console.log(type)
  dateType.value = type
  show.value = true
}

function navigateTo(url: string) {
  uni.navigateTo({url})
}

const show = ref(false)

function handleClose() {
  show.value = false
}

const timeValue = ref(Date.now())
const maxDate = dayjs().valueOf();

function handleSubmit() {
  console.log(timeValue.value);

  // 根据类型设置对应的日期字段
  if (dateType.value === 'start') {
    formData.value.validStart = timeValue.value
  } else if (dateType.value === 'end') {
    formData.value.validEnd = timeValue.value
  }

  // 关闭弹窗
  show.value = false
}

// 提交表单数据
function submitForm() {
  try {
    // 检查是否同意协议
    if (!isAgree.value) {
      uni.showToast({
        title: t('pages-user.coupons.validation.agreeAgreementFirst'),
        icon: 'none',
        duration: 2000
      })
      return
    }
    // 使用 zod 校验表单数据
    formSchema.parse(formData.value)
    // 校验日期时间：生效日期不得晚于失效日期
    if (formData.value.validStart && formData.value.validEnd) {
      const startTime = dayjs(formData.value.validStart)
      const endTime = dayjs(formData.value.validEnd)

      if (startTime.isAfter(endTime)) {
        uni.showToast({
          title: t('pages-user.coupons.validation.startDateCannotLaterThanEndDate'),
          icon: 'none',
          duration: 2000
        })
        return
      }
    }
    // 如果是余额支付,弹出支付密码弹窗
    if (payMethodOptions.value.payMethod === 2) {
      passwordInputRef.value?.showPasswordInput()
    } else {
      appCouponAddCoupon()
    }
  } catch (error) {
    // 校验失败，显示第一个错误信息
    if (error instanceof z.ZodError) {
      const firstError = error.errors[0]
      uni.showToast({
        title: firstError.message,
        icon: 'none',
        duration: 2000
      })
    }
  }
}

function appCouponAddCoupon() {
  appCouponAddCouponPost({
    body: {
      ...payMethodOptions.value,
      ...formData.value,
      nameEn: formData.value.nameZh,
      // 用户输入1-100，转换为 1 - (x/100)，例如90 -> 0.1
      discountValue: Number((1 - (Number(formData.value.discountValue) / 100)).toFixed(2)),
      // 确保其他字段为数字类型
      totalQuantity: Number(formData.value.totalQuantity),
      validStart: Number(formData.value.validStart),
      validEnd: Number(formData.value.validEnd),
    }
  }).then(res => {
    uni.showToast({
      title: t('pages-user.coupons.validation.createSuccess'),
      icon: 'none'
    })
    uni.navigateBack()
  })
}

// 支付参数
const payMethodOptions = ref({
  orderId: '',
  cardId: '',
  payMethod: 1, // 支付方式 1信用卡 2余额
  payPassword: '',
})
const passwordInputRef = ref()
useEventEmit(EventEnum.CHOOSE_PAYMENT_METHOD, (data) => {
  if (data) {
    if (data.payMethod === 1) {
      payMethodOptions.value.cardId = data.cardId
      payMethodOptions.value.cardNumber = data.cardNumber
      payMethodOptions.value.payMethod = 1
    } else {
      payMethodOptions.value.payMethod = 2
    }
  }
})

function payPawSuccess(payPassword: string) {
  payMethodOptions.value.payPassword = payPassword
  appCouponAddCoupon()
}

// 获取用户默认信用卡信息
onLoad((options: any) => {
  // 是否免费添加优惠券
  appCouponCouponCost()
  // 查询用户默认信用卡
  appUserCardSelectDefault()
})

function appUserCardSelectDefault() {
  appUserCardSelectDefaultPost({}).then(res => {
    console.log('查询用户默认信用卡', res)
    payMethodOptions.value.cardId = res.data?.cardId || ''
    payMethodOptions.value.cardNumber = res.data?.cardNumber || ''
  })
}

const feeNum = ref(0)

function appCouponCouponCost() {
  appCouponCouponCostPost({}).then(res => {
    console.log('是否免费添加优惠券', res)
    if (res.data) {
      feeNum.value = Number(res.data) || 0
    }
  })
}
</script>

<template>
  <view>
    <navbar title="Add for free"></navbar>
    <view class="px-30rpx">
      <!--优惠券名称-->
      <view class="mt-44rpx">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">{{ t('pages-user.coupons.name') }}:</view>
        <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
          <wd-input
              v-model="formData.nameZh"
              :focus-when-clear="false"
              :maxlength="20"
              :placeholder="t('common.placeholder.pleaseEnter')"
              clearable
              confirm-type="search"
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholderStyle="font-size: 30rpx;color: #999;"
              use-prefix-slot
          >
          </wd-input>
        </view>
      </view>

      <!--优惠值-->
      <view class="mt-44rpx">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">{{ t('pages-user.coupons.discount') }}:</view>
        <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
          <wd-input
              v-model="formData.discountValue"
              :focus-when-clear="false"
              :max="100"
              :min="1"
              :placeholder="t('common.placeholder.pleaseEnter')"
              clearable
              confirm-type="search"
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholderStyle="font-size: 30rpx;color: #999;"
              type="number"
              use-prefix-slot
          >
          </wd-input>
        </view>
      </view>

      <!--Distribution quantity-->
      <view class="mt-44rpx">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">{{
            t('pages-user.coupons.totalQuantity')
          }}:
        </view>
        <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
          <wd-input
              v-model="formData.totalQuantity"
              :focus-when-clear="false"
              :placeholder="t('common.placeholder.pleaseEnter')"
              clearable
              confirm-type="search"
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholderStyle="font-size: 30rpx;color: #999;"
              type="number"
              use-prefix-slot
          >
          </wd-input>
        </view>
      </view>

      <!--生效日期:-->
      <view class="mt-44rpx" @click="openHours('start')">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">{{ t('pages-user.coupons.validStart') }}:</view>
        <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
          <text :class="formData.validStart ? 'text-#333' : 'text-#999'" class="text-30rpx lh-30rpx">
            {{
              formData.validStart ? dayjs(formData.validStart).format(`DD/MM/YYYY`) : t('common.placeholder.pleaseSelect')
            }}
          </text>
          <image class="w-32rpx h-32rpx" src="@img/chef/115.png"></image>
        </view>
      </view>


      <!--失效日期:-->
      <view class="mt-44rpx" @click="openHours('end')">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">{{ t('pages-user.coupons.validEnd') }}:</view>
        <view class="flex-center-sb h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6">
          <text :class="formData.validEnd ? 'text-#333' : 'text-#999'" class="text-30rpx lh-30rpx">
            {{
              formData.validEnd ? dayjs(formData.validEnd).format(`DD/MM/YYYY`) : t('common.placeholder.pleaseSelect')
            }}
          </text>
          <image class="w-32rpx h-32rpx" src="@img/chef/115.png"></image>
        </view>
      </view>

      <view v-if="feeNum > 0" class="mt-44rpx" @click="navigateTo('/pages-user/pages/choose-paymethod/index')">
        <view class="text-36rpx lh-36rpx text-#333 font-500 mb-20rpx">{{ t('pages-user.coupons.payMethods') }}:</view>
        <view class="h-98rpx px-24rpx rounded-16rpx bg-#F6F6F6 flex items-center w-full">
          <view class="w-full flex-center-sb text-32rpx lh-32rpx font-500 text-#333">
            <view class="flex items-center">
              <image
                  class="w-44rpx h-44rpx mr-28rpx shrink-0"
                  mode="aspectFit"
                  src="@img/chef/138.png"
              />
              <text class="">
                <template v-if="payMethodOptions.payMethod === 1">{{
                    t('pages-user.choosePaymethod.creditCard')
                  }}
                </template>
                <template v-else>{{ t('pages-user.choosePaymethod.wallet') }}</template>
              </text>
            </view>
            <view class="flex items-center">
              <view class="mr-12px">
                <template v-if="payMethodOptions.payMethod === 1">
                  <!--判断用户是否有信用卡  {{ t("pages-user.member.creditCard") }}-->
                  <text v-if="!payMethodOptions.cardId"></text>
                  <text v-else>{{ payMethodOptions.cardNumber }}</text>
                </template>
                <template v-else-if="payMethodOptions.payMethod === 2">
                  <!--                  {{ t('pages-user.choosePaymethod.wallet') }}-->
                  <text></text>
                </template>
              </view>
              <image
                  class="w-32rpx h-32rpx shrink-0"
                  mode="aspectFit"
                  src="@img/chef/142.png"
              />
            </view>
          </view>
        </view>
      </view>
    </view>


    <view class="px-90rpx flex items-center mt-104rpx" @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-login.continuing-agree') }}
        <text class="text-#00A76D"
              @click.stop="navigateTo('/pages/agreement/index?code=' + Agreement.CHEF_M_CODE_AGREEMENT)">
          《{{ t('agreement.codeAgreement') }}》
        </text>
      </view>
    </view>


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

    <fixed-bottom-large-btn
        :text="feeNum > 0 ? `${t('pages-user.coupons.paidPublishing')}($${feeNum})` : t('pages-user.coupons.publishNow')"
        class="z-100"
        fixed
        @click="submitForm"
    />


    <wd-popup v-model="show" position="bottom" @close="handleClose">
      <view>
        <view class="flex-center-sb h-102rpx bg-#F7F7F7 px-30rpx">
          <view class="text-30rpx text-#999" @click="handleClose">{{ t('common.cancel') }}</view>
          <view class="text-34rpx text-#333">
            {{
              dateType === 'start' ? t('pages-user.coupons.selectValidStartDate') : dateType === 'end' ? t('pages-user.coupons.selectValidEndDate') : t('pages-user.coupons.dateFilter')
            }}
          </view>
          <view class="text-30rpx text-#FF6106" @click="handleSubmit">{{ t('common.confirm') }}</view>
        </view>
        <view class="px-60rpx pt-60rpx">
          <wd-datetime-picker-view v-model="timeValue" :minDate="maxDate" type="date"/>
        </view>
      </view>
    </wd-popup>

    <password-container ref="passwordInputRef" @success="payPawSuccess"/>
  </view>
</template>

<style>
page {
  background-color: #fff;
}
</style>
<style lang="scss" scoped>
</style>