<template>
  <view class="wrapper">
    <!-- 背景颜色充满屏 -->
    <view class="bg-color"></view>
    <navBar title="收银"></navBar>
    <view class="money">
      <text class="money-title">需支付金额(元)</text>
      <text class="money-value"
        >￥{{ state.orderData.amount / 100 ?state.orderData.amount / 100: "0.00" }}</text
      >
    </view>
    <view class="bankcard">
      <view class="method-item border-line">
        <view class="method-name">
          <image class="name-img" :src="`${$imgUrl}order/bank.png`"></image>
          <text class="name-text">{{ state.bankInfo.name }}</text>
        </view>
        <image
          class="name-img-selected"
          :src="`${$imgUrl}order/selected.png`"
          v-if="state.methodSelected == state.bankInfo.id"
        ></image>
        <view
          class="select-circle"
          @click="methodHandle(state.bankInfo.id)"
          v-else
        ></view>
      </view>
      <view class="method-item other-method" @click="showList">
        <view class="method-name">
          <text class="name-text text-space">其他银行卡</text>
        </view>
        <image class="img-arrow" :src="`${$imgUrl}user/icon-arrow.png`"></image>
      </view>
    </view>
    <view class="pay-method">
      <view class="method-item border-line" @click="methodHandle('wx')">
        <view class="method-name">
          <image class="name-img" :src="`${$imgUrl}order/uni.png`"></image>
          <text class="name-text">微信支付</text>
        </view>
        <image
          class="name-img-selected"
          :src="`${$imgUrl}order/selected.png`"
          v-if="state.methodSelected == 'wx'"
        ></image>
        <view class="select-circle" v-else></view>
      </view>
	  
	  <view class="method-item border-line" @click="methodHandle('ali')">
	    <view class="method-name">
	      <image class="name-img" :src="`${$imgUrl}order/uni.png`"></image>
	      <text class="name-text">支付宝支付</text>
	    </view>
	    <image
	      class="name-img-selected"
	      :src="`${$imgUrl}order/selected.png`"
	      v-if="state.methodSelected == 'ali'"
	    ></image>
	    <view class="select-circle" v-else></view>
	  </view>
      <view class="method-item border-line" @click="methodHandle('ysf')">
        <view class="method-name">
          <image class="name-img" :src="`${$imgUrl}order/ysf.png`"></image>
          <text class="name-text">云闪付</text>
        </view>
        <image
          class="name-img-selected"
          :src="`${$imgUrl}order/selected.png`"
          v-if="state.methodSelected == 'ysf'"
        ></image>
        <view class="select-circle" v-else></view>
      </view>
      <view class="method-item" @click="methodHandle('wxhy')">
        <view class="method-name">
          <image class="name-img" :src="`${$imgUrl}order/wx1.png`"></image>
          <text class="name-text">微信好友支付</text>
        </view>
        <image
          class="name-img-selected"
          :src="`${$imgUrl}order/selected.png`"
          v-if="state.methodSelected == 'wxhy'"
        ></image>
        <view class="select-circle" v-else></view>
      </view>
    </view>
    <view class="btn" @click="toPayOrder">支付</view>

    <!-- 银行list弹窗 -->
    <u-popup
      v-model="state.listInfo.show"
      mode="bottom"
      :mask-close-able="false"
    >
      <view class="list-header">请选择</view>
      <scroll-view scroll-y="true" style="height: 530rpx; background: #f4f4f4">
        <view class="list-box">
          <view
            v-for="item in state.listInfo.list"
            :key="item.id"
            class="p-list-item"
            @click="listSelected(item)"
          >
            {{ item.name }}
          </view>
        </view>
      </scroll-view>
    </u-popup>
  </view>
</template>

<script setup lang="ts">
import navBar from "@/components/nav-bar/nav-bar.vue";
import { reactive } from "vue";
import { request } from "@/utils/network/request.js";
import {
  checkOrderStatus,
  orderPay,
  wechatAppID,
  wechatPayConfigId,
  aliPayConfigId,
  obtainUserId,
  wechatSecret,
} from "@/utils/network/api";
import { stringToJson } from "@/utils/network/encryption";
import { onLoad } from "@dcloudio/uni-app";
import { confirm, msg } from "@/utils/utils";

const state = reactive({
  methodSelected: "wx",
  bankInfo: { id: 1, name: "招商银行储蓄卡（0843）" },
  listInfo: {
    show: false,
    list: [
      { name: "工商银行", id: 2 },
      { name: "建设银行", id: 3 },
    ],
  },
  orderData: {} as any, //订单数据
  openid: "",
});

const methodHandle = (val) => {
  state.methodSelected = val;
  console.log(state.methodSelected);
};

// 展开其他银行卡
const showList = () => {
  state.listInfo.show = true;
};

//其他银行卡选择
const listSelected = (item) => {
  state.listInfo.show = false;
};

//订单支付
const toPayOrder = () => {
  if (state.methodSelected == "wx") {
    //微信支付
    wxPayment();
  }  else if (state.methodSelected == "ali"){
	  aliPayment()
  } else {
    msg("目前只支持微信支付！");
  }
};

//掉起微信支付
const wxPayment = () => {
  // #ifdef MP-WEIXIN
  if (!state.openid) {
    getOpenID();
    msg("请求失败，请稍后重试！");
    return;
  }

  const options = {
    type: 2,
    data: {
      openid: state.openid,
      productId: state.orderData.productId, //产品id
      orderId: state.orderData.orderId,
      payConfigId: wechatPayConfigId,
    },
    method: "POST",
    showLoading: true,
  };
  request(orderPay, options).then((res) => {
    const data = stringToJson(res.bizContent);
    uni.requestPayment({
      provider: "wxpay",
      orderInfo: "",
      timeStamp: data.timestamp,
      nonceStr: data.noncestr,
      package: data.wxPackage ?data.wxPackage: "",
      signType: data.signType,
      paySign: data.sign,
      success: function (e) {
        console.log("支付成功", e);
        checkOrder();
      },
      fail: function (err) {
        confirm(err, () => {}, "支付失败", false);
      },
    });
  });
  // #endif
};

