<template>
  <view :style="viewColor">
    <view class='order-submission'>
      <!-- 商品信息 -->
      <view class="storeinfo-wrapper">
        <view class="store-item">
          <view class="store-title">
            <text class="iconfont icon-shangjiadingdan"></text>
            <view class="txt" @click="goStore(item.mer_id)">{{payForm.merName}}</view>
            <text class="iconfont icon-xiangyou"></text>
          </view>

          <view class="product-item">
            <view class="img-box">
              <image src="https://lihai001.oss-cn-chengdu.aliyuncs.com/def/89ad3202402292014108303.jpg" width="170rpx"
                height="180rpx" />
            </view>
            <view class="content event_content">
              <view class="name line1">
                {{payForm.money}}元实物提货券
              </view>
              <view style="margin-top: 30rpx;color: #FF5C2D;">
                ¥{{payForm.money}}
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class='wrapper'>
        <view class='item'>
          <view style="font-weight: bold;">支付方式</view>
          <view class='list'>
            <!-- #ifdef H5 -->
            <view class='payItem acea-row row-middle' :class='active==index ?"on":""' @tap='payItem(index)'
              v-for="(item,index) in cartArr" :key='index' v-if="item.payStatus==1">
              <view class='name acea-row row-center-wrapper'>
                <view class='iconfont animated'
                  :class='(item.icon) + " " + (animated==true&&active==index ?"bounceIn":"")'></view>
                {{item.name}}
              </view>
              <view class='tip'>
                {{item.title}}
                <block v-if="item.value == 'balance'">
                  {{userInfo.now_money}}
                </block>
                <block v-else-if="item.value == 'merBalance'">
                  {{moneyInfo.extract_money}}
                </block>
              </view>
            </view>
            <!-- #endif -->
            <!-- #ifdef MP || APP-PLUS -->
            <view class='payItem acea-row row-middle' :class='active==index ?"on":""' @tap='payItem(index)'
              v-for="(item,index) in cartArr" :key='index' v-if="item.payStatus==1">
              <view class='name acea-row row-center-wrapper'>
                <view class='iconfont animated'
                  :class='(item.icon) + " " + (animated==true&&active==index ?"bounceIn":"")'></view>
                {{item.name}}
              </view>
              <view class='tip'>
                {{item.title}}
                <block v-if="item.value == 'balance'">
                  {{userInfo.now_money}}
                </block>
                <block v-else-if="item.value == 'merBalance'">
                  {{moneyInfo.extract_money}}
                </block>
              </view>
            </view>
            <!-- #endif -->
          </view>
        </view>
      </view>

      <view class='moneyList'>
        <view class='item acea-row row-between-wrapper'>
          <view>商品总价:</view>
          <view class='money'>¥{{payForm.money}}</view>
        </view>

        <view class='item acea-row row-between-wrapper'>
          <view>补贴抵扣</view>
          <block v-if="platformConsumption.length > 0" >
            <view class='discount money red_packet' @click="couponTap3()">
              <text v-if="consumption_id">-¥{{consumption_money||'0.00'}}</text>
              <text v-else>有补贴补贴未选</text>
              <text class='iconfont icon-jiantou'></text>
            </view>
          </block>
          <block v-else>
            <view class='discount'>暂无抵扣红包</view>
          </block>
        </view>
      </view>
      <view style='height:140rpx;'></view>

      <view class='footer acea-row row-between-wrapper'>
        <view class="footer_count">
          <view>
            合计:
            <text class='pColor' v-if="cartArr[4].payStatus == 1 && active == 4">¥0.00</text>
            <text class='pColor' v-else>¥{{ total_coupon }}</text>
          </view>
        </view>
        <view class='settlement' :class='couponData.status != "noAddress" ? "" : "disabled"' style='z-index:100'
          @tap="SubOrder">{{couponData.status != "noAddress" ? '提交订单':'选择地址'}}</view>
      </view>
    </view>
  </view>
