<route lang="json5">
{
  style: {
    navigationBarTitleText: '领取优惠券',
  },
}
</route>

<template>
  <view class="bg-gray-100 min-h-screen pb-20">
    <!-- 优惠券使用规则 -->
    <view class="bg-white px-4 py-4 mb-3 shadow-sm">
      <view class="flex items-center mb-3">
        <view class="text-lg font-bold text-gray-800">优惠券使用规则</view>
        <view class="ml-2 flex-1 h-px bg-gray-100"></view>
      </view>
      <view class="rules-text text-sm text-gray-600 space-y-1">
        <view>1. 优惠券审核后，有效期为30天，过期作废；</view>
        <view>2. 个人购买者：享受消费优惠券同类型农机不超过2台;</view>
        <view>3. 组织购买者：享受消费优惠券同类型农机不超过10台。</view>
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="bg-white px-4 py-4 shadow-sm">
      <view class="flex items-center mb-4">
        <view class="text-lg font-bold text-gray-800">请填写信息</view>
        <view class="ml-2 flex-1 h-px bg-gray-100"></view>
      </view>
      <wd-form ref="formRef" :model="formData">
        <wd-cell-group border>
          <!-- 用户类型 -->
          <wd-cell
            title="用户类型"
            title-width="100px"
            prop="userstype"
            required
            custom-class="custom-cell"
          >
            <wd-radio-group
              v-model="formData.userstype"
              @change="handleUserTypeChange"
              inline
              shape="dot"
              :rules="[{ required: true, message: '请选择用户类型' }]"
            >
              <wd-radio value="个人">个人</wd-radio>
              <wd-radio value="企业">企业</wd-radio>
            </wd-radio-group>
          </wd-cell>

          <!-- 姓名/企业名称 -->
          <wd-input
            :label="usersnameLabel"
            label-width="100px"
            prop="usersname"
            required
            v-model="formData.usersname"
            :placeholder="`请输入${usersnameLabel}`"
            clearable
            no-border
            :rules="[{ required: true, message: `请输入${usersnameLabel}` }]"
          />

          <!-- 证件号 -->
          <wd-input
            :label="idNumberLabel"
            label-width="100px"
            prop="idNumber"
            required
            v-model="formData.idNumber"
            :placeholder="`请输入${idNumberLabel}`"
            clearable
            no-border
            :rules="[{ required: true, message: `请输入${idNumberLabel}` }]"
          />

          <!-- 证件照片上传 -->
          <wd-cell
            :title="idPhotoLabel"
            title-width="100px"
            prop="idPhotoIds"
            required
            custom-class="custom-cell"
          >
            <view class="flex-1">
              <!-- 个人身份证上传 -->
              <template v-if="formData.userstype === '个人'">
                <UploadComponent
                  v-model="formData.idCardFiles"
                  v-model:fileIds="formData.idCardIds"
                  :limit="1"
                  attmodel="coupon_identity"
                  attpath="/coupon_identity/"
                  modelStats="idCardIds"
                  message="请上传身份证照片"
                  tips="请上传身份证正面照片"
                />
              </template>

              <!-- 企业营业执照上传 -->
              <template v-else>
                <UploadComponent
                  v-model="formData.businessLicenseFiles"
                  v-model:fileIds="formData.businessLicenseIds"
                  :limit="1"
                  attmodel="coupon_identity"
                  attpath="/coupon_identity/"
                  modelStats="businessLicenseIds"
                  message="请上传营业执照照片"
                />
              </template>
            </view>
          </wd-cell>

          <!-- 购机者照片上传 (可选) -->
          <wd-cell title="购机者照片" title-width="100px" custom-class="custom-cell">
            <view class="flex-1">
              <UploadComponent
                v-model="formData.buyerPhoto"
                v-model:fileIds="formData.buyerPhotoIds"
                :limit="1"
                :required="false"
                attmodel="coupon_buyer"
                attpath="/coupon_buyer/"
                modelStats="buyerPhotoIds"
                message="请上传购机者照片"
                tips="用于确认购机者身份"
              />
            </view>
          </wd-cell>

          <!-- 手机号 -->
          <wd-input
            label="手机号"
            label-width="100px"
            prop="phone"
            required
            v-model="formData.phone"
            placeholder="请输入您的手机号码"
            clearable
            no-border
            :rules="[
              { required: true, message: '请输入手机号码' },
              { required: false, pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' },
            ]"
            @blur="validatePhone"
          />
        </wd-cell-group>
      </wd-form>
    </view>

    <!-- 提交按钮 -->
    <view class="fixed-bottom bg-white p-4 border-t border-gray-100">
      <wd-button type="primary" block size="large" @click="handleSubmit" :loading="submitLoading">
        确认领取
      </wd-button>
    </view>

    <!-- loading -->
    <wd-overlay :show="overlayShow">
      <view class="wrapper w-full h-full flex items-center justify-center">
        <wd-loading />
      </view>
    </wd-overlay>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, onUnmounted, onMounted } from 'vue'
