<script setup lang="ts">
// import mpHtml from 'mp-html/dist/uni-app/components/mp-html/mp-html'
import {
  getDyProductDetail,
  getJdProductDetail,
  getPddProductDetail, getShareId,
  getSuProductDetail,
  getTaobaoProductDetail,
  getVipProductDetail
} from "~/apis/product";
import CXBBasePage from "~/components/CXBBasePage/CXBBasePage.vue";
import type {
  IProductDetail,
  JdProductDetailModel,
  TaobaoProductThirdPartyWaresModel,
  TaobaoWaresDetail
} from "~/apis/model/product.model";
import FPrice from "~/components/FPrice/FPrice.vue";
import FButton from "~/components/FButton/FButton.vue";
import CXBButton from "~/components/CXBButton/CXBButton.vue";
import CXBBackTop from "~/components/CXBBackTop/CXBBackTop.vue";
import {debounce, merge} from "lodash-es";

import {useDebounceFn} from '@vueuse/core';

import dayjs from "dayjs";
import {decodeBase64} from "~/utils/http/helper";
import {CDN_URL} from "~/config/app";

const discount_coupon_bg_220804Image = CDN_URL + '/static/assets/discount_coupon_bg_220804.png'
const productId = ref('')
//

const userStore = useUserStore()
const isSubmit = ref(false)
const productType = ref(-1)
// 优惠券劵信息
const coupon = ref({
  // 优惠券金额
  money: '',
  // 优惠券有效期
  startTime: '',
  endTime: ''
})
const productDetail = ref<JdProductDetailModel | TaobaoWaresDetail>()

const props = defineProps({
  type: {
    type: Number,
    default: 0
  }
})

const state = reactive({
  data: {},
  shareId: ''
})
const detail = ref<IProductDetail>()
onLoad((options: any) => {

  const data: Partial<IProductDetail> = JSON.parse(decodeBase64(options.params))
  // console.log(data)
  mergeProductDetail(data)
  // if (options.platform && options.id) {
  uni.showLoading({
    title: '数据加载中',
    icon: 'none'
  })
  loadProductDetail(data)
  // }
})
onShow(() => {
  isSubmit.value = false
})



function mergeProductDetail(data: Partial<IProductDetail> = {}) {
  detail.value = merge(detail.value, data)
}

function loadProductDetail(product: Partial<IProductDetail>) {
  // console.log('产品id')
  // console.log(product.id)
  // 京东
  if (product.platform == 6) {
    getJdProductDetail(product.id).then(res => {
      const jdProduct = res[0]
      // console.log(jdProduct)
      mergeProductDetail({
        images: jdProduct.detail,
        coupon: {
          amount: jdProduct.couMoney
        },
        ...jdProduct
      })

      uni.hideLoading()
    })
  }
  // 淘宝
  if (product.platform === 5) {
    getTaobaoProductDetail(product.id).then(res => {
      const product = res.waresDetail
      mergeProductDetail({
        images: product.small_images,
        coupon: {
          startTime: product.couponStartTime,
          endTime: product.couponEndTime
        },
        ...product
      })
      uni.hideLoading()

    })
  }

  // 拼多多
  if (product.platform == 1) {
    getPddProductDetail(product.id).then(res => {
      // detail.value = res
      mergeProductDetail({
        spreadUrl: res.pddlink.url,
        images: res.goods_gallery_urls,
        featured: res.goods_gallery_urls,
        mallName: res.mall_name,
        ...res
        // allowance:
      })

      if (res.coupon_start_time > 0) {
        mergeProductDetail({
          coupon: {
            // amount: (res.extra_coupon_amount / 100).toString(),
            startTime: dayjs.unix(res.coupon_start_time).format('YYYY-MM-DD'),
            endTime: dayjs.unix(res.coupon_end_time).format('YYYY-MM-DD')
          },
        })
      } else {
        mergeProductDetail({
          coupon: null
        })
      }

      uni.hideLoading()

    })
  }

  // 唯品会
  if (product.platform == 2) {
    getVipProductDetail(product.id).then(res => {
      // console.log(res.result[0])
      const product = res.result[0]
      // detail.value = product
      mergeProductDetail({
        featured: product.goodsCarouselPictures,
        images: product.goodsDetailPictures,
        mallName: '唯品自营',
        ...product,
        ...res
      })
      if (product.couponInfo) {
        mergeProductDetail({
          coupon: {
            amount: product.couponInfo.activedAmount,
            startTime: product.couponInfo.useBeginTime,
            endTime: product.couponInfo.useEndTime
          }
        })
      }

      uni.hideLoading()

    })
  }
  // 苏宁
  if (product.platform == 3) {
    getSuProductDetail(product.id).then(res => {
      // const product = res
      mergeProductDetail({
        images: res.detail,
        ...res
      })

      uni.hideLoading()

    })
  }
  // 抖音
  if (product.platform == 9) {
    getDyProductDetail(product.id).then(res => {
      console.log(res)
      mergeProductDetail({
        mallName: res.shopName,
        images: res.imgs,
        ...res
      })

      uni.hideLoading()

    })


  }
}