</template>
<script>
  // +----------------------------------------------------------------------
  // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  // +----------------------------------------------------------------------
  // | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
  // +----------------------------------------------------------------------
  // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  // +----------------------------------------------------------------------
  // | Author: CRMEB Team <admin@crmeb.com>
  // +----------------------------------------------------------------------
  let app = getApp();
  import {
    orderConfirm,
    createOrder
  } from '@/api/order.js';
  import {
    getUserInfo,
    getAdminApplyAPI
  } from '@/api/user.js';
  import {
    openPaySubscribe
  } from '@/utils/SubscribeMessage.js';
  import {
    mapGetters
  } from "vuex";
  import {
    configMap
  } from '@/utils';
  import {
    orderPay,
    orderCheck
  } from "@/api/payment.js";

  export default {
    data() {
      return {
        platformConsumption: [],
        //支付方式
        cartArr: [{
            "name": "微信支付",
            "icon": "icon-weixin2",
            value: 'weixin',
            title: '微信快捷支付',
            payStatus: 1,
          },
          {
            name: "支付宝支付",
            icon: "icon-icon34",
            // #ifdef H5 || APP-PLUS
            value: 'alipay',
            // #endif
            // #ifdef MP
            value: 'alipayQr',
            // #endif
            title: '支付宝支付',
            payStatus: this.$store.getters.globalData.alipay_open
          },
          {
            "name": "余额支付",
            "icon": "icon-icon-test",
            value: 'balance',
            title: '可用余额:',
            payStatus: this.$store.getters.globalData.yue_pay_status,
          },
          {
            "name": "商户余额",
            "icon": "icon-icon-test",
            value: 'merBalance',
            title: '可用余额:',
            payStatus: this.$store.getters.globalData.yue_pay_status,
          },
          {
            "name": "线下支付",
            "icon": "icon-yinhangqia",
            value: 'offline',
            title: '线下支付',
            payStatus: 2,
          }, {
            "name": "先货后款",
            "icon": "tan-a-lujing17324",
            value: 'creditBuy',
            title: `结算周期:${this.settle_cycle}天 日利率:${this.interest_rate}%`,
            payStatus: '',
          },
        ],
        tagStyle: {
          img: 'width:100%;display:block;',
          video: 'width:100%;'
        },
        radioList: [{
          title: this.deliveryName,
          check: true
        }, {
          title: '到店核销',
          check: false
        }],
        payType: 'weixin', //支付方式
        active: 0, //支付方式切换
        address: {
          address: false
        }, //地址组件
        couponId: 0, //优惠券id
        cartId: '', //购物车id
        userInfo: {}, //用户信息
        moneyInfo: {}, //商户余额信息
        coupon_price: 0, //优惠券抵扣金额
        ChangePrice: 0, //使用积分抵扣变动后的金额
        formIds: [], //收集formid
        status: 0,
        is_address: false,
        toPay: false, //修复进入支付时页面隐藏从新刷新页面
        cartInfo: [],
        priceGroup: {},
        animated: false,
        totalPrice: 0,
        offlinePostage: "",

        from: '',
        orderStatus: '', //是否有地址
        couponIndex: 0, //选择商铺优惠券索引
        subCoupon: {}, //提交订单使用的优惠券
        couponData: {},
        orderPay: false,
        pics: [],
        extend: [],
        virtualIndex: 0,
        platformCoupon: [],
        total_platform_coupon_price: 0,
        enabledPlatformCoupon: false,
        plantCoupon: false,
        order_key: '',
        product_type: '',
        source: null,
        settle_cycle: '', // 周期
        type_id: '', //店铺类型
        consumption_id: '', //补贴id
        consumption_money: '', //补贴抵扣金额
        total_coupon: '', //合计
        payForm: {
          cart_id: '',
          address_id: '',
          consumption_id: '',
          use_coupon: '',
          takes: '',
          use_integral: '',
          receipt_data: [],
          mark: '',
          pay_type: '',
          money: '',
          merName: '',
          return_url: ''
        },
        checkForm: {
        	address_id: '',
        	cart_id: [],
        	consumption_id: '',
        	product_type: 0,
        	source: 999,
        	takes: [],
        	use_coupon: {},
        	use_integral: false
        },
      };
    },
    computed: {
      ...mapGetters(['isLogin', 'viewColor']),
      ...configMap(['hide_mer_status', 'yue_pay_status']),
    },
    watch: {
      yue_pay_status(n) {
        this.payMode[2].payStatus = n
      }
    },
    onLoad: function(options) {
      options.money = parseFloat(options.money).toFixed(2);
      this.payForm.cart_id = options.cartId;
      this.payForm.money = options.money;
      this.payForm.merName = options.merName;
      this.checkForm.cart_id = options.cartId.split(',');
      this.total_coupon = options.money;
      
      // this.platformConsumption = [{
      //   balance: "39000.00",
      //   coupon_price: "50000.00",
      //   coupon_title: "春耕采购余额",
      //   coupon_user_id: 178,
      //   describe: "仅限平台指定商家商品可使用",
      //   end_time: "2025-07-01 00:00:00",
      //   start_time: "2024-03-02 14:15:17",
      //   uid: 889
      // }]

      const eventChannel = this.getOpenerEventChannel();
      eventChannel.on('datas', (data) => {
        this.platformConsumption = data;
      })

      // #ifdef H5
      this.from = this.$wechat.isWeixin() ? 'weixin' : 'h5'
      // #endif
      // #ifdef MP
      this.from = 'routine'
      // #endif
      // #ifdef APP-PLUS
      this.from = 'weixin'
      // #endif

      if (!this.isLogin) {
        this.isAuto = true;
        this.isShowAuth = true
      }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
      this.getUserInfo()
    },

    methods: {
      couponTap3: function(item, index) {
        uni.navigateTo({
          url: '/pages/redpacket/redpacket',
          success: (res) => {
            res.eventChannel.emit('changeRedPacketInfo', this.platformConsumption)
            uni.$once('changeRedPacket', (data) => {
              this.consumption_id = data;
              orderCheck({
                ...this.checkForm,
                consumption_id: this.consumption_id
              }).then(res=>{
                this.total_coupon = res.data.order_price;
                this.consumption_money = res.data.consumption_money;
                this.payForm.consumption_id = this.consumption_id;
                // this.payForm.money = res.data.order_price;
              })
            })
          }
        })
      },
      // 授权关闭
      authColse: function(e) {
        console.log(e, 'authColse')
        this.isShowAuth = e;
      },
      onLoadFun() {
        this.isShowAuth = false;
      },

      // 获取个人信息
      getUserInfo() {
        getUserInfo().then(res => {
          this.userInfo = res.data;
          this.loadMoneyInfo();
        })
      },

      payItem: function(e) {
        let that = this;
        let active = e;
        that.active = active;
        // console.log(this.active);
        that.animated = true;
        that.payType = that.cartArr[active].value;
        if (that.payType == 'weixin') {
          that.payType = that.from
        }
      },
      
      loadMoneyInfo(){
        //获取账户金额以及冻结金额 重新调了一次接口
        getAdminApplyAPI(this.userInfo.service.mer_id).then(res => {
          this.moneyInfo = res.data;
        })
      },

      payment: function(data) {
        let that = this;
        createOrder(data).then(res => {

          let status = res.data.status,
            orderId = res.data.result.order_id,
            jsConfig = res.data.result.config,
            // 暂不跳转
            goPages = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=' + res.message +
            '&product_type=' + that.payForm.product_type + '&source=' + that.payForm.source,
            goPagesOrder = '/pages/order_details/stay?order_id=' + orderId +
            '&credit_buy=1&product_type=' + that.payForm.product_type;

          that.orderPay = true;
          uni.hideLoading();
          switch (status) {
            case 'ORDER_EXIST':
            case 'EXTEND_ORDER':
            case 'PAY_ERROR':
            case 'error':
              return that.$util.Tips({
                title: res.message
              }, {
                tab: 5,
                url: goPagesOrder
              });
              break;
            case 'success':
              return that.$util.Tips({
                title: res.message,
                icon: 'success'
              }, {
                tab: 5,
                url: goPages
              });
              break;
            case 'alipay':
            case "alipayQr":
              return;
              break;
              // #ifndef MP
            case "wechat":
            case "weixin":
            case "weixinApp":
              jsConfig.timeStamp = jsConfig.timestamp;
              // #ifndef APP-PLUS
              this.$wechat.pay(jsConfig).then(res => {
                return that.$util.Tips({
                  title: res.message,
                  icon: 'success'
                }, {
                  tab: 4,
                  url: goPages
                });
              }).catch(res => {
                if (res.errMsg == 'chooseWXPay:cancel') return that.$util.Tips({
                  title: '取消支付'
                }, {
                  tab: 5,
                  url: goPages + '&status=0'
                });
              })
              // #endif
              // #ifdef APP-PLUS
              let mp_pay_name = ''
              if (uni.requestOrderPayment) {
                mp_pay_name = 'requestOrderPayment'
              } else {
                mp_pay_name = 'requestPayment'
              }
              uni[mp_pay_name]({
                provider: 'wxpay',
                orderInfo: jsConfig,
                success: (e) => {
                  // 暂不跳转
                  let url = '/pages/order_pay_status/index?order_id=' + orderId +
                    '&msg=支付成功' + '&product_type=' + that.product_type +
                    '&source=' + that.source;

                  return that.$util.Tips({
                    title: '支付成功',
                    icon: 'success'
                  }, {
                    tab: 4,
                    url: url
                  });
                },
                fail: (e) => {
                  console.log(e, '111111111')
                  // 暂不跳转
                  let url = '/pages/order_pay_status/index?order_id=' + orderId +
                    '&msg=取消支付' + '&product_type=' + that.product_type +
                    '&source=' + that.source;
                  return that.$util.Tips({
                    title: '取消支付',
                  }, {
                    tab: 4,
                    url: url
                  });
                },
                complete: (res) => {
                  uni.hideLoading();
                },
              });
              // #endif
              break;
              // #endif
              // #ifdef MP
            case "routine":
              jsConfig.timeStamp = jsConfig.timestamp;
              that.toPay = true;
              let mp_pay_name = ''
              if (uni.requestOrderPayment) {
                mp_pay_name = 'requestOrderPayment'
              } else {
                mp_pay_name = 'requestPayment'
              }
              uni[mp_pay_name]({
                ...jsConfig,
                success: function(res) {
                  uni.hideLoading();
                  return that.$util.Tips({
                    title: '支付成功',
                    icon: 'success'
                  }, {
                    tab: 5,
                    url: goPages
                  });
                },
                fail: function(e) {
                  // 暂不跳转
                  let pages = '/pages/order_pay_status/index?order_id=' +
                    orderId + '&msg=取消支付' + '&product_type=' + that
                    .product_type + '&source=' + that.source;
                  return that.$util.Tips({
                    title: '取消支付'
                  }, {
                    tab: 5,
                    url: pages + '&status=0'
                  });
                },
              })
              break;
              // #endif
            case "balance":
              //余额
              return that.$util.Tips({
                title: res.msg
              }, {
                tab: 5,
                url: goPages + '&status=1'
              });
              break;
              // #ifdef H5
            case 'h5':
              let host = window.location.protocol + "//" + window.location.host;
              let url =
                `${host}/pages/order_pay_status/index?order_id=${orderId}&msg=${res.message}&product_type=${that.product_type}&source${that.source}`
              let eUrl = encodeURIComponent(url)
              let jsurl = jsConfig.mweb_url || jsConfig.h5_url
              let locations = `${jsurl}&redirect_url=${eUrl}`
              // 暂不跳转
              setTimeout(() => {
                location.href = locations;
              }, 100);
              break;
              // #endif
            default:
              // 暂不跳转
              let pages = '/pages/order_pay_status/index?order_id=' +
                orderId + '&msg=取消支付' + '&product_type=' + that.product_type + '&source=' +
                that.source

              return that.$util.Tips({
                title: '取消支付'
              }, {
                tab: 5,
                url: pages + '&status=0'
              });
          }
        }).catch(err => {
          return that.$util.Tips({
            title: err
          });
          uni.hideLoading();
        });
      },

      SubOrder: function() {
        let that = this,
          data = {};
        if (!that.payType) return that.$util.Tips({
          title: '请选择支付方式'
        });

        if (that.payType == 'balance' && this.userInfo.now_money < this.payForm.money) {
          return that.$util.Tips({
            title: '余额不足,请选择其他的支付方式!'
          });
        }
        this.payForm.pay_type = that.payType;
        uni.showLoading({
          title: '订单支付中',
          mask: true
        });

        // #ifdef MP
        openPaySubscribe().then(() => {
          that.payment(this.payForm);
        });
        // #endif

        // #ifndef MP
        that.payment(this.payForm);
        // #endif
      }
    }
  }
