<template>
  <div class="payment-con">
    <div class="content-scroll">
      <div class="header flex-default">
        <div class="title">待支付</div>
        <div class="left-time flex-default" v-if="payTypeObj.showLeftTime">
          <span>支付剩余时间</span>
          <van-count-down
            class="count-down"
            :time="leftTime"
            @finish="countDownFinish"
            :format="leftTimeFormat"
          />
        </div>
      </div>
      <div class="price-con flex-default">
        <m-price
          :amt="payInfo[payTypeObj.unPaidAmtKey]"
          color="#FFFFFF"
          :rmbSize="18"
          :intSize="32"
          :floatSize="22"
        />
      </div>
      <div
        class="pay-type"
        v-for="(pItem, key) of payTypeList"
        :key="`pay-type-${key}`"
      >
        <div class="header flex-default">
          <m-icon :size="11" icon="icon-3dot" />
          <div class="title">{{ pItem.title }}</div>
        </div>
        <div
          class="item flex-default"
          v-for="(item, index) of pItem.list"
          :key="`pay-currenty-${index}`"
          @click="handleSelect(key, item)"
        >
          <m-icon :icon="item.icon" :size="20" className="pay-icon" />
          <div class="right flex-default">
            <div class="text">{{ item.name }}</div>
            <m-icon
              :icon="
                paySelect.type== item.type
                  ? 'icon-radio-round-check'
                  : 'icon-radio-round'
              "
              :size="16"
            />
          </div>
        </div>
      </div>
    </div>

    <div class="bottom-con flex-default">
      <van-button
        type="primary"
        round
        @click="handlePay"
        :disabled="btnDisabled"
        block
      >
        立即支付
      </van-button>
    </div>

    <verify-popup
      v-model="showVerify"
      ref="verifypopup"
      :pid="pid"
      :payTypeMap="payTypeMap"
      :payTypeObj="payTypeObj"
      @handleConfirm="handleConfirm"
    />
  </div>
</template>

