<route lang="json5">
{
  style: {
    navigationBarTitleText: '农机详情',
  },
}
</route>

<template>
  <!-- 选网点，选择机器型号，输入SN号，下订单 -->
  <view class="bg-gray-100 min-h-screen pb-6">
    <!-- 产品名称头部 -->
    <view class="bg-white px-4 py-1 mb-3 shadow-sm">
      <view class="product-title text-xl font-bold text-gray-800">
        {{ productInfo?.productsname }}
      </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>
      <div class="detail-box rounded-lg">
        <wd-cell-group inset>
          <wd-cell title="产品名称" :value="productInfo?.productsname" />
          <wd-cell title="生产企业" :value="productInfo?.scqyinfomc" />
          <wd-cell title="机具类型" :value="productInfo?.productsjjlx" />
          <wd-cell title="产品类别" :value="productInfo?.productscategory" />
          <wd-cell title="产品型号" :value="productInfo?.productsmodel" />
          <wd-cell
            title="分类"
            :value="`${productInfo?.productsfl1} - ${productInfo?.productsfl2}`"
          />
          <wd-cell title="品目" :value="productInfo?.productspm" />
          <wd-cell
            title="产品原价"
            :value="`¥${Number(productInfo?.productsprice).toFixed(2)}`"
            value-class="text-red-500 font-medium"
          />
          <wd-cell
            title="中央补贴金额"
            :value="`¥${Number(productInfo?.productszybt).toFixed(2)}`"
            value-class="text-green-500 font-medium"
          />
          <wd-cell
            title="特殊县中央补贴金额"
            :value="`¥${Number(productInfo?.productstsxzybt).toFixed(2)}`"
            value-class="text-green-500 font-medium"
          />
        </wd-cell-group>
      </div>
    </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>
      <!-- 优惠劵列表 -->
      <view class="coupon-box">
        <!-- 这里添加优惠券列表组件 -->
        <view v-if="!coupons?.length" class="text-center py-8 text-gray-400">暂无可用优惠券</view>
        <view v-else>
          <view class="coupon-list">
            <wd-radio-group v-model="couponChoose" shape="dot">
              <wd-radio :value="coupon.couponid" v-for="coupon in coupons" :key="coupon.couponid">
                <view class="flex items-center justify-between">
                  <view class="text-gray-800">{{ coupon.couponmc }}</view>
                </view>
              </wd-radio>
            </wd-radio-group>
          </view>
        </view>
      </view>
      <!-- 领取优惠劵 -->
      <view class="mt-4 px-2">
        <wd-button type="primary" plain block @tap="showPhoneDialog">领取优惠劵</wd-button>
      </view>
    </view>

    <!-- 下单 -->
    <!-- 立即下单按钮 -->
    <view class="fixed-bottom bg-white p-4 border-t border-gray-100">
      <wd-button type="primary" block size="large" @tap="handleOrder">立即下单</wd-button>
    </view>

    <!-- 手机号输入弹窗 -->
    <wd-popup
      v-model="phoneDialogVisible"
      round
      :closable="true"
      title="请输入手机号"
      custom-class="w-[80%]"
    >
      <view class="phone-dialog p-6">
        <view class="text-center mb-5">
          <view class="text-lg font-semibold text-gray-800 mb-2">请输入您的手机号码</view>
          <view class="text-sm text-gray-500">领取优惠券需要验证您的手机号</view>
        </view>
        <wd-input
          v-model="phone"
          placeholder="请输入您的手机号码"
          clearable
          :error="phoneError"
          :error-message="phoneErrorMsg"
          @blur="validatePhone"
          required
          class="mb-4"
        />
        <view class="mt-6">
          <wd-button
            type="success"
            block
            @click="handleSubmit"
            :loading="submitLoading"
            :disabled="submitLoading"
          >
            确认领取
          </wd-button>
        </view>
      </view>
    </wd-popup>

    <!-- 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 { useProductStore } from '@/store/product'
import { useCouponStore } from '@/store/coupon'
import { useMessage } from 'wot-design-uni'
import { useAppStore } from '@/store/app'