import { useCouponStore } from '@/store/coupon'
import { useMessage } from 'wot-design-uni'
import { onLoad } from '@dcloudio/uni-app'
import UploadComponent from '@/components/UploadComponent.vue'

const couponStore = useCouponStore()
const message = useMessage()

const productsid = ref('') // 产品id
const couponid = ref('') // 优惠券（主劵）id
const usersid = ref('') // 用户id（销售点userid）

const formRef = ref<any>()
const formData = reactive({
  userstype: '个人', // 用户类型，默认个人
  usersname: '', // 姓名或企业名称
  idNumber: '', // 证件号

  // 身份证照片（个人用户）
  idCardFiles: [], // 身份证照片文件列表
  idCardIds: [], // 身份证照片ID列表

  // 营业执照（企业用户）
  businessLicenseFiles: [], // 营业执照照片文件列表
  businessLicenseIds: [], // 营业执照照片ID列表

  // 购机者照片(可选)
  buyerPhoto: [], // 购机者照片文件列表
  buyerPhotoIds: [], // 购机者照片ID列表

  phone: '', // 手机号
})

const usersnameLabel = computed(() => (formData.userstype === '个人' ? '姓名' : '企业名称'))
const idNumberLabel = computed(() =>
  formData.userstype === '个人' ? '身份证号' : '统一社会信用代码',
)
const idPhotoLabel = computed(() => (formData.userstype === '个人' ? '身份证正面' : '营业执照'))

const overlayShow = ref(false)
const submitLoading = ref(false)

// 手机号验证相关
const isPhoneValid = ref(false)
const phoneReg = /^1[3-9]\d{9}$/

function validatePhone() {
  if (!formData.phone) {
    isPhoneValid.value = false
    return
  }
  isPhoneValid.value = phoneReg.test(formData.phone)
  if (!isPhoneValid.value && formData.phone) {
    uni.showToast({ title: '请输入正确的手机号码', icon: 'none' })
  }
}

// 用户类型切换
function handleUserTypeChange() {
  // 清空相关字段以便用户重新输入和校验
  formData.usersname = ''
  formData.idNumber = ''

  // 清空证件照片上传
  if (formData.userstype === '个人') {
    formData.idCardFiles = []
    formData.idCardIds = []
    formData.businessLicenseFiles = []
    formData.businessLicenseIds = []
  } else {
    formData.idCardFiles = []
    formData.idCardIds = []
    formData.businessLicenseFiles = []
    formData.businessLicenseIds = []
  }

  // 清空购机者照片
  formData.buyerPhoto = []
  formData.buyerPhotoIds = []
}