function handleBuyNow() {
  if (isSubmit.value) return
  if (!userStore.uid) {
    isSubmit.value = true

    uni.navigateTo({
      url: '/pages/user/login/index'
    })
  }
  if (detail.value?.platform) {
    // 京东
    if (detail.value?.platform == 6 && detail.value?.materialUrl) {
      // console.log(detail.value?.spreadUrl)
      console.log(detail.value)
      if (detail.value && detail.value.materialUrl) {
        uni.navigateToMiniProgram({
          appId: 'wx91d27dbf599dff74',
          // path: 'pages/union/proxy/proxy?spreadUrl=' + encodeURIComponent(detail.value?.spreadUrl),
          path: 'pages/union/proxy/proxy?spreadUrl=' + detail.value.materialUrl,
          extraData: {
            foo: 'bar'
          },
          envVersion: 'release',
          success(res) {
            // 打开成功
            // console.log(res);
          },
          fail: (error) => {
            console.log(error);
          }
        })
      } else {
        return uni.showToast({
          title: '跳转失败请重试',
          icon: 'none'
        })
      }
    } else if (detail.value?.platform == 1) {
      // console.log(detail.value)
      const pddWx = detail.value.pddlink.wx
      if (pddWx) {
        uni.navigateToMiniProgram({
          appId: pddWx.app_id,
          path: pddWx.page_path,
          // extraData: {
          //  foo: 'bar'
          // },
          envVersion: 'release',
          success(res) {
            // 打开成功
            // console.log(res);
          },
          fail: (error) => {
            console.log(error);
          }
        })

      } else {
        uni.showToast({
          title: '跳转失败请重试',
          icon: 'none'
        })
      }
      // console.log(detail.value.pddlink)
      // console.log(pddWx)
    } else {
/*      let platformName = ''
      let clipboardData = ''
      if (detail.value?.platform == 5) {
        platformName = '淘宝'
        clipboardData = detail.value?.spreadUrl
      }
      if (detail.value?.platform == 9) {
        platformName = '抖音'
        clipboardData = detail.value?.dyZlink
      }
      if (detail.value?.platform == 2) {
        platformName = '唯品会'
        clipboardData = detail.value?.destUrl
      }
      if (detail.value?.platform == 3) {
        platformName = '苏宁易购'
        clipboardData = detail.value?.productUrlWap
      }
      return uni.setClipboardData({
        data: clipboardData,
        success(res) {
          return uni.showToast({
            title: `链接已复制，去【${platformName}】打开即可。`,
            icon: 'none'
          })
        },
        fail(res) {
          return uni.showToast({
            title: '请更新隐私协议',
            icon: 'none'
          })
        }
      })*/

      // }
      return uni.showToast({
        title: '商品维护中，请稍后再试',
        icon: 'none'
      })
    }
  }
  /*
  if (detail.value?.platform == 3) {
  }

  if (detail.value?.platform == 9) {
    console.log(detail.value)
  }
  if (detail.value?.platform == 2) {
    console.log(detail.value)
  }*/

  onShareAppMessage(async () => {
    await uni.showLoading({
      title: '分享中',
      icon: 'none'
    })
    return await getShareId({ pid: state.id, type: 1 }).then(res => {
      if (res) {
        state.shareId = res.share_id
        uni.hideLoading()
        return {
          title: `${detail.value.title}`,
          path: `pages/store/product/detail?id=${detail.value.id}&from=share&shareID=${state.shareId}`
        }
      }
    }).catch(error => {
      uni.showToast({
        title: '请登录后分享',
        icon: 'none'
      }).then(() => {
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/user/login/index'
          })
        }, 500)
      })
      uni.hideLoading()
    })

  })

  onShareTimeline(() => {

    if (!userStore.uid) {
      return uni.showToast({
        title: '请登录后分享',
        icon: 'none'
      }).then(() => {
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/user/login/index'
          })
        }, 500)
      })
    }

    return {
      title: `${detail.value.store_name}`,
      imageUrl:  state.shareImage,
      query: `id=${state.id}&from=share&shareID=${state.shareId}`
    }

  })

}

