<template>
  <view class="member-content">
    <scroll-view class="sheet-content" :scroll-y="true" @scroll="handleContentScroll">
      <!-- 导航栏  :leftIconColor="!isTop ? '#fff' : '#000'"-->
      <!-- <u-navbar :placeholder="true" autoBack>
        <view slot="center">
          <view class="center navbar-title" style="background-color: #fff;">商品详情</view>
        </view>
      </u-navbar> -->
      <!-- 主图 -->
      <view class="mainImame">
        <ImageItem :src="$globalData.publicUrl + params.productMainImage" />
      </view>
      <view class="content">
        <!-- 第一行text -->
        <view class="firstRow">
          <text v-if="selectedObj" class="priceClass">
            {{ params.paymentType == 1 ? selectedObj.pricePoint + '积分' :
              params.paymentType == 2 ? selectedObj.priceMoney + '元' :
                params.paymentType == 3 ? selectedObj.priceMoney + '元' + '+' +
                  selectedObj.pricePoint + '积分' : null }}
          </text>
          <text v-else class="priceClass">
            {{ params.paymentType == 1 ? params.pricePoint + '积分' :
              params.paymentType == 2 ? params.priceMoney + '元' :
                params.paymentType == 3 ? params.priceMoney + '元' + '+' +
                  params.pricePoint + '积分' : null }}
          </text>
          <text class="deletePriceClass">{{ selectedObj ? selectedObj.originPrice : params.specComboVOList ?
            params.specComboVOList[0].originPrice : null }}元</text>
          <view class="productName"> {{ params.name }}</view>
          <view class="discribeClass">{{ params.summary }}</view>
          <view class="serviceClass">
            <view v-for="(item,index) in servicePromiseArr" :key="index">
              <view style="display: flex;align-items: center;" v-if="item.isShow">
                <ImageItem style="width: 24rpx;height: 24rpx;margin-right: 4rpx;" :src="item.icon" />
                <view style="margin-right: 24rpx;">{{ item.name }}</view>
              </view>
            </view>
          </view>

        </view>
        <!-- 第二行text -->
        <view class="seconedRow">
          <view class="specClass">
            <view style="display: flex;align-items: center;justify-content: space-between;width: 100%;">
              <view style="display: flex;align-items: center;">
                <text style="color: #666666;">规格</text>
                <image v-if="selectedObj" class="imgClass" :src="$globalData.publicUrl + selectedObj.image"
                  mode="heightFix">
                </image>
              </view>
              <view style="display: flex;align-items: center;position: relative;" @click="selectProductShowFun">
                <text v-if="selectedObj" style="color: #666666;margin-right: 35rpx;">
                  已选：{{ selectedObj.specValueText }}</text>
                <text v-else style="color: #999;margin-right: 35rpx;">选择商品</text>
                <span style="position: absolute;right: 0;top: -5rpx;">
                  <image style="height: 35rpx;width: 35rpx;" src="@/static/points/Keyboard_arrow_rifht.png" mode="">
                  </image>
                </span>
              </view>
            </view>

          </view>
          <view class="arriveAddressClass">
            <text style="color: #666666;margin-right: 24rpx;">送至</text>
            <view style="width: 80%; white-space:nowrap; overflow: hidden; text-overflow: ellipsis;"
              @click="addressSelectFun">
              <text v-if="defaultAddress">
                {{ defaultAddress.address + defaultAddress.atlasAdd }}</text>

              <text v-else style="color: #999;position: absolute;right: 35rpx;top:0">添加收货地址</text>
              <span style="position: absolute;right: 0;top: -5rpx;">
                <image style="width: 35rpx;height: 35rpx;" src="@/static/points/Keyboard_arrow_rifht.png" mode="">
                </image>
              </span>
            </view>

          </view>
          <view class="seedAddressClass">
            <text style="color: #666666;margin-right: 24rpx;">发货</text>
            <text>山西省太原市小店区
              <text v-if="params.freight != undefined"> | {{ params.freight == 0 ? '免运费' : '运费' + params.freight + '元'
              }}</text>
            </text>
          </view>
          <view class="promiseSeedTime" style="margin-left: 80rpx;">
            下单后{{ params.deliveryTime }}小时内发货
          </view>

        </view>
        <!-- 第三行商品详情 -->
        <view class="produceDateil">
          <view style="font-weight: 800;font-size: 32rpx;color: #333333;">商品详情</view>
          <view v-for="(img,index) in params.productImage" :key="index" style="margin-top: 20rpx;">
            <image style="width: 100%;" :src="$globalData.publicUrl + img" mode="widthFix"></image>
          </view>

        </view>
        <!-- 兑换须知 -->
        <view class="niticeClass">
          <view class="title">
            兑换须知
            <span style="position: absolute;right: 24rpx;">
              <!-- <image style="width: 28rpx;height: 28rpx;" @click="clichFun"
                src="@/static/points/Keyboard_arrow_rifht.png" mode=""></image> -->
            </span>
          </view>
          <view class="text" style="-webkit-line-clamp: 8;">
            1、会员可凭上述积分兑换“广誉源会员定制玻璃杯”一个； <br>
            2、双层曲线杯身在隔热防烫的同时，让您的手掌体验一次美妙的抓握感； <br>
            3、积分兑换商品不支持质量问题外的退换货服务，请您先确认后签收；<br>
            4、积分商城仅支持中国大陆地区的兑换邮寄服务，我们将在10个工作日内寄出；<br>
          </view>
        </view>
        <!-- 平台须知 -->
        <view class="niticeClass" style="margin-bottom: 30rpx;">
          <view class="title">平台说明

            <span style="position: absolute;right: 24rpx;">
              <!-- <image style="width: 28rpx;height: 28rpx;" @click="clichFun"
                src="@/static/points/Keyboard_arrow_rifht.png" mode=""></image> -->
            </span>

          </view>
          <view class="text">
            价格说明：划线价格：商品的专柜价、吊牌价、正品零售价、厂商指导价，并非原价，仅供参考未划线价格：商品的实时标价，不因表述的差异改变性质。具体成交价格根据商品参加活动、或会员优惠、积分等发生变化，最终以订单结算页价格为准。
          </view>
        </view>
      </view>

      <view class="footer-bar">
        <u-button :disabled="redeemNowBtnDisable" v-if="selectedObj ? selectedObj.stock : params.stock" :customStyle="{
          color: '#fff',
          background: '#03C1B8'
        }" @click="selectProductShowFun">{{ redeemNowBtnDisable ? '支付中...' : '立即兑换' }}</u-button>
        <u-button v-else :customStyle="{
          color: '#999999 ',
          background: '#eee'
        }">库存不足</u-button>
      </view>

      <u-popup :show="redemptionRulesShowPopup" mode="bottom" @close="redemptionRulesShowPopup = false" round="20">
        <RedemptionRules ref="redemptionRulesRef"></RedemptionRules>
      </u-popup>
      <u-popup :z-index="999" :show="selectProductShowPopup" mode="bottom" round="10">
        <SelectProduct :redeemNowBtnDisable="redeemNowBtnDisable" :params="params" ref="selectProductRef"
          :defaultAddress="defaultAddress" @redeemNowFun="redeemNowFun" @getAddrListFun="getAddrListFun"
          @closeSelectProduct="closeSelectProduct">
        </SelectProduct>
      </u-popup>

    </scroll-view>




  </view>
