<template>
  <view class="cu-modal bottom-modal" :class="{ show: visible }">
      <view class="mask" @click="close"></view>
      <view class="wrapper cu-dialog">
          <view>
              <view class="title">
                  立即发货
                  <view class="close" @click="close">
                      <text class="cuIcon-close"></text>
                  </view>
              </view>
          </view>
          <view>
              <view class="paddingY10" v-if="goods2">
                  <scroll-view scroll-x class="scroll-wrapper" v-if="goods2.length > 4">
                      <view class="item" v-for="(goods, index) in goods2" :key="index">
                          <image
                              class="super-image translateX"
                              mode="aspectFit"
                              :src="goods.data.cover"
                          />
                          <view
                              class="bg-title bold"
                              :style="'background-image:url(' + ossurl.welfare.detail.numBg + ')'"
                          >
                              <text class="">x</text>
                              {{ goods.total }}
                          </view>
                      </view>
                  </scroll-view>
                  <view v-else class="flex-align-around">
                      <view class="item" v-for="(goods, index) in goods2" :key="index">
                          <image
                              class="super-image translateX"
                              mode="aspectFit"
                              :src="goods.data.cover"
                          />
                          <view
                              class="bg-title bold"
                              :style="'background-image:url(' + ossurl.welfare.detail.numBg + ')'"
                          >
                              <text class="">x</text>
                              {{ goods.total }}
                          </view>
                      </view>
                  </view>
              </view>
              <view v-if="expressAmount" class="flex-align paddingY8">
                  <view class="flex1 font4">运费</view>
                  <view class="font2 color-theme marginR5">¥{{ expressAmount }}</view>
              </view>
              <view v-if="expressAmount && cash && hide" class="flex-align paddingY8">
                  <view class="flex1 font4">
                      使用钱包支付
                      <text class="color-theme">(余额：¥{{ cash.balance }})</text>
                  </view>
                  <switch
                      class="purple"
                      :checked="cashChecked"
                      @change="changeCashChecked"
                  ></switch>
              </view>
              <view
                  class="flex-align-between paddingY10"
                  @click="$router.push('address', { type: 1 })"
              >
                  <text v-if="!address" class="font-8 bold">请填写收货地址</text>
                  <view v-else>
                      <view class="font4">{{ address.contactName }} {{ address.contactNo }}</view>
                      <view class="font3">
                          {{ address.province }}{{ address.city }}{{ address.district
                          }}{{ address.address }}
                      </view>
                  </view>
                  <text class="cuIcon-right font4 marginL5"></text>
              </view>
          </view>
          <cm-button ::height="44" @click="pay()">确定发货</cm-button>
          <view class="fill"></view>
      </view>
  </view>
</template>