/**
 * 有优惠券
 */
const hasCoupon = computed(() => {
  return detail.value?.coupon && detail.value?.coupon.startTime
})

// 距离顶部距离
let Scroll_X = ref(0)

const headerClass = ref('')
onPageScroll((page) => {
  // console.log('滚轮事件触发了',page.scrollTop.toFixed());
  
  // console.log(page.scrollTop.toFixed(),'距离顶部的距离')
  Scroll_X.value = Number(page.scrollTop.toFixed())
  if (page.scrollTop >= 76 ) {
    headerClass.value = 'bg-white !text-gray-900'
  } else {
    headerClass.value = ''
  }
})
</script>
<template>
  <CXBBasePage>
    <div class="relative w-screen " v-if="detail">
      <swiper
          v-if="detail.featured"
          :indicator-dots="false"
          :circular="true"
          :autoplay="true"
          :interval="5000"
          :duration="500"
          class="h-95"
      >
        <swiper-item
            v-for="(item, index) in detail.featured"
            :key="index"
        >
          <image
              :key="index"
              :src="item"
              mode="aspectFill" class="h-full w-full"
          />
        </swiper-item>
      </swiper>
      <CXBBackTop :Scroll_X="Scroll_X"/>
      <div>
        <div class="relative p-3 bg-white">
          <div class="flex gap-2 items-end">
            <FPrice v-if="detail && detail.salePrice" :price="detail.salePrice" need-symbol :size="'large'"
                    ex-class="!text-[24px]"/>
            <FPrice v-if="detail && detail.price" :price="detail.price" :ex-class="'!text-gray'" need-symbol
                    strike-through/>
          </div>

          <div class="font-bold py-2">{{ detail.title }}</div>
        </div>

        <div class="relative"
             v-if="hasCoupon"

        >
          <div
              class="px-3 relative"
              @tap="handleBuyNow"
          >
            <image :src="discount_coupon_bg_220804Image"
                   mode="widthFix"
                   class="w-full"
            ></image>
            <div class="absolute top-2 left-15 h-full w-fit text-white"
            >
              <div class=" inline-flex justify-center items-end w-full py-2">
                <div class="text-[28px]">{{ detail.coupon.amount }}</div>
                元代金劵
              </div>
              <div class="text-[10px]">使用期限：{{ detail.coupon.startTime }} -{{ detail.coupon.endTime }}</div>
            </div>
          </div>

        </div>

        <div class="relative pb-safe mt-3 bg-white">
          <div v-if="detail.mallName" class="p-3 font-bold">
            {{ detail.mallName }}
          </div>
          <!--          <mpHtml :content=""></mpHtml>-->
          <image v-for="(imgItem, index) in detail.images"
                 :key="index"
                 mode="widthFix"
                 :src="imgItem"
                 class="w-full h-full"
          ></image>
        </div>
      </div>
      <div class="fixed bottom-0  w-full h-15 shadow">
        <div class="w-full bg-white pb-safe">
          <div class="flex justify-between items-center p-3">
            <div class="inline-flex items-center">
              <div class="text-sm">预估养老金</div>
              <FPrice :price="detail.yanglao || detail.commission" need-symbol ex-class="text-[20px] font-bold"/>
            </div>
            <div>
              <nut-button type="primary" @tap="handleBuyNow" :disabled="isSubmit">
                立即购买
              </nut-button>
            </div>
          </div>
        </div>
      </div>
    </div>

  </CXBBasePage>
</template>

<route lang="yaml">
style:
  navigationBarTitleText: 商品详情
  enablePullDownRefresh: true
</route>