</template>

<script>
import wx from 'weixin-js-sdk';
import { h5Url } from '@/common/config.js';
import ImageItem from "@/components/swiper/components/image.vue";
import RedemptionRules from "./components/redemptionRules.vue";
import SelectProduct from "./components/selectProduct.vue";
import { productGetById } from '@/api/points'
import { productOrderCreate, productOrderPay } from '@/api/pointOrder'
import { getAddrList, } from '@/api/address';
import { getInfo, getSignature } from '@/api/index.js';
//paymentType 商品的付款类型 付款类型（1：积分 2：金额 3：积分+金额）

//订单状态(0：待付款 1：待发货 2：待收货 3：已收货 4：售后中  11：取消订单)

//售后状态(0:待审核 1：退款完成 2:等待用户寄回  3:等待商家收货 4:等待商家寄出  5:订单完成 6:取消售后)

export default {
  components: { ImageItem, RedemptionRules, SelectProduct },
  data() {
    return {
      redeemNowBtnDisable: false,
      isTop: 0,
      redemptionRulesShowPopup: false,
      selectProductShowPopup: false,
      params: {},
      servicePromiseArr: [
        { name: '放心购', icon: '/static/points/Group4.png', isShow: false },
        { name: '假一赔三', icon: '/static/points/Group6.png', isShow: false },
        { name: '7天无理由退换', icon: '/static/points/Group2.png', isShow: false },
        { name: '破损包退换', icon: '/static/points/return7.png', isShow: false },
      ],
      selectedObj: null,
      defaultAddress: null,
      selectPayMeth: null, //1 微信支付 2 余额
      orderRemarks: null,
      addressList: [],
      dBalance: 0.00,
      wxconfig: {},
      orderNo: null,
      isGetAddrListFunLoaded: false,


    }
  },
  onLoad(data) {
    console.log(data, 'onLoad66666')
    if (data.selectedAddressId) this.selectedAddressId = data.selectedAddressId
    if (data.id) {
      this.productGetByIdFun(data.id)
      this.getAddrListFun()
      this.isGetAddrListFunLoaded = true
      this.getinfo()
    }

  },
  onShow(onShow) {
    console.log(onShow, this.isGetAddrListFunLoaded, 'onShow55555')
    if (!this.isGetAddrListFunLoaded) {
      this.getAddrListFun()
    } else {
      this.isGetAddrListFunLoaded = false
    }


  },
  onPageScroll(e) {
    //console.log("滚动距离为：" + e.scrollTop);
    this.isTop = e.scrollTop;
  },

  methods: {
    handleContentScroll(e) {
      this.isTop = e.detail.scrollTop > 0
    },

    //账户余额
    getinfo() {
      getInfo().then(res => {
        if (res.data.code == 200) {
          this.dBalance = res.data.data.dBalance.toFixed(2)
        }
      })
    },
    //查询默认地址
    getAddrListFun() {
      let params = {
        current: 1,
        size: 100,
        openId: uni.getStorageSync('wx_copenid'),
      }
      getAddrList(params).then(res => {
        if (res.data.code === 200) {
          if (!res.data.data.length) {
            this.defaultAddress = null
            return
          }

          if (this.selectedAddressId) {
            let flag = res.data.data.some(item => {
              return item.id == this.selectedAddressId
            });
            if (flag) {
              let defaultAddress = res.data.data.find(item => {
                if (item.id == this.selectedAddressId)
                  return item
              });
              this.$set(this, 'defaultAddress', defaultAddress);
            } else {
              this.defaultAddress = res.data.data[0]
            }
            return
          }
          if (!this.selectedAddressId || !this.defaultAddress) {
            let flag = res.data.data.some(item => {
              return item.type == 1
            });
            if (flag) {
              this.defaultAddress = res.data.data.find(item => {
                if (item.type == 1)
                  return item
              });
            } else {
              this.defaultAddress = res.data.data[0]
            }
          }
        }
      });
    },

    //查询商品详情
    productGetByIdFun(id) {
      productGetById({ id: id }).then(res => {
        if (res.data.code === 200) {
          this.params = Object.assign({}, res.data.data)
          //this.selectedObj = this.params.specComboVOList[0]
          this.servicePromiseArr.forEach(element => {
            this.params.servicePromise.map(m => {
              if (m == element.name) {
                element.isShow = true
              }
            })

          });

        }

      })

    },
    //兑换须知页面
    clichFun() {
      this.redemptionRulesShowPopup = true
    },
    //立即兑换
    redeemNowFun(selectedObj, selectPayMeth, orderRemarks, redeemNowBtnDisable) {
      if (selectedObj) this.selectedObj = selectedObj
      if (selectPayMeth) this.selectPayMeth = selectPayMeth
      if (orderRemarks) this.orderRemarks = orderRemarks

      if (!this.defaultAddress) {
        uni.showToast({
          title: '请选择添加地址',
          icon: 'none'
        })
        return
      }
      if (this.selectPayMeth == null && (params.paymentType !== 1 || this.params.freight > 0)) {
        uni.showToast({
          title: '请选择支付方式',
          icon: 'none'
        })
        return
      }

      this.selectProductShowPopup = true
      this.$nextTick(() => {
        this.$refs.selectProductRef.onShowFun(this.selectedObj, this.orderRemarks, this.selectPayMeth)
      });

      this.redeemNowBtnDisable = redeemNowBtnDisable ? redeemNowBtnDisable : true
      let params = {}
      //params.openId = uni.getStorageSync('wx_copenid');//用户openId
      params.userPhone = this.defaultAddress.phone;//用户手机号
      params.userName = this.defaultAddress.userName;//用户名
      params.userAddress = this.defaultAddress.address + this.defaultAddress.atlasAdd;//地图地址+详细地址
      //params.addressId = this.defaultAddress.id;//地址ID
      params.productId = this.params.id;
      params.name = this.params.name;
      params.productMainImage = this.params.productMainImage;
      params.skuId = this.selectedObj.skuId; //选中的SKU ID
      params.specNameValueList = this.selectedObj.specNameValueList; // SKU列表（规格组合明细）
      params.quantity = 1; //购买数量
      params.payType = this.params.paymentType == 1 ? 3 : Number(this.selectPayMeth);//支付方式：1微信支付 2账户余额
      params.freightAmount = this.params.freight; //运费
      params.totalAmount = (this.selectedObj.priceMoney + (this.params.freight > 0 ? this.params.freight : 0));// 支付金额+运费=总金额
      params.payAmount = this.selectedObj.priceMoney;// 支付金额
      params.pointsUsed = this.selectedObj.pricePoint;// 使用的积分
      params.buyerRemark = this.orderRemarks;//买家备注信息
      if (this.params.paymentType == 1 && this.params.freight == 0) {//只有积分兑换
        this.productOrderCreateFun(params)
        return
      }
      if (this.selectPayMeth == 1) {
        //微信支付
        this.weixinPay(params)
      } else if (this.selectPayMeth == 2) {
        //余额支付
        this.nowYuyue(params)
      }

    },
    //微信支付
    async weixinPay(params) {
      let data = await this.productOrderCreateFun(params)
      if (!data) return
      let payConfig = JSON.parse(data.data)
      getSignature(h5Url).then(res => {
        this.wxconfig = res.data
        wx.config({
          beta: true,
          debug: false,
          appId: this.wxconfig.appId, // 公众号ID
          // appId: uni.getAppBaseInfo().host.appId, // 公众号ID
          timestamp: this.wxconfig.timestamp, // 时间戳，自1970年以来的秒数
          nonceStr: this.wxconfig.nonceStr, // 随机串
          signature: this.wxconfig.signature, // 微信签名方式
          jsApiList: ['getBrandWCPayRequest']
        });
        var vm = this
        wx.invoke('getBrandWCPayRequest',
          // 下面参数内容都是后台返回的
          {
            'appId': payConfig.appId, // 公众号名称，由商户传入
            'timeStamp': payConfig.timeStamp, // 时间戳
            'nonceStr': payConfig.nonceStr, // 随机串
            'package': payConfig.package, // 预支付id
            'signType': payConfig.signType, // 微信签名方式
            'paySign': payConfig.paySign, // 微信签名
          },
          function (res) {
            console.log(res, '---------------付款')
            vm.redeemNowBtnDisable = false
            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。

            // JSON.stringify(res);
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              uni.navigateTo({
                url: '/points/productDetails/paymentSuccessful?orderNo=' + vm.orderNo
              });
            } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
              uni.showToast({
                title: '已取消支付',
                icon: 'none'
              })
              uni.navigateTo({
                url: '/points/productDetails/pendingPayment?orderNo=' + vm.orderNo
              });


            } else {
              vm.redeemNowBtnDisable = false
              alert('付款失败');
            }
          }
        )

      }).catch(err => {
        this.redeemNowBtnDisable = false
        uni.showToast({
          title: err,
          icon: 'none'
        })

      })
    },
    //账号余额支付
    async nowYuyue(params) {
      if (parseFloat(this.dBalance) < parseFloat(this.selectedObj.priceMoney)) {
        this.redeemNowBtnDisable = false
        uni.showModal({
          title: '账户余额不足',
          content: '请充值',
          success: function (res) {
            if (res.confirm) {
              uni.navigateTo({
                url: '../../pages/my/pay?name=充值'
              })
            } else if (res.cancel) { }
          }
        });
      } else {
        let data = await this.productOrderCreateFun(params)
        if (!data) return
        this.redeemNowBtnDisable = false
        uni.navigateTo({
          url: '/points/productDetails/paymentSuccessful?orderNo=' + this.orderNo
        });

      }
    },
    //支付api
    async productOrderCreateFun(params) {
      let res = await productOrderCreate(params)
      if (res.data.code == 200) {
        this.orderNo = res.data.data
        let res1 = await productOrderPay({
          orderNo: res.data.data, //订单编号
          payType: params.payType, //支付方式:1微信支付 2:余额支付
          totalPrice: params.totalAmount //订单总金额，单位：元
        })
        if (res1.data.code == 200) {
          return res1.data
        } else {
          this.redeemNowBtnDisable = false
          uni.showToast({
            title: res1.data.msg,
            icon: 'none'
          })
        }

      } else {
        this.redeemNowBtnDisable = false
        uni.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }



    },

    //打开选择商品页
    selectProductShowFun() {
      this.selectProductShowPopup = true
      this.$nextTick(() => {
        this.$refs.selectProductRef.onShowFun(this.selectedObj, this.orderRemarks, this.selectPayMeth)
      });
    },
    //关闭选择商品页
    closeSelectProduct(selectedObj, selectPayMeth, orderRemarks) {
      if (selectedObj) this.selectedObj = selectedObj
      if (selectPayMeth) this.selectPayMeth = selectPayMeth
      if (orderRemarks) this.orderRemarks = orderRemarks
      this.selectProductShowPopup = false
    },
    //去我的地址页面 /points/productDetails/addressManagement
    addressSelectFun() {
      uni.navigateTo({
        url: `/pages/address/index?selectedAddressId=${this.defaultAddress ? this.defaultAddress.id : null}&productId=${this.params.id}`
      });
    },

  }
}
</script>