//掉起支付宝支付
const aliPayment = () => {
  // #ifdef MP-ALIPAY
 my.getAuthCode({
   scopes: 'auth_user',
   success: res => {
 	  const optionsUser = {
 	  	type: 2,
 	  	data: {
 	  		payConfigId: aliPayConfigId,
 	  		code: res.authCode
 	  	},
 	  	method: "POST",
 	  	showLoading: true,
 	  };
 	  request(obtainUserId, optionsUser).then((res) => {
 	  	const data = stringToJson(res.bizContent); 
 	  	const optionsali= {
 	  	  type: 2,
 	  	  data: {
 	  	    openid: data.userId,
 	  	    productId: state.orderData.productId, //产品id
 	  	    orderId: state.orderData.orderId,
 	  	    payConfigId: aliPayConfigId,
 	  	  },
 	  	  method: "POST",
 	  	  showLoading: true,
 	  	};
 		request(orderPay, optionsali).then((res) => {
 			const data = stringToJson(res.bizContent);
 			state.orderData.orderId = data.orderId
 			my.tradePay ({
 			  // 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号 trade_no
 			  tradeNO: data.prepayId,
 			  success: res => {
 			    console.log("支付成功", res);
 			    checkOrder();
 			  },
 			  fail: res => {
 			    confirm(res, () => {}, "支付失败", false);
 			  },
 			});
 			
 		});
 	  });
   },
   fail: err => {
     console.log('my.getAuthCode 调用失败', err)
   }
 });
  
  // #endif
};


//获取微信小程序openid
const getOpenID = () => {
  uni.login({
    provider: "weixin",
    success: function (e) {
      uni.request({
        url: `https://api.weixin.qq.com/sns/jscode2session?appid=${wechatAppID}&secret=${wechatSecret}&js_code=${e.code}&grant_type=authorization_code`,
        success: (res: any) => {
          state.openid = res.data.openid;
        },
      });
    },
  });
};

//支付成功改变订单状态
const checkOrder = () => {
	let configId = ""
	if (state.methodSelected == "wx") {
		configId = wechatPayConfigId;
	} else if (state.methodSelected == "ali")  {
		configId = aliPayConfigId
	}

  const options = {
    type: 2,
    data: {
      orderId: state.orderData.orderId,
      payConfigId: configId,
    },
    method: "POST",
    showLoading: true,
  };

  request(checkOrderStatus, options).then((res) => {
    payOrderSuccess();
  });
};

const payOrderSuccess = () => {
  confirm(
    "您申办的ETC订单支付成功，请等待业务员审核信息，确认无误后发货！",
    () => {
      uni.$emit("refreshOrder");
      uni.navigateBack();
    },
    "支付成功",
    false
  );
};

onLoad((options) => {
  //需要参数参数json形式：{orderId, productId，amount}
  state.orderData = JSON.parse(options.data);
  console.log(state.orderData);
  getOpenID();
});
</script>
<style lang="scss" scoped>
.bg-color {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #f3f3f3;
  z-index: -1;
}

.wrapper {
  padding-bottom: 20rpx;
}

.money {
  background: #ffffff;
  display: flex;
  flex-direction: column;
  height: 266rpx;
  justify-content: center;
  align-items: center;

  .money-title {
    color: #717171;
    font-size: 29rpx;
  }

  .money-value {
    font-size: 40rpx;
    color: #2a2a2a;
    font-weight: 500;
    margin-top: 32rpx;
  }
}

.bankcard,
.pay-method {
  background: #ffffff;
  margin-top: 20rpx;
  padding: 0 30rpx;
}

.method-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;

  .text-space {
    margin-left: 69rpx;
  }

  .img-arrow {
    width: 14rpx;
    height: 25rpx;
    margin-right: 12rpx;
  }

  .method-name {
    .name-img {
      width: 50rpx;
      height: 50rpx;
      vertical-align: middle;
    }

    .name-text {
      color: #333333;
      font-size: 28rpx;
      margin-left: 19rpx;
      line-height: 30rpx;
    }
  }

  .select-circle {
    width: 37rpx;
    height: 37rpx;
    background: #ffffff;
    border: 2px solid #999999;
    border-radius: 50%;
  }

  .name-img-selected {
    width: 37rpx;
    height: 37rpx;
  }

  .text-icon {
    font-size: 25rpx;
  }
}

.border-line {
  border-bottom: 1rpx solid #dcdcdc;
}

.btn {
  margin: 233rpx 40rpx 40rpx 40rpx;
  height: 80rpx;
  background: linear-gradient(-90deg, #43a1e0 0%, #13e7c1 100%);
  border-radius: 40rpx;
  font-size: 32rpx;
  font-weight: 400;
  color: #fff;
  text-align: center;
  line-height: 80rpx;
}
.list-header {
  height: 81rpx;
  background: #ffffff;
  border: 1px solid #dcdcdc;
  line-height: 81rpx;
  text-align: center;
  color: #333333;
  font-size: 36rpx;
}
.p-list-item {
  padding: 30rpx 46rpx;
  border-bottom: 1px solid #dcdcdc;
  font-size: 28rpx;
  color: #333333;
}
.list-box {
  padding: 0 30rpx;
}
</style>