const couponStore = useCouponStore()
const productStore = useProductStore()
const appStore = useAppStore()
const message = useMessage()
const usersid = ref('') // 销售网点用户id（渠道id）
const productsid = ref('') // 产品id
const productInfo = ref<any>(null) // 产品详情
const overlayShow = ref(false) // 加载状态
const coupons = ref<any[]>([]) // 可用优惠券列表
const couponChoose = ref('') // 选择的优惠券ID
const submitLoading = ref(false) // 提交订单loading
const phoneDialogVisible = ref(false) // 手机号输入弹窗显示状态

// 手机号相关
const phone = ref('')
const phoneError = ref(false)
const phoneErrorMsg = ref('')

// 显示手机号输入弹窗
function showPhoneDialog() {
  // 检查是否选择了优惠券
  if (!couponChoose.value && coupons.value && coupons.value.length > 0) {
    message.alert({
      msg: '请选择优惠券',
      title: '提示',
    })
    return
  }

  phoneDialogVisible.value = true
}

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

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

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

// 提交表单
async function handleSubmit() {
  // 验证手机号
  if (!validatePhone()) {
    return
  }

  submitLoading.value = true

  // 获取选中的优惠券
  const selectedCoupon = coupons.value.find((coupon) => coupon.couponid === couponChoose.value)

  if (!selectedCoupon) {
    message.alert({
      msg: '请选择优惠券',
      title: '提示',
    })
    submitLoading.value = false
    return
  }

  try {
    // 调用领取优惠券API
    const result = await couponStore.receiveCoupon({
      couponid: selectedCoupon.couponid,
      coupon2phone: phone.value,
      coupon2productids: productsid.value,
    })

    if (result && result.Success) {
      message.alert({
        msg: '优惠券领取成功,请注意查收短信',
        title: '提示',
      })
      phoneDialogVisible.value = false // 关闭弹窗
    } else {
      message.alert({
        msg: result?.Message || '领取失败，请稍后再试',
        title: '提示',
      })
    }

    submitLoading.value = false
  } catch (error) {
    console.error('领取优惠券出错：', error)
    message.alert({
      msg: '操作失败',
      title: '提示',
    })
    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
}

// 获取优惠券列表
async function getCouponList() {
  if (!productsid.value) return
  coupons.value = await couponStore.getCouponList(productsid.value)
  // 如果有可用优惠券，默认选中第一个
  if (coupons.value && coupons.value.length > 0) {
    couponChoose.value = coupons.value[0].couponid
  }
}

// 立即下单
function handleOrder() {
  // 检查登录状态
  if (!appStore.isLoginState) {
    // 未登录状态，显示确认框
    message
      .confirm({
        title: '提示',
        msg: '请先登录后再进行下单操作',
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
      })
      .then(() => {
        // 用户点击确认，跳转到登录页面
        // 保存当前页面路径用于登录后回跳
        const currentPage = getCurrentPages()[getCurrentPages().length - 1].route
        const queryParams = `?usersid=${usersid.value}&productsid=${productsid.value}`
        const redirectPath = `/${currentPage}${queryParams}`

        uni.navigateTo({
          url: `/pages-sub/auth/index?redirect=${encodeURIComponent(redirectPath)}`,
        })
      })
      .catch(() => {
        // 取消操作，不做任何处理
      })
  } else {
    // 已登录状态，跳转到订单确认页面
    uni.navigateTo({
      url: `/pages/form/formStep4?usersid=${usersid.value}&productsid=${productsid.value}`,
    })
  }
}

onLoad(async (query) => {
  usersid.value = query.usersid
  productsid.value = query.productsid
  getProductDetail() // 获取产品详情
  getCouponList() // 获取优惠券列表
})
</script>

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

.detail-box {
  :deep(.wd-cell__wrapper) {
    // @apply py-2;
  }

  :deep(.wd-cell__title) {
    @apply text-gray-600 min-w-[120px] text-sm;
  }

  :deep(.wd-cell__value) {
    @apply text-gray-800 text-sm whitespace-nowrap;
  }
}

.coupon-box {
  @apply rounded-lg;
}

.coupon-list {
  // :deep(.wd-radio) {
  //   @apply py-2;
  // }

  :deep(.wd-radio__label) {
    @apply flex-1 pr-4;
  }
}
</style>
