const app = getApp()
const dayjs = require("../../../utils/dayjs.min");
import {
  pay,
  lingyuanpay
} from "../../../api/consult"
import {
  payPrescription
} from "../../../api/prescription"
import Dialog from '@vant/weapp/dialog/dialog';
import {inquiryDetail} from "../../../api/consultOrder"
import {productDetail} from "../../../api/medinceOrder"
import {
  throttle
} from "../../../utils/util"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    doctor_id: '',
    chat_id: '',
    message_error:'',
    showOrderMsg:false,
    showMsgOrder:false,
    time: '',
    canPay:true,
    inquiry_no: '',
    amount_total: "",
    discount_amount:'',
    cannot_use_coupon_reason:'',
    coupon_amount_total: 0,
    logistics_fee: 0,
    payment_amount_total: '',
    pay_config: null,
    created_at: "",
    inquiry_type: "",
    order_type: 1,
    inquiry_mode: "",
    order_inquiry_id: "",
    order_id: "",
    order_no: "",
    address_id: '',
    product_ids: [],
    order_detection_id:'',
    order_service_id:'',
    order_product_id: '',
    fromType: '',
    showDing:false,
    isLock:false
  },
  goBack() {
    if (app.globalData.origion == 1) {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    } else if (app.globalData.origion == 2) {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    } else {
      // this.setData({
      //   showDing:true,
      // });
      Dialog.confirm({
          title: '温馨提示',
          cancelButtonText: "确定离开",
          confirmButtonText: '继续支付',
          selector:"#mydialog"
        }).then(() => {
          this.setData({
            showMsgOrder:true
          })
          //this.goPayPlatform();
        })
        .catch(() => {
          let {
            order_product_id,
            order_inquiry_id,
            order_type,
            order_detection_id,
            order_service_id,
            fromType
          } = this.data;
          console.log( order_type, order_service_id)
          if (order_type == 1) {
            if (fromType) {
              if (fromType == "detail") {
                wx.navigateBack({
                  delta: 1,
                })
              } else {
                wx.redirectTo({
                  url: '/patient/pages/orderDetail/orderDetail?order_inquiry_id=' + order_inquiry_id + "&fromType=list",
                })
              }

            } else {
              wx.navigateBack({
                delta: 1,
                fail:function(){
                  wx.reLaunch({
                    url: '/pages/index/index',
                  })
                }
              })
            }
          }else if(order_type==3){
            
            if (fromType) {
              wx.redirectTo({
                url: '/sugarCheck/pages/checkOrderDetail/checkOrderDetail?order_detection_id=' + order_detection_id + "&fromType=" + fromType,
              })
            } else {
              wx.navigateBack({
                delta: 1,
              })
            }
          }else if(order_type==4 || order_type==5){
            if (fromType) {
                wx.redirectTo({
                  url: '/healthyService/pages/healthyOrderDetail/healthyOrderDetail?order_service_id=' + order_service_id + "&fromType=" + fromType,
                })
              } else {
                wx.navigateBack({
                  delta: 1,
                })
              }
          }else {
            if (fromType) {
              wx.redirectTo({
                url: '/patient/pages/medinceOrderDetail/medinceOrderDetail?order_product_id=' + order_product_id + "&fromType=" + fromType,
              })
            } else {
              wx.navigateBack({
                delta: 1,
              })

            }
          }
        });

    }


  },
  onCloseMsg(){
    this.goUrl();
  },
  onConfirmMsg(){
    this.goPayPlatform();
  },
  // onConfirm(){
  //   this.goPayPlatform();
  // },
  onClose(){
       let {
            order_product_id,
            order_inquiry_id,
            order_type,
            fromType,
            order_detection_id
          } = this.data;
          if (order_type == 1) {
            if (fromType) {
              if (fromType == "detail") {
                wx.navigateBack({
                  delta: 1,
                })
              } else {
                wx.redirectTo({
                  url: '/patient/pages/orderDetail/orderDetail?order_inquiry_id=' + order_inquiry_id + "&fromType=list",
                })
              }
            } else {
              wx.navigateBack({
                delta: 1,
                fail:function(){
                  wx.reLaunch({
                    url: '/pages/index/index',
                  })
                }
              })
            }
          }else if(order_type==3){
            if (fromType) {
              wx.redirectTo({
                url: '/sugarCheck/pages/checkOrderDetail/checkOrderDetail?order_detection_id=' + order_detection_id + "&fromType=" + fromType,
              })
            } else {
              wx.navigateBack({
                delta: 1,
              })
            }
          } else {
            if (fromType) {
              wx.redirectTo({
                url: '/patient/pages/medinceOrderDetail/medinceOrderDetail?order_product_id=' + order_product_id + "&fromType=" + fromType,
              })
            } else {
              wx.navigateBack({
                delta: 1,
              })
            }
          }

  },
  handleThrottle:throttle(function() {
    if(!this.data.canPay){
        wx.showToast({
          title: '订单异常',
          icon:'none'
        })
        return false;
    }
   if(!this.data.isLock){
       this.goPayPlatform();
     this.setData({
       isLock:true
     });
     
   }
   
  }),
  goPayPlatform() {
    this.orderMsg(this.goUrl);
  },
  goUrl(){
    let {
      order_no,
      order_type,
      chat_id,
      doctor_id,
      payment_amount_total,
      inquiry_type,
      inquiry_mode,
      order_inquiry_id,
      order_product_id,
      order_detection_id,
      order_prescription_id,
      fromType
    } = this.data;
    if (payment_amount_total == 0) {
       this.freePay();
    } else {
      this.setData({
        isLock:false
      })
      let url = '';
      if (order_type == 2) {
        url = '/patient/pages/payPlatform/payPlatform?order_no=' + order_no + "&order_type=2" + "&order_prescription_id=" + order_prescription_id + "&order_product_id=" + order_product_id + "&fromType=" + fromType;
      }else if(order_type == 3){//糖组检测
        url = '/patient/pages/payPlatform/payPlatform?order_no=' + order_no + "&order_type=3" + "&order_detection_id=" + order_detection_id+ "&fromType=" + fromType;
      }else if(order_type == 4){//随访包
        url = '/patient/pages/payPlatform/payPlatform?order_no=' + order_no + "&order_type=4&chat_id=" + chat_id + "&doctor_id" + doctor_id + "&inquiry_type=" + inquiry_type + "&inquiry_mode=" + inquiry_mode + "&fromType=" + fromType;
      }else if(order_type == 5){//健康包
        url = '/patient/pages/payPlatform/payPlatform?order_no=' + order_no + "&order_type=5&chat_id=" + chat_id + "&doctor_id" + doctor_id + "&inquiry_type=" + inquiry_type + "&inquiry_mode=" + inquiry_mode + "&fromType=" + fromType;
      }else {
        if (chat_id) {
          url = '/patient/pages/payPlatform/payPlatform?order_no=' + order_no + "&order_type=1&chat_id=" + chat_id + "&doctor_id" + doctor_id + "&inquiry_type=" + inquiry_type + "&inquiry_mode" + inquiry_mode + "&order_inquiry_id=" + order_inquiry_id + "&fromType=" + fromType;
        } else {
          url = '/patient/pages/payPlatform/payPlatform?order_no=' + order_no + "&order_type=1&inquiry_type=" + inquiry_type + "&inquiry_mode=" + inquiry_mode + "&order_inquiry_id=" + order_inquiry_id + "&fromType=" + fromType;
        }
      }
      app.method.navigateTo({
        url: url
      })
    }
  },
  payOrder() {
    let {
      order_no,
      order_type
    } = this.data;
    pay({
      order_type: order_type,
      order_no: order_no
    }).then((result) => {
     console.log(result)
      let data=result.data;
      //订单成功
      if(result.status==1){
        for (const key in data) {
          this.setData({
            [key]: data[key]
          })
        };
        if(order_type==3){
          this.setData({
            order_detection_id:data.order_no
          })
        }else if(order_type==4 || order_type==5){
            this.setData({
                order_service_id:data.order_no
              })
           
        }
        
        let {
          created_at
        } = data;
        let endtime = dayjs(created_at).add(30, 'minute').format('YYYY-MM-DD HH:mm:ss');
        let nowtime = dayjs().format('YYYY-MM-DD HH:mm:ss');
        let countdown = dayjs(endtime).diff(nowtime, "millisecond");
  
        this.setData({
          time: countdown > 0 ? countdown : 0
        });
        if (countdown <= 0) {
          let {
            order_product_id,
            order_inquiry_id,
            order_detection_id,
            order_type,
            fromType,
            order_service_id
          } = this.data;
          if (order_type == 1) {
            if (fromType) {
              if (fromType == "detail") {
                wx.navigateBack({
                  delta: 1,
                })
              } else {
                wx.redirectTo({
                  url: '/patient/pages/orderDetail/orderDetail?order_inquiry_id=' + order_inquiry_id + "&fromType=list",
                })
              }
  
            } else {
              wx.navigateBack({
                delta: 1,
              })
            }
          }else if(order_type == 3){
            if (fromType) {
              wx.redirectTo({
                url: '/sugarCheck/pages/checkOrderDetail/checkOrderDetail?order_detection_id=' + order_detection_id + "&fromType=" + fromType,
              })
            } else {
              wx.navigateBack({
                delta: 1,
              })
  
            }
          }else if(order_type == 4 || order_type == 5){
            if (fromType) {
                wx.redirectTo({
                  url: '/healthyService/pages/healthyOrderDetail/healthyOrderDetail?order_service_id=' + order_service_id + "&fromType=" + fromType,
                })
              } else {
                wx.navigateBack({
                  delta: 1,
                })
    
              }
          }else {
            if (fromType) {
              wx.redirectTo({
                url: '/patient/pages/medinceOrderDetail/medinceOrderDetail?order_product_id=' + order_product_id + "&fromType=" + fromType,
              })
            } else {
              wx.navigateBack({
                delta: 1,
              })
  
            }
          }
        }
      }else if(result.status==2){
        //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(order_type==1){
        //   order_status='inquiry_status';
        //   pay_status='inquiry_pay_status'
        // }else if(order_type==3){
        
        // }else{
        //   order_status='order_product_status';
        //   pay_status='pay_status'
        // }
        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:"#hasPayDialog"
        }).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==3){
            wx.redirectTo({
              url: '/sugarCheck/pages/checkOrderDetail/checkOrderDetail?order_detection_id='+data.order_no+ "&fromType=" +encodeURIComponent("sugarCheck/checkOrder/checkOrder"),
            })
          }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 if(result.status==3){
       this.setData({
        message_error:'当前有问诊中的订单，结束后才可购买'
       })
       Dialog.confirm({
        title: '温馨提示',
        showCancelButton:false,
        selector:"#hasPayDialog"
      }).then(() => {
        wx.redirectTo({
            url: '/patient/pages/orderDetail/orderDetail?order_inquiry_id='+data.order_id+ "&fromType=list",
          })
      })
      }
     
    }).catch(error=>{
        if(error.code==500){
            this.setData({
                canPay:false
            })
        };
       
    })
  },
  orderMsg(callback){
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    let {
      order_type,
      inquiry_type
    } = this.data;
    let THIS=this;
    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        let item = res.subscriptionsSetting.itemSettings;
        //console.log(res.subscriptionsSetting)
        if (order_type == 1 || order_type == 4 || order_type == 5) { //问诊异常提醒 长期订阅                          
          let tmplIds_longtime = ['UOMww1S30Oq7rErJrqO8wN6lNEVKRo2fgcXnb0tBwHI', '9v6dZhjg09CttLd3W9nEUV_-eshNc4BYYNy59jglvZE']; //问诊提醒长期订阅 
          if (!item || !item['UOMww1S30Oq7rErJrqO8wN6lNEVKRo2fgcXnb0tBwHI'] ||(item['UOMww1S30Oq7rErJrqO8wN6lNEVKRo2fgcXnb0tBwHI'] != "accept") && (item['9v6dZhjg09CttLd3W9nEUV_-eshNc4BYYNy59jglvZE'] != "accept")  || !item['9v6dZhjg09CttLd3W9nEUV_-eshNc4BYYNy59jglvZE']) {
            THIS.subscription(tmplIds_longtime,callback)
            // wx.requestSubscribeMessage({
            //   tmplIds: tmplIds_longtime,
            //   complete(res) {
            //     callback();
            //   }
            // })
          }else {
                                 //处方支付提醒 一次性订阅                      //处方到期通知 一次性订阅
              let tmplIds = ['tMiz2aIthMikcR4qisLrFXCM3Piy-M0tkzapz-Nzp_8','NewZk53LaPtJ6BtBGORK-9lsbsrueUoBQjYHnQ6F-mM'];
              THIS.subscription(tmplIds,callback)
             
          }

        }else if(order_type==3){
          let tmplIds = ['5aJSrO8SU5rxqdB99zzl4rMVgcOTjt5mQh56cpZI1Hg','dNj3azLupP_w3j649v6lqz7je_ScqwgwFsnug6pKvyI'];
          THIS.subscription(tmplIds,callback);

        }else if(order_type==2) {                      //药品发货通知 一次性订阅              //购药提醒 一次性订阅  
          let tmplIds = ['YFdVxDclV1ZjhS7E4Cs0zFdshTRizERpwYdZizj_UWo',  'KjX4m_HOPT5zYuDJqE2rRopAC_QCCMqUTCGc8ElDeWQ','gQO5vhPQfdnvXtK0XnGns1XqNhQpOrXTjdl-5HWWMUw'];  
          //药品订单取消通知 一次性订阅 
          THIS.subscription(tmplIds,callback)       
        }

      }
    })
  },
  subscription(tmplIds,callback){
    let THIS=this;
    return new Promise((resolve, reject) => {
        wx.getSetting({
            withSubscriptions: true,
            success(res) {
             
                if(!res.subscriptionsSetting.mainSwitch) { // 关闭订阅消息主按钮
                    return wx.showModal({
                        title: '提示',
                        content: '您已关闭订阅消息通知，请点击“确认”按钮在设置中打开订阅通知。',
                        success: function (res) {
                            if (res.confirm) {
                                wx.openSetting({
                                    success(res) {

                                    }
                                });
                            }
                        },
                        complete(){
                          THIS.setData({
                            isLock:false
                          })
                        }
                    });
                } else { // 开放订阅消息主按钮
                    wx.requestSubscribeMessage({
                        tmplIds:tmplIds, // 需要订阅的消息模板的id的集合，一次调用最多可订阅3条消息
                        complete (res) { 
                            callback();
                            resolve()
                        }
                    })
                }
            },
            complete(){
              wx.hideLoading();

            }
        })
    })
},
  freePay() {
    let {
      order_no,
      order_type
    } = this.data;
    lingyuanpay({
      order_type: order_type,
      order_no: order_no
    }).then((data) => {
      wx.showToast({
        title: '支付成功',
        icon:"none"
      })
      this.goByType();
    

    })
    this.setData({
      isLock:false
    })
  },
  goByType() {
    let {
      chat_id,
      inquiry_type,
      order_inquiry_id,
      order_type,
      order_id,
      order_no,
      order_product_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){
      app.method.navigateTo({
        url: '/sugarCheck/pages/checkOrderDetail/checkOrderDetail?order_detection_id=' + order_detection_id +"&fromType=" + fromType
      })
  }else if(order_type == 4 || order_type == 5){
    app.method.navigateTo({
        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
        })
      }
    }

  },
  //问诊订单详情
  handleinquiryDetail(id){
    inquiryDetail(id).then(data=>{
      if(data.inquiry_pay_status==2){
        Dialog.confirm({
          title: '温馨提示',
          cancelButtonText: "确定",
          selector:"#hasPayDialog"
        }).then(() => {
          wx.redirectTo({
            url: '/patient/pages/orderDetail/orderDetail?order_inquiry_id=' +id + "&fromType=list",
          })
        })
      }
    })
  },
  //药品订单详情
  handleProductDetail(id){
    productDetail(id).then(data=>{
      if(data.inquiry_pay_status==2){
        Dialog.confirm({
          title: '温馨提示',
          cancelButtonText: "确定",
          selector:"#hasPayDialog"
        }).then(() => {
          wx.redirectTo({
            url: '/patient/pages/medinceOrderDetail/medinceOrderDetail?order_product_id=' + id + "&fromType=" +encodeURIComponent("patient/pages/medinceOrder/medinceOrder"),
          })
        })
      }
    })
  },
  //获取处方支付信息
  handlepayPrescription(id) {
    payPrescription(id).then(data => {
      this.setData({
        amount_total: data.amount_total,
        coupon_amount_total: data.coupon_amount_total,
        logistics_fee: data.logistics_fee,
        payment_amount_total: data.payment_amount_total
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      console.log(options)
    //fromType list跳问诊订单列表页，处方过来的是链接，跳链接页 ,chat是问诊过来
    if (options.fromType) {
      this.setData({
        fromType: options.fromType
      })
    };
   
    //处方订单
    if (options.order_type == 2) {
      let order_prescription_id = options.order_prescription_id;
      this.setData({
        order_type: 2,
        inquiry_type: '',
        order_no: options.inquiry_no,
        order_product_id: options.order_product_id,
        order_prescription_id: order_prescription_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.inquiry_no,
        order_detection_id
      })

    }else if(options.order_type==4){//随访包订单
        let order_service_id=options.order_service_id;
        this.setData({
            order_type: 4,
            doctor_id: options.doctor_id,
            inquiry_type:options.inquiry_type,
            order_no: options.inquiry_no,
            chat_id: options.chat_id,
            order_service_id:order_service_id?order_service_id:'',
           inquiry_mode: options.inquiry_mode
          })
    }else if(options.order_type==5){//健康包订单
        let order_service_id=options.order_service_id;
        this.setData({
            order_type:5,
            doctor_id: options.doctor_id,
            inquiry_type:options.inquiry_type,
            order_no: options.inquiry_no,
            chat_id: options.chat_id,
            order_service_id:order_service_id?order_service_id:'',
           inquiry_mode: options.inquiry_mode
          })
    }else {
      //问诊相关
      this.setData({
        doctor_id: options.doctor_id,
        order_no: options.inquiry_no,
        order_inquiry_id: options.order_inquiry_id,
        chat_id: options.chat_id,
        inquiry_type: options.inquiry_type,
        inquiry_mode: options.inquiry_mode
      })
     
    }
    //console.log(options.inquiry_mode,options.order_type)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      img_host:app.hostConfig().imghost
    })
    this.payOrder();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setData({
        isLock:false
      });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    
  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  
})