<route lang="json5">
{
  style: {
    navigationBarTitleText: '确认下单',
  },
}
</route>

<template>
  <!-- 选网点，选择机器型号，输入SN号，下订单 -->
  <view class="bg-gray-100 min-h-screen pb-6">
    <!-- 步骤1：优惠码输入 -->
    <view class="bg-white px-4 py-4 mb-3 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-cell-group>
        <!-- 优惠码 -->
        <wd-input
          label="优惠码"
          v-model="formData.couponCode"
          placeholder="请输入优惠码"
          clearable
          required
          :error="couponError"
          :error-message="couponErrorMsg"
          @blur="validateCoupon"
          right-icon="warning"
          @click-right-icon="handleCouponInfo"
        />
      </wd-cell-group>

      <view class="mt-4">
        <wd-button type="primary" block @tap="verifyCouponCode" :loading="verifyLoading">
          验证优惠码
        </wd-button>
      </view>
    </view>

    <!-- 步骤2：显示产品信息和其他输入字段（仅在优惠码验证成功后显示） -->
    <template v-if="isVerified && productInfo">
      <!-- 产品信息 -->
      <view v-if="productInfo" class="bg-white px-4 py-4 mb-3 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>

        <view class="product-detail">
          <view class="product-title text-xl font-bold text-gray-800 mb-3">
            {{ productInfo.productsname }}
          </view>
          <view class="text-gray-600 mb-1">生产企业: {{ productInfo.scqyinfomc }}</view>
          <view class="text-gray-600 mb-1">机具类型: {{ productInfo.productsjjlx }}</view>
          <view class="text-gray-600 mb-1">产品型号: {{ productInfo.productsmodel }}</view>
        </view>
      </view>

      <!-- 表单信息 -->
      <view class="bg-white px-4 py-4 mb-3 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-cell-group>
          <!-- SN号 -->
          <wd-input
            label="SN码"
            v-model="formData.sn"
            placeholder="请输入SN码"
            clearable
            required
            :error="snError"
            :error-message="snErrorMsg"
            @blur="validateSn"
          />

          <!-- 手机号 -->
          <wd-input
            label="手机号"
            v-model="formData.phone"
            placeholder="请输入手机号"
            clearable
            required
            :error="phoneError"
            :error-message="phoneErrorMsg"
            @blur="validatePhone"
          />
        </wd-cell-group>
      </view>

      <!-- 发票上传 -->
      <view class="bg-white px-4 py-4 mb-3 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>

        <view class="mb-4">
          <view class="text-gray-700 mb-2 text-base flex items-center">
            <text>发票照片</text>
            <text class="text-gray-400 ml-1">(可选)</text>
          </view>
          <UploadComponent
            v-model="formData.invoiceFiles"
            v-model:fileIds="formData.invoiceFileIds"
            :limit="1"
            :required="false"
            attmodel="orders_invoice"
            attpath="/orders_invoice/"
            modelStats="invoiceFileIds"
            message="请上传发票照片"
            tips="请上传清晰的发票照片"
          />
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="px-4 pt-4 pb-12">
        <wd-button type="primary" block size="large" @tap="handleSubmit" :loading="submitLoading">
          确认下单
        </wd-button>
      </view>
    </template>

    <!-- 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 { ref, reactive, computed } from 'vue'
import { useUserStore } from '@/store/user'
import { useMessage } from 'wot-design-uni'
import { useProductStore } from '@/store/product'
import { useOrderStore } from '@/store/order'
import { useCouponStore } from '@/store/coupon'
import UploadComponent from '@/components/UploadComponent.vue'

const message = useMessage()
const userStore = useUserStore()
const productStore = useProductStore()
const orderStore = useOrderStore()
const couponStore = useCouponStore()

// 页面参数
const usersid = ref('') // 销售网点用户id（渠道id）
const productsid = ref('') // 产品id
const couponCode = ref('') // 优惠码

const productInfo = ref<any>(null) // 产品详情
const overlayShow = ref(false) // 加载状态
const submitLoading = ref(false) // 提交订单loading
const verifyLoading = ref(false) // 验证优惠码loading
const isVerified = ref(false) // 优惠码是否已验证

// 表单数据
const formData = reactive({
  sn: '', // SN码
  phone: '', // 手机号
  couponCode: '', // 优惠码
  // 新增发票相关字段
  invoiceFiles: [], // 发票照片文件列表
  invoiceFileIds: [], // 发票照片ID列表
})

// 表单验证状态
const snError = ref(false)
const snErrorMsg = ref('')
const phoneError = ref(false)
const phoneErrorMsg = ref('')
const couponError = ref(false)
const couponErrorMsg = ref('')