<script>
  import cmButton from '../../components/cm-button.vue'
  import { throttle } from '@/utils'
  import { LEVEL_MAP } from '@/utils/config'
  import ossurl from '@/utils/ossurl'
  import { baseEncode } from '../../utils/utils'
  export default {
      components: { cmButton },
      data() {
          return {
              ossurl,
              LEVEL_MAP,
              visible: false,
              address: null,
              expressAmount: null,
              goods2: [],
              cash: null,
              cashChecked: false
          }
      },
      computed: {
          payInfo() {
              return this.$store.state.payInfo
          }
      },
      watch: {
          payInfo(val) {
              if (val && val.payResult == 'SUCCESS') {
                  this.paySuccess(val)
              } else if (val && val.payResult !== 'SUCCESS') {
              }
          }
      },
      mounted() {
          this.$event.on(this.$event.key.ADDRESS_SET, (data) => {
              this.address = data
          })
          this.getAddress()
      },
      beforeDestroy() {
          this.$event.off(this.$event.key.ADDRESS_SET)
      },
      computed: {
          hide() {
              return !this.$store.state.hide
          }
      },
      methods: {
          async getAddress() {
              const res = await this.$service.address.default()
              this.address = res
          },
          show(data = {}, goods) {
              this.generateGoods2(goods)
              this.expressAmount = data.expressAmount || 0
              if (data.cash && data.cash.balance > data.expressAmount) {
                  this.cash = data.cash
                  this.cashChecked = true
              } else {
                  this.cash = null
                  this.cashChecked = false
              }
              this.visible = true
          },
          generateGoods2(goods) {
              this.goods = goods
              let goodsMap = {}
              goods.forEach((item) => {
                  let key = item.spuId + '_' + item.level
                  let obj = goodsMap[key]
                  if (obj) {
                      goodsMap[key] = {
                          total: obj.total + 1,
                          data: obj.data
                      }
                  } else {
                      goodsMap[key] = {
                          total: 1,
                          data: item
                      }
                  }
              })
              this.goods2 = Object.values(goodsMap)
          },
          close() {
              this.visible = false
              this.$emit('close', false)
          },
          changeCashChecked(e) {
              this.cashChecked = e.detail.value
          },
          async pay() {
              if (!this.address) {
                  this.$message.warn('请选择地址')
                  return
              }
              this.realPay()
          },
          async realPay() {
              const ids = this.goods.map((item) => item.id)
              const res = await this.$service.award.takeApply(ids, this.address.id,'ALIPAY_APP')
              //判断是否是微信支付
              if (res) {
                  if (res.paySuccess) {
                      this.close()
                      this.$emit('success')
                      return
                  }
                  let self = this
                  // 支付宝支付
                  uni.requestPayment({
                      provider: 'alipay',
                      orderInfo: res.payInfo,
                      success: function (res) {
                          self.close()
                          self.$emit('success')
                      },
                      fail: function (err) {
                          console.log('fail:' + JSON.stringify(err));
                      }
                  });
              }
          },
          wechatPay(data) {
              let payInfo = data.payInfo
              wx.requestPayment({
                  timeStamp: payInfo.timeStamp,
                  nonceStr: payInfo.nonceStr,
                  package: payInfo.packageValue,
                  signType: payInfo.signType,
                  paySign: payInfo.paySign,
                  success: (res) => {
                      this.close()
                      this.$emit('success')
                  },
                  fail: (res) => {}
              })
          },
          thirdPay(data) {
              let self = this
              let redirectUrl = data.redirectUrl
              let requestId = data.requestId
              const base64Url = encodeURIComponent(baseEncode(redirectUrl))
              wx.openEmbeddedMiniProgram({
                  path: 'pages/pay/order', // 启动目标页面
                  appId: 'wx0448557563ffc600', // 启动的小程序
                  envVersion: 'release', // develop | trial | release
                  verify: 'binding',
                  extraData: {
                      title: '订单付款', // 导航Title
                      tip: `待支付订单付款`, // 支付提示内容
                      requestId: requestId, // 本次请求ID
                      action: 'epPay', // 支付模式
                      payUrl: base64Url // 支付地址, 需要进行Base64转换
                  },
                  success: (res) => {
                      console.info('启动成功', res)
                  },
                  fail: (err) => {
                      console.info('启动失败', err)
                  }
              })
          },
          paySuccess(payInfo) {
              this.close()
              this.$emit('success')
              this.$store.state.payInfo = null
          }
      }
  }
</script>

<style lang="scss" scoped>
  .mask {
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
  }
  .wrapper {
      padding: 0 28rpx;
      background: #fff;
      border-radius: 15px 15px 2px 2px !important;
      .title {
          text-align: center;
          font-size: 32rpx;
          font-family: Source Han Sans, Source Han Sans;
          font-weight: 700;
          color: #000000;
          padding: 44rpx 0 10rpx 0;
          position: relative;
      }

      .close {
          position: absolute;
          right: 0;
          width: 48rpx;
          height: 48rpx;
          background: #ebebeb;
          border-radius: 48rpx;
          color: #a2a2a2;
          top: 30rpx;
          line-height: 48rpx;
      }
      .fill {
          height: 50rpx;
      }
  }
  .scroll-wrapper {
      padding-left: 28rpx;
      overflow: hidden;
      height: 182rpx;
      white-space: nowrap;
      width: 100%;
      .item {
          display: inline-block;
          margin-right: 8rpx;
      }
  }
  .item {
      width: 158rpx;
      height: 206rpx;
      background: #ffffff;
      border-radius: 12rpx 12rpx 12rpx 12rpx;
      opacity: 1;
      border: 2rpx solid #eaeaea;
      position: relative;
      .super {
          position: absolute;
          z-index: 0;
          left: 0;
          top: 0;
          width: 120rpx;
          height: 182rpx;
      }
      .super-image {
          width: 146rpx;
          height: 170rpx;
      }
      .bg-title {
          width: 36rpx;
          height: 32rpx;
          background-size: 100% 100%;
          font-size: 20rpx;
          font-family: Arial, Arial;
          font-weight: 400;
          color: #ffffff;
          line-height: 32rpx;
          text-align: center;
          position: absolute;
          right: 0;
          top: 0;
      }
  }
</style>