<script>
import VerifyPopup from "./verify-popup";
import { mapState, mapMutations } from "vuex";
import { PayType, PayTypeObj } from "@/enums";
import {sysInfo}  from "@/utils/common";
export default {
  components: {
    VerifyPopup,
  },
  data() {
    return {
      payTypeList: {
        currency: {
          title: "法币资产支付",
          list: [
            {
              type: 2,
              name: "微信支付",
              icon: "icon-wxpay",
            },
            // {
            //   type: 1,
            //   name: "支付宝",
            //   icon: "icon-alipay",
            // },
            // {
            //   type: 3,
            //   name: "银联支付",
            //   icon: "icon-unionpay",
            // },
          ],
        },
        coin: {
          title: "数字资产支付",
          list: [
            {
              type: 4,
              name: "积分支付",
              icon: "icon-integral-pay",
            },
          ],
        },
      },
      paySelect: {
        currency: "",
        coin: 4,
        type:2
      },
      showVerify: false,
      pid: "",
      payType: PayType.NORMAL,
      payInfo: {
        total: 0,
        createTime: 0,
        unpaidAmount: 0,
      },
      leftTime: 3 * 60 * 1000,
      formType: "order",
      timeFinish: false,
      oid:""
    };
  },
  computed: {
    ...mapState(["withdrawGoodsInfo", "accountInfo", "preSaleBalanceInfo"]),
    btnDisabled() {
      if (this.payTypeObj.showLeftTime) {
        if (this.timeFinish) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    payTypeMap() {
      let map = {};
      Object.keys(PayType).forEach((key) => {
        map[key] = this.payType == PayType[key];
      });
      return map;
    },
    payTypeObj() {
      let obj = PayTypeObj[this.payType];
      return obj || PayTypeObj[PayType.NORMAL];
    },
    leftTimeFormat(){
      if(this.payTypeMap.PRE_SALE_DEPOSIT || this.payTypeMap.PRE_SALE_BALANCE){
        return "DD天HH时mm分ss秒"
      }
      return "mm:ss"
    }
  },
  methods: {
    ...mapMutations(["clearPickUpGoodsInfo"]),
    confirmSetPwd() {
      if (this.accountInfo.isPayPassword) {
        return true;
      }
      this.$confirm({
        content: "您当前尚未设置支付密码，是否前往设置？",
        confirm: () => {
          let query = { first: true, setup: 1 };
          this.$router.push({ name: "update-pay-pwd", query });
        },
      });
    },
    handlePay() {
      if(!this.paySelect.type) {
         return this.$toast('请选择支付方式~')
      }
      switch(this.paySelect.type){
        case 2:
          this.wxPay()
          break;
        case 4:
          if(this.confirmSetPwd()){
            this.showVerify = true;
          }
           break;
        default:
          this.showVerify = true;
      }
    },
    wxPay(){  //获取微信支付 id
      let postData = { 
        "payType": this.paySelect.type,
        "pid": this.pid,
          }
      if (this.payTypeMap.WITHDRAW_GOODS) {
        postData = { ...this.withdrawGoodsInfo,...postData};
      } else if (this.payTypeMap.PRE_SALE_BALANCE) {
        postData = { ...this.preSaleBalanceInfo,...postData};
      }
      postData.delivery=0
     
      if(sysInfo.isWechat) {
        postData.model = 1
        postData.openId = localStorage.getItem('openId')
        this.$api({
          apiName:'wxPay',
          postData,
          success:(res)=> {
            if (typeof WeixinJSBridge == "undefined") {
              if (document.addEventListener) {
                  document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(res), false);
              } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(res));
                document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(res));
              }
            } else {
              this.onBridgeReady(res);
            }
          }
        })  
      }else {
        postData.model = 2
        this.$api({ //
          apiName:'wxPay',
          postData,
          success:(res)=> {
              this.appWxPay(res,response=>{  
                // alert(response)
                if(response==0){
                  let params = { pid:this.pid };
                  let query = { type: this.payType,oid:this.oid };
                  this.$router.replace({ name: "pay-result", params, query});
                }else if(response==-2){
                  this.$toast("取消支付");
                }else{
                  this.$toast("支付失败");
                }
              })
            }
        })
      }   
    },
    onBridgeReady(res) {
      let vm = this
      WeixinJSBridge.invoke('getBrandWCPayRequest', {
        "appId": res.appId,     //公众号ID，由商户传入     
        "timeStamp": res.timeStamp,     //时间戳，自1970年以来的秒数     
        "nonceStr":  res.noncestr,      //随机串     
        "package":  res.prePayId,
        "signType":res.signType,     //微信签名方式：     
        "paySign":  res.signature,
      },
      function(t) {
        if (t.err_msg == "get_brand_wcpay_request:ok") {
          let params = { pid: vm.pid };
           let query = { type: vm.payType,oid:vm.oid };
          // 使用以上方式判断前端返回,微信团队郑重提示：
          //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          vm.$router.replace({ name: "pay-result", params, query });
        }
        else if (t.err_msg == "get_brand_wcpay_request:cancel") {
            // alert("支付取消") // 会执行
        } else {
            alert("支付失败")
        }
      })
    },
    handleSelect(key, item) {
      if (this.paySelect.type == item.type) {
        this.paySelect.type = "";
      } else {
        this.paySelect.type = item.type;
      }
    },
    requestData() {
      if (this.payTypeMap.WITHDRAW_GOODS) {
        this.payInfo = this.withdrawGoodsInfo;
        return;
      } else if(this.payTypeMap.PRE_SALE_BALANCE){
        this.payInfo = this.preSaleBalanceInfo
        return
      }
      this.$showLoading();
      this.$api({
        apiName: this.payTypeObj.detailApi,
        postData: this.pid,
        success: (res) => {
          let oids=JSON.parse(res.oidsJson)
          this.oid=oids[0] || ""
          this.payInfo = res;
          let timeOut = this.payInfo.createTime + 3 * 60 * 1000 - +new Date();
          this.leftTime = timeOut > 0 ? timeOut : 0;
          setTimeout(() => {
            this.$hideLoading();
          }, 500);
        },
      });
    },
    handleConfirm(type, code) {
      this.$showLoading("支付中...");
      let { pid, payType } = this;
      let postData = { pid };
      
      if (this.payTypeMap.WITHDRAW_GOODS) {
        postData = { ...this.withdrawGoodsInfo };
      } else if (this.payTypeMap.PRE_SALE_BALANCE) {
        postData = { ...this.preSaleBalanceInfo };
      }
      if (type == "pwd") {
        postData.payPassword = code;
      } else {
        postData.verificationCode = code;
      }
      postData.coin="BASE"
      postData.payType=this.paySelect.type
      this.$api({
        apiName: this.payTypeObj.api,
        postData,
        success: (res) => {
          if (this.payTypeMap.WITHDRAW_GOODS) {
            pid = res;
          }
          let params = { pid };
          let query = { type: payType,oid:this.oid };
          this.$router.replace({ name: "pay-result", params, query });
        },
        complete: () => {
          this.$refs.verifypopup.clearCode();
          this.$hideLoading();
        },
      });
    },

    countDownFinish() {
      this.timeFinish = true;
    },
  },
  created() {
    let { pid, type, fromType } = this.$route.query;
    this.pid = pid;
    this.payType = type;
    this.fromType = fromType;
    this.requestData();
    // this.confirmSetPwd();
  },
};
</script>


<style lang="less">
.payment-con {
  height: 100vh;
  background: #f5f7fb;
}

.payment-con > .content-scroll {
  height: ~"calc(100% - 60px)";
  overflow-y: auto;
}

.payment-con > .content-scroll {
  > .header {
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;
    padding: 10px 16px 0 28px;

    .title {
      font-weight: bold;
      color: #140603;
      font-size: 18px;
    }

    .left-time {
      font-size: 12px;
      color: #2C66F5;
    }

    .count-down {
      font-size: 12px;
      margin-left: 3px;
    }
  }

  > .price-con {
    height: 80px;
    background: linear-gradient(136deg, #488FF7 0%, #2C66F5 100%);
    border-radius: 10px;
    margin: 0 16px 10px 16px;
    align-items: center;
    padding-left: 12px;
  }

  > .pay-type {
    background: #ffffff;
    border-radius: 10px;
    margin-bottom: 10px;
    color: #140603;
    padding-bottom: 22px;

    .header {
      align-items: center;
      padding: 14px 16px 10px 16px;
    }

    .header > .title {
      font-size: 14px;
      font-weight: bold;
      margin-left: 5px;
    }

    .item {
      align-items: center;
      padding: 0 18px;
      height: 50px;
    }
    .item > .right {
      height: 100%;
      flex: 1;
      border-bottom: 1px solid #f1f1f1;
    }

    .item .pay-icon {
      margin-right: 12px;
    }

    .item .text {
      flex: 1;
      font-size: 13px;
    }
  }
}

.payment-con > .bottom-con {
  background: #f5f7fb;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 0 20px;
  height: 60px;
  align-items: center;
  button {
    height: 36px;
  }
}
</style>