<style></style>
<style lang="scss" scoped>
.mainImame {
  height: 456rpx;
}

::v-deep .u-popup {

  .u-transition,
  .u-fade-enter-to,
  .u-fade-enter-active {
    z-index: 999 !important;
  }
}

.footer-bar {
  .u-button {
    height: 84rpx;
    border-radius: 98rpx 98rpx 98rpx 98rpx;
    margin: 20rpx 40rpx;
    font-weight: bold;
    font-size: 32rpx;
    line-height: 36rpx;
    text-align: center;
    font-style: normal;
    text-transform: none;

  }
}

.content {
  background-color: #F5F8F8;
  padding: 24rpx 32rpx 0 32rpx;
  font-family: PingFang SC, PingFang SC;
  margin-bottom: 150rpx;
  border: 1px solid rgb(255, 255, 255);

  .firstRow {
    background-color: #fff;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    padding: 26rpx 24rpx 24rpx 24rpx;

    .priceClass {
      font-weight: 500;
      font-size: 40rpx;
      color: #F53E54;
      line-height: 40rpx;
      text-align: left;
      font-style: normal;
      text-transform: none
    }

    .deletePriceClass {
      margin-left: 24rpx;
      width: 90rpx;
      height: 32rpx;
      font-weight: 500;
      font-size: 32rpx;
      color: #999999;
      line-height: 32rpx;
      text-align: left;
      font-style: normal;
      text-decoration-line: line-through;
      text-transform: none;
    }

    .productName {
      margin-top: 22rpx;
      width: 638rpx;
      font-weight: bold;
      font-size: 36rpx;
      color: #333333;
      line-height: 44rpx;
      text-align: left;
      font-style: normal;
      text-transform: none;
    }

    .discribeClass {
      margin-top: 12rpx;
      line-height: 28rpx;
      font-weight: 500;
      font-size: 28rpx;
      color: #999999;
      line-height: 32rpx;
      text-align: left;
      font-style: normal;
      text-transform: none;
    }

    .serviceClass {
      margin-top: 24rpx;
      height: 24rpx;
      font-weight: 500;
      font-size: 24rpx;
      color: #666666;
      line-height: 24rpx;
      text-align: left;
      font-style: normal;
      text-transform: none;
      display: flex;
      align-items: center;
    }


  }

  .seconedRow {
    background: #FFFFFF;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    margin-top: 24rpx;
    padding: 24rpx;
    font-weight: 500;
    font-size: 28rpx;
    color: #333333;
    line-height: 28rpx;
    text-align: left;
    font-style: normal;
    text-transform: none;

    .specClass {
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;

      .imgClass {
        width: 64rpx;
        height: 64rpx;
        background: #D9D9D9;
        border-radius: 8rpx 8rpx 8rpx 8rpx;
        margin-left: 24rpx;

      }
    }

    .arriveAddressClass {
      margin-top: 32rpx;
      position: relative;
      display: flex;
      align-items: center;
    }

    .addressTextClass {
      margin-top: 32rpx;
    }

    .seedAddressClass {
      margin-top: 32rpx;
    }

    .promiseSeedTime {
      margin-top: 24rpx;
    }
  }

  .produceDateil {
    background: #FFFFFF;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    margin-top: 24rpx;
    padding: 24rpx;
  }

  .niticeClass {
    background: #FFFFFF;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    margin-top: 24rpx;
    padding: 24rpx;
    position: relative;

    .title {
      font-weight: 800;
      font-size: 32rpx;
      color: #333333;
      line-height: 32rpx;
      text-align: left;
      font-style: normal;
      text-transform: none;
      width: 686rpx;

    }

    .text {
      margin-top: 24rpx;
      font-weight: 500;
      font-size: 28rpx;
      color: #999999;
      line-height: 36rpx;
      text-align: left;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 5;
      /* 这里控制显示几行 */
      -webkit-box-orient: vertical;
      word-break: break-all;
      /* 长数字/英文自动换行 */

    }
  }
}

.popupClass {
  background-color: #F5F8F8;
  padding: 24rpx 32rpx 0 32rpx;
  font-family: PingFang SC, PingFang SC;

  .niticeClass {
    background: #FFFFFF;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    margin-top: 24rpx;
    padding: 24rpx;
    position: relative;

    .title {
      font-weight: 800;
      font-size: 28rpx;
      color: #333333;
      line-height: 28rpx;
      text-align: left;
      font-style: normal;
      text-transform: none;
      width: 686rpx;
      margin: 24rpx 0;
    }

    .text {
      color: #999999;
    }
  }
}
</style>