</script>

<style lang="scss" scoped>
  .order-submission .wrapper {
    margin-bottom: 12rpx;
    background-color: #fff;
  }

  .order-submission .wrapper .item {
    padding: 27rpx 30rpx;
    font-size: 30rpx;
    color: #282828;
  }

  .order-submission .virtual_form {
    padding: 0 30rpx;
  }

  /deep/.order-submission .virtual_form .uni-input-wrapper {
    text-align: right;
  }

  .order-submission .virtual_form .item-require {
    color: red;
    margin-right: 4rpx;
  }

  .order-submission .virtual_form .item {
    border-bottom: 1rpx solid #EEEEEE;
    padding: 27rpx 0;
  }

  .upload {
    display: -webkit-box;
    display: -moz-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-lines: multiple;
    -moz-box-lines: multiple;
    -o-box-lines: multiple;
    -webkit-flex-wrap: wrap;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
  }

  .order-submission .virtual_form .pictrue {
    width: 156rpx;
    height: 156rpx;
    margin: 24rpx 20rpx 0 0;
    position: relative;
    font-size: 11px;
    color: #bbb;
    border-radius: 3rpx;

    &:nth-child(4n) {
      margin-right: 0;
    }

    &:nth-last-child(1) {
      border: 0.5px solid #ddd;
      box-sizing: border-box;
    }

    uni-image,
    image {
      width: 100%;
      height: 100%;
      border-radius: 1px;

      img {
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -moz-user-select: none;
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        opacity: 0;
        width: 100%;
        height: 100%;
      }
    }
  }


  .order-submission .wrapper .item .discount {
    font-size: 30rpx;
    color: #999;

    &.discount_voice {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 500rpx;
      text-align: right;
    }
  }

  .order-submission .wrapper .item .discount .iconfont {
    color: #515151;
    font-size: 30rpx;
    margin-left: 15rpx;
  }

  .order-submission .wrapper .item .discount .num {
    font-size: 32rpx;
    margin-right: 20rpx;
  }

  .order-submission .wrapper .item input {
    flex: 1;
    height: 100%;
    margin-left: 20rpx;
    text-align: right;
  }

  .order-submission .wrapper .item .placeholder {
    color: #ccc;
  }

  .order-submission .wrapper .item .list {
    margin-top: 35rpx;
  }

  .order-submission .wrapper .item .list .payItem {
    border: 1px solid #eee;
    border-radius: 6rpx;
    height: 86rpx;
    width: 100%;
    box-sizing: border-box;
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #282828;
  }

  .order-submission .wrapper .item .list .payItem.on {
    border-color: var(--view-theme);
    color: var(--view-theme);
  }

  .order-submission .wrapper .item .list .payItem .name {
    width: 50%;
    text-align: center;
    border-right: 1px solid #eee;
    justify-content: left;
    padding-left: 80rpx;
  }

  .order-submission .wrapper .item .list .payItem .name .iconfont {
    width: 44rpx;
    height: 44rpx;
    border-radius: 50%;
    text-align: center;
    line-height: 44rpx;
    background-color: #fe960f;
    color: #fff;
    font-size: 30rpx;
    margin-right: 15rpx;
  }

  .order-submission .wrapper .item .list .payItem .name .iconfont.icon-weixin2 {
    background-color: #41b035;
  }

  .order-submission .wrapper .item .list .payItem .name .iconfont.icon-icon34 {
    background-color: #4295D5;
  }

  .order-submission .wrapper .item .list .payItem .tip {
    width: 49%;
    text-align: center;
    font-size: 26rpx;
    color: #aaa;
  }

  .order-submission .moneyList {
    margin-top: 12rpx;
    background-color: #fff;
    padding: 30rpx;
  }

  .order-submission .moneyList .item {
    font-size: 28rpx;
    color: #282828;
  }

  .order-submission .moneyList .item~.item {
    margin-top: 20rpx;
  }

  .order-submission .moneyList .item .money {
    color: #868686;
  }

  .order-submission .footer {
    width: 100%;
    height: 100rpx;
    height: calc(100rpx+ constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
    height: calc(100rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
    background-color: #fff;
    padding: 0 30rpx;
    font-size: 28rpx;
    color: #333;
    box-sizing: border-box;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 30;

    .footer_count {
      font-size: 28rpx;
    }

    .coupon_price {
      color: #999999;
      font-size: 20rpx;
      margin-top: 10rpx;

      text {
        color: #282828;
        padding: 2rpx 10rpx;
        background: #F5F5F5;
        border-radius: 26rpx;
        margin-left: 20rpx;
        line-height: 30rpx;
        height: 30rpx;
        display: inline-block;
      }
    }
  }

  .pColor {
    color: var(--view-priceColor);
  }

  .order-submission .footer .settlement {
    font-size: 30rpx;
    color: #fff;
    width: 240rpx;
    height: 70rpx;
    background-color: var(--view-theme);
    border-radius: 50rpx;
    text-align: center;
    line-height: 70rpx;

    &.disabled {
      background-color: #cccccc;
    }
  }

  .storeinfo-wrapper {
    .store-item {
      margin-top: 12rpx;
      background-color: #fff;

      .store-title {
        display: flex;
        align-items: center;
        padding: 28rpx 30rpx;

        .icon-shangjiadingdan {
          font-size: 32rpx;
        }

        .icon-xiangyou {
          font-size: 26rpx;
          color: #999;
        }

        .txt {
          margin: 0 8rpx;
        }
      }

      .product-item {
        display: flex;
        padding: 25rpx 30rpx;
        border-top: 1px solid #F0F0F0;

        .img-box {
          width: 130rpx;
          height: 130rpx;

          image {
            width: 130rpx;
            height: 130rpx;
            border-radius: 16rpx;
          }
        }

        .content {
          position: relative;
          width: 550rpx;
          margin-left: 30rpx;
          font-size: 28rpx;
          color: #282828;
          overflow: hidden;

          &.event_content {
            .line1 {
              width: 360rpx;
            }

            .price {
              position: absolute;
              top: 0;
              right: 0;
              margin-top: 0;

              text {
                display: block;
                text-align: right;
              }
            }
          }

          .label {
            margin-top: 10rpx;
            color: #868686;
            font-size: 20rpx;
          }

          .price {
            margin-top: 20rpx;
            color: var(--view-priceColor);
            position: relative;

            text {
              margin-left: 10rpx;
              color: #999;
            }

            .delivery_type {
              float: right;

              text {
                color: var(--view-priceColor);
                font-size: 20rpx;
              }
            }
          }
        }
      }
    }
  }

  uni-checkbox-group,
  .checkgroup {
    width: 100%;

    .checkbox {
      float: right;
    }
  }

  .total {
    display: flex;
    justify-content: flex-end;
    padding-right: 30rpx;
    padding-bottom: 30rpx;
    font-size: 26rpx;
    color: #282828;

    .price {
      margin-left: 10rpx;
      color: var(--view-priceColor);
      font-size: 28rpx;
      font-weight: bold;

      text {
        font-size: 20rpx;
      }
    }
  }

  .red_packet {
    color: #ff5c2d !important;
    background-color: rgba(#ff5c2d, 0.3);
    border-radius: 60rpx;
    padding: 5rpx 10rpx;
    padding-left: 20rpx;
    font-size: 25rpx;
  }
</style>