// 提交表单
async function handleSubmit() {
  try {
    const valid = await formRef.value.validate()
    if (!valid) {
      return
    }

    validatePhone()
    if (!isPhoneValid.value) {
      uni.showToast({ title: '请输入正确的手机号码', icon: 'none' })
      return
    }

    // 验证证件照片上传
    const hasUploadedFiles =
      formData.userstype === '个人'
        ? formData.idCardIds.length > 0
        : formData.businessLicenseIds.length > 0

    if (!hasUploadedFiles) {
      uni.showToast({
        title: `请上传${formData.userstype === '个人' ? '身份证照片' : '营业执照照片'}`,
        icon: 'none',
      })
      return
    }

    submitLoading.value = true
    overlayShow.value = true

    // 获取证件照片IDs
    const fileIds =
      formData.userstype === '个人'
        ? formData.idCardIds.map((item) => item.id).join(',')
        : formData.businessLicenseIds.map((item) => item.id).join(',')

    // 收集所有上传文件的ID（包括购机者照片）
    const allFileIds = [
      ...fileIds.split(',').filter((id) => id), // 证件照片ID
      ...formData.buyerPhotoIds.map((item) => item.id), // 购机者照片ID
    ]
    const finalFileIds = allFileIds.join(',')

    // 调用领取优惠券API
    const res = await couponStore.receiveCouponNew({
      couponid: couponid.value,
      userstype: formData.userstype,
      usersshtyxydm: formData.userstype === '企业' ? formData.idNumber : '',
      usersidcardnumber: formData.userstype === '个人' ? formData.idNumber : '',
      usersname: formData.usersname,
      coupon2productids: productsid.value,
      coupon2phone: formData.phone,
      filesid: finalFileIds, // 上传的文件ID字符串（包含证件和购机者照片）
      coupon2merchantid: usersid.value,
      // smsCode: formData.smsCode,
      // ... 其他可能需要的参数
    })

    // console.log('领取优惠券API成功', res)  领取优惠券API成功 2025052017584880465552

    message
      .confirm({
        msg: '优惠券领取成功！',
        title: '提示',
        confirmButtonText: '使用优惠劵下单',
        cancelButtonText: '返回到产品页',
      })
      .then(() => {
        // 跳转回formStep3页面
        // 注意：需要确保formStep3页面能够正确处理返回逻辑，比如刷新优惠券列表
        uni.navigateTo({
          // url: `/pages/form/formStep4?usersid=${usersid.value}&productsid=${productsid.value}&couponcode=${res}`,  // 跳转到formStep4 下单页面
          url: `/pages/coupon/index`, // 跳转到优惠劵列表
        })
      })
      .catch(() => {
        // 取消操作，不做任何处理
        uni.navigateBack()
      })
  } catch (error) {
    console.error('领取优惠券出错：', error)
  } finally {
    submitLoading.value = false
    overlayShow.value = false
  }
}

onLoad(async (query: any) => {
  productsid.value = query.productsid || ''
  couponid.value = query.couponid || ''
  usersid.value = query.usersid || ''
  // 可以根据 query 中的参数做一些初始化操作
})
onUnmounted(() => {
  // 如果需要清理任何资源，可以在这里添加清理逻辑
})

// 将校验规则绑定到form
onMounted(() => {
  // 初始化其他必要的操作
})
</script>

<style lang="scss" scoped>
.rules-text {
  line-height: 1.6;
}

.fixed-bottom {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 100;
}

// 针对 wd-field 内的 wd-input, wd-radio-group 等组件去除边框或调整样式
:deep(.wd-cell-group .wd-input) {
  // If they don't have a border by default or if no-border is not working as expected
  // Example:
  // border-bottom: 1px solid #eee;
}
:deep(.wd-cell-group .wd-input__inner) {
  // If no-border was intended to remove internal padding/borders of wd-input for wd-field
  // We might not need this if wd-input itself looks fine as a direct child of wd-cell-group.
  // The no-border prop on wd-input might be sufficient.
}

// For wd-cell containing radio group or other custom layouts
:deep(.custom-cell .wd-cell__value) {
  flex: 1; // Allow radio group or other content to take full width
}
:deep(.custom-cell .wd-radio-group) {
  // specific styles for radio group if needed
}

// 调整获取验证码按钮的样式，如果需要
// :deep(.wd-button--small) {
//   // padding: 0 8px;
// }

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>
