<template>
  <view>
    <!-- 跳转微信-->
    <ModalConfirm ref="modalConfirmRefs" :model="model" @editOrder="editOrder" @saveSchedule="saveSchedule">
    </ModalConfirm>
  </view>
</template>

<script>
  import {
    editTerminalOrder,
    queryTerminalOrder
  } from '@/api/home/order.js'
  import {
    creatMemberOrder,
    queryMemberOrder
  } from '@/api/home/memberOrder.js'
  import {
    getOpenId
  } from '@/api/common.js'

  import {
    buySchedule,
    queryScheduleAgentOrder
  } from '@/api/teaching/scheduleAgent.js'

  import {
    taskAccomplish
  } from "@/api/home/taskCentre.js";

  import ModalConfirm from '@/components/modal/modalConfirm.vue'

  export default {
    components: {
      ModalConfirm
    },
    props: {
      orderForm: {
        typeof: Object
      },
      payOrderType: {
        typeof: String
      },
      scheduleForm: {
        typeof: Object
      }
    },
    data() {
      return {
        //跳转微信参数
        sweixin: {},
        model: {
          title: '',
          content: '',
          type: 0
        },
        memberOrderForm: {
          orderId: undefined,
          openId: undefined,
          payType: 'W',
          payPlat: undefined
        },
        orderId: undefined
      }
    },
    methods: {
      createOrder() {
        //终端
        if (this.payOrderType == 'DEVICE_PRODUCT') {
          if (this.orderForm.paytype == 'W') {
            this.orderPament();
          } else if (this.orderForm.paytype == 'T') {
            this.model.title = '提示'
            this.model.content = '确认余额支付吗？'
            this.model.type = 1
            this.$nextTick(() => {
              this.$refs.modalConfirmRefs.openModel();
            })
          } else if (this.orderForm.paytype == 'B') {
            this.model.title = '提示'
            this.model.content = '确认使用银行卡转账吗？'
            this.model.type = 2
            this.$nextTick(() => {
              this.$refs.modalConfirmRefs.openModel();
            })
          } else {
            uni.$u.toast('请求类型异常！');
          }
        } else if (this.payOrderType == 'MEMBER') {
          this.orderPament();
        } else if (this.payOrderType == 'TEACHING_SCHEDULE') {
          if (this.scheduleForm.paytype == 'W') {
            this.orderPament();
          } else if (this.scheduleForm.paytype == 'T') {
            this.model.title = '提示'
            this.model.content = '确认余额支付吗？'
            this.model.type = 3
            this.$nextTick(() => {
              this.$refs.modalConfirmRefs.openModel();
            })
          }
        }
        //其他情况暂时没有
      },
      orderPament() {
        let _this = this

        //微信小程序支付
        //#ifdef MP-WEIXIN
        uni.showLoading({
          mask: true,
          title: '加载中'
        });

        wx.login({
          success(res) {
            if (res.code) {
              getOpenId({
                'code': res.code
              }).then(res => {
                //调用下单
                if (_this.payOrderType == 'DEVICE_PRODUCT') {
                  //openId
                  _this.orderForm.openId = res.msg
                  _this.editOrder(_this.orderForm.paytype);
                } else if (_this.payOrderType == 'MEMBER') {
                  //openId
                  _this.memberOrderForm.openId = res.msg
                  _this.openMemberOrder();
                } else if (_this.payOrderType == 'TEACHING_SCHEDULE') {
                  //openId
                  _this.scheduleForm.openId = res.msg
                  _this.saveSchedule(_this.scheduleForm.paytype);
                }
              });
            } else {
              uni.hideLoading()
              console.log('登录失败！' + res.errMsg)
            }
          },
          fail: (res) => {
            console.log("获取登录凭证code失败！", res)
          }
        })
        //#endif

        //#ifdef APP-PLUS

        //调用下单
        if (_this.payOrderType == 'DEVICE_PRODUCT') {
          //openId
          _this.editOrder(_this.orderForm.paytype);
        } else if (_this.payOrderType == 'MEMBER') {
          //openId
          _this.openMemberOrder();
        } else if (_this.payOrderType == 'TEACHING_SCHEDULE') {
          _this.saveSchedule(_this.scheduleForm.paytype);
        }
        //#endif

        // uni.$u.toast('请前往小程序下单！');
        // //跳转小程序
        // this.model.type = 0
        // this.model.title = '提示'
        // this.model.content = '是否确认跳转微信小程序吗？'
        // this.$nextTick(() => {
        //   this.$refs.modalConfirmRefs.openModel();
        // })
      },
      //调用接口
      editOrder(payPlat) {
        //判断平台
        //#ifdef MP-WEIXIN
        this.orderForm.payPlat = 'WECHAT';
        //#endif

        //#ifdef APP-PLUS
        this.orderForm.payPlat = 'APP';
        //#endif

        editTerminalOrder(this.orderForm).then(res => {
          //跳转到支付成功页面
          if (payPlat == 'T') {
            this.toolBtn("complete")
          } else if (payPlat == 'W') {
            //下单成功，打开支付
            this.openWxPayPage(res.data);
          } else if (payPlat == 'B') {
            //如果是银行卡转账，直接提交订单，跳到支付成功页面
            //新增成功跳转到订单支付页
            this.toolBtnComplete('complete')
          }
        });
      },
      //调用接口
      openMemberOrder() {
        //判断平台
        //#ifdef MP-WEIXIN
        this.memberOrderForm.payPlat = 'WECHAT';
        //#endif

        //#ifdef APP-PLUS
        this.memberOrderForm.payPlat = 'APP';
        //#endif

        creatMemberOrder(this.memberOrderForm).then(res => {
          //下单成功，打开支付
          this.memberOrderForm.orderId = res.data.orderId
          this.openWxPayPage(res.data);
        });
      },
      //调用接口
      saveSchedule(payPlat) {
        //判断平台
        //#ifdef MP-WEIXIN
        this.scheduleForm.payPlat = 'WECHAT';
        //#endif

        //#ifdef APP-PLUS
        this.scheduleForm.payPlat = 'APP';
        //#endif

        buySchedule(this.scheduleForm).then(res => {
          //跳转到支付成功页面
          if (payPlat == 'T') {
            this.skipBtnDetialVideo()
          } else if (payPlat == 'W') {
            //下单成功，打开支付
            this.openWxPayPage(res.data);
          }
        })
      },
      openWxPayPage(obj) {
        let _this = this
        //订单号赋值
        _this.orderId = obj.orderId
        uni.getProvider({
          service: 'payment',
          success: function(res) {
            if (~res.provider.indexOf('wxpay')) {
              //#ifdef MP-WEIXIN
              uni.requestPayment({
                "provider": "wxpay", //固定值为"wxpay"
                "timeStamp": obj.timeStamp,
                "nonceStr": obj.nonceStr,
                "package": obj.package,
                "signType": obj.signType,
                "paySign": obj.paySign,
                "success": function(res) {
                  //成功回调
                  _this.successOrder(_this.orderId);
                },
                "fail": function(res) {
                  console.log(res)
                  uni.$u.toast('用户取消支付！');
                },
              })
              //#endif

              //#ifdef APP-PLUS
              var orderInfo = {
                "appid": obj.appId, // 应用ID（AppID）
                "partnerid": obj.mchId, // 商户号（PartnerID）
                "prepayid": obj.prepayId, // 预支付交易会话ID
                "package": obj.package, // 固定值
                "noncestr": obj.nonceStr, // 随机字符串
                "timestamp": obj.timeStamp, // 时间戳（单位：秒）
                "sign": obj.paySign // 签名，这里用的 MD5 签名
              };

              uni.requestPayment({
                "provider": "wxpay", //固定值为"wxpay"
                "orderInfo": orderInfo,
                "success": function(res) {
                  //成功回调
                  _this.successOrder(_this.orderId);
                },
                "fail": function(res) {
                  console.log(res)
                  uni.$u.toast('用户取消支付！');
                },
              })
              //#endif
            }
          }
        });
      },
      successOrder(orderId) {
        let _this = this
        //调用远程接口修改状态
        uni.$u.toast('支付成功！');
        if (_this.payOrderType == 'DEVICE_PRODUCT') {
          queryTerminalOrder({
            'regulateCode': orderId
          }).then(res => {
            //跳转到支付成功页面
            _this.toolBtn("complete");
          });
        } else if (_this.payOrderType == 'MEMBER') {
          queryMemberOrder({
            'orderId': orderId
          }).then(res => {
            //刷新会员页面和修改缓存
            _this.$emit('changeAgentMode');
          });
        } else if (_this.payOrderType == 'TEACHING_SCHEDULE') {
          queryScheduleAgentOrder({
            'regulateCode': orderId
          }).then(res => {
            //跳转到课程详情页面
            _this.skipBtnDetialVideo();
          })
        }

        //任务
        let taskType = wx.getStorageSync("taskType");
        let taskId = wx.getStorageSync("taskId");
        if(!!taskType && taskType == "order"){
          taskAccomplish(taskId).then(res => {
              uni.$u.toast('任务奖励已到账余额！');
              wx.removeStorageSync("taskType")
              wx.removeStorageSync("taskId")
          })
        }
      },
      // 跳页
      toolBtn(tool) {
        uni.navigateTo({
          url: './' + tool
        })
      },
      toolBtnComplete(tool) {
        const payType = 'Y';
        uni.navigateTo({
          url: '/pages/mall/' + tool + '?orderId=' + this.orderForm.orderId + '&payType=' + payType
        })
      },
      //跳转到课程详情
      skipBtnDetialVideo() {
        uni.navigateTo({
          url: "/pages/work/detial_video?scheduleId=" + this.scheduleForm.scheduleId
        })
      }
    }
  }
</script>

<style>
</style>
