// pages/payPlatform/payPlatform.js
const app = getApp();
import Dialog from '@vant/weapp/dialog/dialog';
import {
  pay
} from "../../../api/consult"
import {
  throttle
} from "../../../utils/util"
//import {payPrescription} from "../../api/prescription"
let isLock=false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static',
    doctor_id: '',
    chat_id: '',
    time: '',
    inquiry_no: '',
    amount_total: "",
    order_detection_id:'',
    coupon_amount_total: 0,
    payment_amount_total: '',
    pay_config: null,
    created_at: "",
    inquiry_type: "",
    order_type: 1,
    inquiry_mode: "",
    order_inquiry_id: "",
    order_no: "",
    order_id: '',
    order_product_id: '',
    fromType: '',
    paySucess:false
  },
  payOrder() {
    let {
      order_no,
      order_type
    } = this.data;
    pay({
      order_type: order_type,
      order_no: order_no
    }).then((result) => {
      console.log('------------------------------------------')
      console.log(result);
      let data=result.data;
      if(result.status==1){
        for (const key in data) {
          this.setData({
            [key]: data[key]
          })
        }
        this.wxPay();
      }else{
         //inquiry_status '问诊订单状态（1:待支付 2:待分配 3:待接诊 4:已接诊 5:已完成 6:已结束 7:已取消）',
        //inquiry_pay_status//1:未支付 2:已支付 3:支付中 4:支付失败 5:支付超时 6:支付关闭 7:已撤销 8:转入退款）;
        let order_status='order_status';
        let pay_status='order_pay_status';
        let message_error='';
       if(data[order_status]==7){
          if(data[pay_status]==5){
           message_error="订单支付超时"
          }else{
           message_error="订单已取消";  
          }
       }else if(data[pay_status]==1){
         message_error="订单未支付"
       }else if(data[pay_status]==2){
         message_error="订单已支付"
       }else if(data[pay_status]==3){
         message_error="订单支付中"
       }else if(data[pay_status]==4){
         message_error="订单支付失败"
       }else if(data[pay_status]==5){
         message_error="订单支付超时"
       }else if(data[pay_status]==6){
         message_error="订单支付关闭"
       }else if(data[pay_status]==7){
         message_error="订单支付已撤销"
       }else if(data[pay_status]==8){
         message_error="订单已退款"
       }
       this.setData({
         message_error
       })
        //异常
        Dialog.confirm({
         title: '温馨提示',
         showCancelButton:false,
         selector:"#myPayDialog"
       }).then(() => {
        if(order_type==1){
          wx.redirectTo({
            url: '/patient/pages/orderDetail/orderDetail?order_inquiry_id='+data.order_id+ "&fromType=list",
          })
        }else if(order_type==2){
          wx.redirectTo({
            url: '/patient/pages/medinceOrderDetail/medinceOrderDetail?order_product_id='+data.order_id+ "&fromType=" +encodeURIComponent("patient/pages/medinceOrder/medinceOrder"),
          })
        }else if(order_type == 4 || order_type == 5){
            wx.redirectTo({
                url: '/healthyService/pages/healthyOrderDetail/healthyOrderDetail?order_service_id=' + data.order_no + "&fromType=" + +encodeURIComponent("healthyService/pages/healthyOrder/healthyOrder"),
              })
          }else{
          wx.redirectTo({
            url: '/sugarCheck/pages/checkOrderDetail/checkOrderDetail?order_detection_id='+data.order_no+ "&fromType=" +encodeURIComponent("sugarCheck/pages/checkOrder/checkOrder"),
          })
        }
        
       })
      }
     
    })
  },
  goPay() {
    this.wxPay();
  },
  handleThrottle: throttle(function () {
    this.goPay()
  }),
  noPayGo(){
    let {
      order_inquiry_id,
      order_type,
      order_product_id,
      order_detection_id,
      fromType
    } = this.data;
    if (order_type == 2) {
      wx.redirectTo({
        url: '/patient/pages/medinceOrderDetail/medinceOrderDetail?order_product_id=' + order_product_id + "&fromType=" + fromType,
      })
    }else if(order_type == 3){
      wx.redirectTo({
        url: '/sugarCheck/pages/checkOrderDetail/checkOrderDetail?order_detection_id=' + order_detection_id + "&fromType=" + fromType,
      })
    }else {
      wx.redirectTo({
        url: '/patient/pages/orderDetail/orderDetail?order_inquiry_id='+ order_inquiry_id+ "&fromType=" + fromType,
      })
    }
  },
  goByType() {
    let {
      chat_id,
      inquiry_type,
      order_inquiry_id,
      order_type,
      order_id,
      order_no,
      order_product_id,
      order_detection_id,
      fromType
    } = this.data;
    
    if (order_type == 2) {
      wx.redirectTo({
        url: '/patient/pages/medinceOrderDetail/medinceOrderDetail?order_product_id=' + order_product_id + "&fromType=" + fromType,
      })
    }else if(order_type == 3){
      wx.redirectTo({
        url: '/sugarCheck/pages/checkOrderDetail/checkOrderDetail?order_detection_id=' + order_detection_id + "&fromType=" + fromType,
      })
    }else if(order_type == 4 || order_type == 5){
        wx.redirectTo({
          url: '/healthyService/pages/healthyOrderDetail/healthyOrderDetail?order_service_id=' + order_no + "&fromType=" + fromType,
        })
      }else {
      // 订单类型（1:专家问诊 2:快速问诊 3:公益问诊 4:问诊购药）
      if (inquiry_type == 1) {
        app.method.navigateTo({
          url: '/TUIService/pages/index?currentConversationID=' + chat_id + "&order_inquiry_id=" + order_inquiry_id + "&inquiry_type=1&fromType=" + fromType
        })
      } else if (inquiry_type == 2) {
        wx.redirectTo({
          url: '/patient/pages/allotDoctor/allotDoctor?inquiry_type=2&order_inquiry_id=' + order_inquiry_id + "&order_id=" + order_id + "&fromType=" + fromType
        })
      } else if (inquiry_type == 3) {
        app.method.navigateTo({
          url: '/TUIService/pages/index?currentConversationID=' + chat_id + "&order_inquiry_id=" + order_inquiry_id + "&inquiry_type=3&fromType=" + fromType
        })
      } else if(inquiry_type == 4) {
        wx.redirectTo({
          url: '/patient/pages/allotDoctor/allotDoctor?inquiry_type=4&order_inquiry_id=' + order_inquiry_id + "&order_id=" + order_id + "&fromType=" + fromType
        })
      }
    }

  },
  wxPay() {
    let {
      timeStamp,
      nonceStr,
      signType,
      paySign
    } = this.data.pay_config;
    let {
      order_type,
      inquiry_type,
    } = this.data;
    let THIS = this;
    let mypackage = this.data.pay_config.package;
    isLock=false;
    wx.requestPayment({
      timeStamp: timeStamp,
      nonceStr: nonceStr,
      package: mypackage,
      signType: signType,
      paySign: paySign,
      success(res) {
        wx.showToast({
          title: '成功',
          icon: "none"
        });
        THIS.setData({
          paySucess:true
        })

      },
      fail(res) {
        wx.showToast({
          title: '支付失败',
          icon: 'none'
        })
      },
      complete(res) {
        //处方到期通知 处方支付提醒 两个长期订阅任意一个订阅后才才调用前两个
        if (res.errMsg == "requestPayment:ok") {
          if(!isLock){
            isLock=true;
            THIS.goByType();
          }
         
        } else {
          console.log("失败")
        }

      }
    })
  },
  handleThrottleBack: throttle(function () {
    this.goback()
  }, 1000),
  goback() {
    wx.navigateBack({
      delta: 1,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.fromType) {
      this.setData({
        fromType: options.fromType
      })
    }

    //处方订单
    if (options.order_type == 2) {
      this.setData({
        order_type: options.order_type,
        order_no: options.order_no,
        inquiry_type: '',
        order_product_id: options.order_product_id
      })

    }else if(options.order_type==3){//检测订单
      let order_detection_id = options.order_detection_id;
      this.setData({
        order_type: 3,
        inquiry_type: '',
        order_no: options.order_no,
        order_detection_id
      })

    }else if(options.order_type==4){//随访包订单
        this.setData({
            order_type: 4,
            doctor_id: options.doctor_id,
            inquiry_type:options.inquiry_type,
            order_no: options.order_no,
            chat_id: options.chat_id,
           inquiry_mode: options.inquiry_mode
          })
    }else if(options.order_type==5){//健康包订单
        this.setData({
            order_type:5,
            doctor_id: options.doctor_id,
            inquiry_type:options.inquiry_type,
            order_no: options.order_no,
            chat_id: options.chat_id,
           inquiry_mode: options.inquiry_mode
          })
    }else {
      //问诊相关
      this.setData({
        doctor_id: options.doctor_id,
        order_no: options.order_no,
        order_inquiry_id: options.order_inquiry_id,
        chat_id: options.chat_id,
        inquiry_type: options.inquiry_type,
        inquiry_mode: options.inquiry_mode
      })
    }
    this.payOrder();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
    wx.hideShareMenu({
      menus: ['shareAppMessage', 'shareTimeline']
    })
    this.setData({
      img_host:app.hostConfig().imghost
    })
    //isLock=false
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
      if(this.data.paySucess && !isLock){
        this.goByType();
      }   
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  //  if(!this.data.paySucess){
  //   this.noPayGo();
  //  }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})