<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>

    <!-- SN码 -->
    <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">农机SN码</view>
        <view class="ml-2 flex-1 h-px bg-gray-100"></view>
      </view>
      <div class="detail-box rounded-lg">
        <wd-form ref="form" :model="model">
          <wd-cell-group border>
            <wd-input
              label="SN码"
              label-width="100px"
              prop="ordersproductsn"
              clearable
              v-model="model.ordersproductsn"
              placeholder="请输入SN码"
              :rules="[{ required: true, message: '请填写SN码' }]"
            />
          </wd-cell-group>
        </wd-form>
      </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" @change="couponRadioChange">
              <wd-radio
                :value="coupon.couponid"
                v-for="coupon in couponsShow"
                :key="coupon.couponid"
              >
                <view class="flex items-center justify-between">
                  <view class="text-gray-800">{{ coupon.couponmc }}</view>
                  <view class="flex items-center justify-end" @click.stop>
                    <wd-button
                      size="small"
                      type="success"
                      @click="handleReceive(coupon)"
                      plain
                      hairline
                      :disabled="!coupon.canReceive"
                    >
                      {{ !coupon.canReceive ? '已领取' : '领取并使用' }}
                    </wd-button>
                  </view>
                </view>
              </wd-radio>
            </wd-radio-group>
          </view>
        </view>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="mt-2 pb-4 px-2">
      <wd-button type="success" block @tap="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 { useProductStore } from '@/store/product'
import { useCouponStore } from '@/store/coupon'
import { useOrderStore } from '@/store/order'
import { useAppStore } from '@/store/app'
import { useUserStore } from '@/store/user'
import { useMessage } from 'wot-design-uni'

const appStore = useAppStore()
const userStore = useUserStore()
const couponStore = useCouponStore()
const productStore = useProductStore()
const orderStore = useOrderStore()
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 currentCoupon2id = ref('') // 当前选中的优惠劵
const coupon2idList = ref<any[]>([]) // 已领取的优惠券ID列表
const couponsShow = ref<any[]>([]) // 展示的优惠券列表
const couponChoose = ref('') // 选择的优惠券ID
const submitLoading = ref(false) // 提交订单loading
const model = reactive<{
  ordersproductsn: string
}>({
  ordersproductsn: '',
})
const form = ref()

// 提交表单
function handleSubmit() {
  // 判断是否完善了个人信息
  if (!userStore.isAuthComplete) {
    message
      .confirm({
        msg: '您还未完善个人信息, 请先完善信息',
        title: '提示',
        confirmButtonText: '去完善',
        cancelButtonText: '继续浏览',
      })
      .then(() => {
        uni.navigateTo({
          url: '/pages-sub/user/index',
        })
      })
      .catch(() => {
        // ...
      })
  }

  form.value.validate().then(async (res) => {
    if (res.valid) {
      // 判断是否选择了优惠券
      if (couponsShow.value.length && !currentCoupon2id.value) {
        message.alert({
          msg: '当前有可用优惠券，请选择优惠券',
          title: '提示',
        })
        return
      }

      try {
        submitLoading.value = true
        await orderStore.submitOrder({
          ordersproductid: productsid.value,
          orderscouponid: currentCoupon2id.value,
          ordersproductsn: model.ordersproductsn,
          ordersuserid1: usersid.value, // 渠道id  魏哥：微信下单增加参数ordersuserid1对应渠道id,后端渠道看自己的订单数据相比管理员只需要另外新增菜单权限配置，额外固定配置参数ordersuserid1.value=session:workeruserid，界面都可以先套用，然后给渠道归类一个角色。
        })
        message
          .alert({
            msg: '提交成功',
            title: '提示',
          })
          .then(() => {
            uni.navigateTo({ url: '/pages/order/index' })
          })
          .finally(() => {
            submitLoading.value = false
          })
      } catch (error) {
        message.alert({
          msg: '提交失败',
          title: '提示',
        })
      } 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
}

// 获取可用优惠券列表
async function getCouponList() {
  if (!productsid.value) return
  coupons.value = await couponStore.getCouponList(productsid.value)
}

// 领取优惠券
async function handleReceive(coupon: any) {
  overlayShow.value = true
  await couponStore.receiveCoupon(coupon.couponid)
  overlayShow.value = false

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

  // 重新获取优惠券列表状态
  await getCouponsShow()
}

// 获取该用户下，已领取的优惠劵id，用于判断是否可以领取
async function getCoupon2id() {
  const { Data } = await couponStore.getCoupon2id({
    coupon2userid: appStore.appInfo.userid,
    coupon2isused: 0,
    coupon2productids: productsid.value,
  })

  coupon2idList.value = Data
}

// 优惠券选择
async function couponRadioChange(e: any) {
  currentCoupon2id.value = couponsShow.value.find((item) => item.couponid === e.value)?.coupon2code
}

// 获取可展示的优惠券列表
function getCouponsShow() {
  Promise.all([
    getCouponList(), // 获取可用优惠券列表
    getCoupon2id(), // 获取该用户下，已领取的优惠劵id，用于判断是否可以领取
  ]).then(() => {
    couponsShow.value = coupons.value.map((coupon) => {
      // 找到匹配的已领取优惠券记录
      const receivedCoupon = coupon2idList.value.find(
        (item) => item.coupon2coupon1id === coupon.couponid,
      )

      return {
        ...coupon,
        canReceive: !receivedCoupon,
        coupon2sid: receivedCoupon?.coupon2sid,
        coupon2code: receivedCoupon?.coupon2code,
      }
    })
  })
}

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

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

.detail-box {
  :deep(.wd-cell) {
    // @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;
  }
}

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

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

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