// 验证SN码
function validateSn() {
  if (!formData.sn) {
    snError.value = true
    snErrorMsg.value = '请输入SN码'
    return false
  }

  snError.value = false
  snErrorMsg.value = ''
  return true
}

// 验证手机号
function validatePhone() {
  if (!formData.phone) {
    phoneError.value = true
    phoneErrorMsg.value = '请输入手机号码'
    return false
  }

  const phoneReg = /^1[3-9]\d{9}$/
  if (!phoneReg.test(formData.phone)) {
    phoneError.value = true
    phoneErrorMsg.value = '请输入正确的手机号码'
    return false
  }

  phoneError.value = false
  phoneErrorMsg.value = ''
  return true
}

// 验证优惠码
function validateCoupon() {
  if (!formData.couponCode) {
    couponError.value = true
    couponErrorMsg.value = '请输入优惠码'
    return false
  }

  couponError.value = false
  couponErrorMsg.value = ''
  return true
}

// 验证优惠码并获取产品信息
async function verifyCouponCode() {
  if (!validateCoupon()) return

  try {
    verifyLoading.value = true
    overlayShow.value = true

    const result = await couponStore.getCoupon2ViewmList({
      coupon2code: formData.couponCode,
    })

    if (result && result.Data && result.Data.length > 0) {
      // 获取优惠券对应的产品信息
      const couponProduct = result.Data[0]

      // 设置产品ID
      productsid.value = couponProduct.coupon2productids || ''

      // 获取产品详细信息
      await getProductDetail()

      // 填充手机号码（优先使用优惠券中的手机号，如果没有则使用用户当前手机号）
      if (couponProduct.coupon2phone) {
        formData.phone = couponProduct.coupon2phone
      } else if (userStore.userDetail?.usersphone) {
        formData.phone = userStore.userDetail.usersphone
      }

      isVerified.value = true
      message.alert({
        title: '成功',
        msg: '优惠码验证成功',
      })
    } else {
      message.alert({
        title: '提示',
        msg: '无效的优惠码，请检查后重试',
      })
    }
  } catch (error) {
    console.error('验证优惠码出错:', error)
    message.alert({
      title: '提示',
      msg: '验证优惠码失败，请稍后再试',
    })
  } finally {
    verifyLoading.value = false
    overlayShow.value = false
  }
}

// 处理优惠码信息提示
function handleCouponInfo() {
  message.alert({
    title: '优惠码说明',
    msg: '请输入您收到的优惠码，验证成功后可以查看产品信息并下单',
  })
}

// 验证表单
function validateForm() {
  if (!validateSn()) return false
  if (!validatePhone()) return false

  // 证件上传相关的验证已移除
  // 发票上传是可选的，此处不添加验证

  return true
}

// 提交表单
async function handleSubmit() {
  // 表单验证
  if (!validateForm()) return

  try {
    submitLoading.value = true

    // 收集所有上传文件的ID
    const allFileIds = [
      ...formData.invoiceFileIds, // 包含发票文件ID
    ]

    // 提取ID字段
    const fileIdsString = allFileIds.map((item) => item.id).join(',')

    // 准备提交数据
    const orderData = {
      ordersproductid: productsid.value, // 产品id
      orderscouponid: formData.couponCode, // 优惠码
      ordersproductsn: formData.sn, // SN号
      ordersuserid1: usersid.value, // 销售网点id
      ordersphone: formData.phone, // 手机号
      filesid: fileIdsString, // 文件ID，已获取
    }

    // 调用下单接口
    const result = await orderStore.submitOrderTel(orderData)

    message.alert({
      title: '提示',
      msg: '下单成功',
    })

    // 下单成功后跳转到订单列表页
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/order/index',
      })
    }, 1500)
  } catch (error) {
    console.error('下单出错:', error)
    message.alert({
      title: '提示',
      msg: '下单失败，请稍后再试',
    })
  } finally {
    submitLoading.value = false
  }
}

// 获取产品详情
async function getProductDetail() {
  if (!productsid.value) return
  overlayShow.value = true
  productInfo.value = await productStore.getProductDetail({
    productsid: productsid.value,
    merchantid: usersid.value,
  })
  overlayShow.value = false
}

// 页面加载
onLoad(async (query) => {
  usersid.value = query.usersid || '' // 销售网点id（渠道id）
  couponCode.value = query.couponcode || '' // 优惠码
  formData.couponCode = couponCode.value

  // 如果优惠码不为空，触发验证优惠码
  if (couponCode.value) {
    await verifyCouponCode()
  }
})
</script>

<style lang="scss" scoped>
.product-title {
  @apply leading-relaxed break-all;
}

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