// pages/orderDetail/orderDetail.js
const app = getApp()
import {cancelOrder,inquiryDetail,inquiryDel,cancelPay,getRate} from "../../../api/consultOrder"
import {fllowDoctor,notfllowDoctor} from "../../../api/consultExpert"
import {assignDoctor,evaluation} from "../../../api/consult"
import {throttle} from "../../../utils/util"
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    countTime:0,
    timer:null,
    order_inquiry_id:'',
    order:null,
    showComment:false,
    show:false,
    is_evaluation:false,
    message:'',
    fromType:'',
    showPadding:false,
    prevData:'',
    comment:{},
    score:5,
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static'
  },
  openComment(){
    this.setData({
        showComment:true,
    })
  },
  onChangeContent(event) {
    this.setData({
      [comment.content]: event.detail
    })
  },
  handleEvaluation: throttle(function () {
      let{ order_inquiry_id}=this.data;
      let doctor_id=this.data.order.user_doctor.doctor_id;
    let {
      reply_quality,
      service_attitude,
      reply_progress,
      content
    } = this.data.comment;
    if (reply_quality == '') {
      wx.showToast({
        title: '请评论回复质量',
        icon: "none"
      });
      return false;
    };
    if (service_attitude == '') {
      wx.showToast({
        title: '请评论服务态度',
        icon: "none"
      });
      return false;
    };
    if (content == '') {
      wx.showToast({
        title: '请填写您对医生的印象',
        icon: "none"
      });
      return false;
    };
    if (reply_progress == '') {
      wx.showToast({
        title: '请评论回复速度',
        icon: "none"
      });
      return false;
    };
    evaluation({
      order_inquiry_id,
      doctor_id:doctor_id,
      reply_quality,
      service_attitude,
      reply_progress,
      content,
    }).then(data => {
      this.setData({
        showComment: false,
        is_evaluation:true
      });
    
      wx.showToast({
        title: '评价成功',
        icon: "none"
      })
    })
  }),
  handleClose() {
    this.setData({
        showComment:false
    })
  },
  onChange(event) {
      let obj='comment.'+event.target.dataset.id
    this.setData({
      [obj]: event.detail
    });
    let {
      reply_quality,
      service_attitude,
      reply_progress
    } = this.data.comment;
    if (reply_quality && service_attitude && reply_progress) {
      let score = (reply_quality * 0.4) + (service_attitude * 0.3) + (reply_progress * 0.3);
      this.setData({
        score: Math.floor(score)
      })
    }
  },
  //获取星级评价
  handleGetRate(id) {
    getRate(id).then(data => {
      let commentDetail = null;
      if (data) {
        commentDetail = data
        this.setData({
            is_evaluation:true,
            score:data.avg_score
        })
      } else {
        commentDetail = {
          avg_score: 5,
          content: "感谢您的服务",
          evaluation_id: "",
          reply_progress: 5,
          reply_quality: 5,
          service_attitude: 5
        }
        this.setData({
            is_evaluation:false,
        })
       
      }
      this.setData({
        comment:commentDetail
    })
    })
  },
  copy(event){
    let text=event.target.dataset.text;
    wx.setClipboardData({
      data:text,
      fail(err){
        console.log(err);
      }
    })
  },
  goBack(flag=true){
   let {fromType,prevData}=this.data;
   if(app.globalData.origion==1){
    wx.reLaunch({
      url: '/pages/index/index',
    })
  }else if(app.globalData.origion==2){
    wx.reLaunch({
      url: '/pages/index/index',
    })
  }else{
    if(fromType){
      wx.redirectTo({
        url: '/patient/pages/consultOrder/consultOrder?fromType='+fromType+"&prevData="+prevData,
      })
     }else{
       if(flag){
        wx.navigateBack({
          delta:1,
          fail:function(){
           wx.reLaunch({
             url: '/pages/index/index',
           })
         }
        })
       }
       
     }
  }
  },
  orderMsg(){
    wx.requestSubscribeMessage({
      tmplIds: ['82rKSdbKkbFK_tHmIMnHyfyRJq9ujvmAsTjRHdxmCdE'],
      success (res) { 
        Dialog.confirm({
          title: '温馨提示',
          confirmButtonOpenType:'contact',
          message: '立即联系客服',
        }).then(() => {
            // on confirm
          }).catch(()=>{
            
          })
      }
    })

   
  },
    //联系客服通知
  

    // 下拉刷新的事件

  // handleThrottle:throttle(function(){
  //     this.goApplyMedince()
  // }),
   confirm:throttle(function(event){
    if(event.detail && this.data.message=="您是否确定删除本条订单记录？"){
      this.handleinquiryDel();
    };
    if(event.detail && this.data.message=="您是否确认取消本次问诊？"){
      this.handelCancelOrder()
    };
    if(event.detail && this.data.message=="您是否确认取消本次支付？"){
      this.handleCancelPay();
    };
    if(event.detail && this.data.message=="已经为您匹配到医生，是否跳转到聊天页面？"){
      this.goChat();
    } 
  }),
  goExpert(){
    let id=this.data.order.user_doctor.doctor_id;
   app.method.navigateTo({
     url: '/patient/pages/expertDetail/expertDetail?doctor_id='+id,
   })
  },
  toggleFllow(){
    if(this.data.order.user_doctor.follow){
      this.handenotfllowDoctor()
    }else{
      this.handelfllowDoctor()
    }
  },
  //定时发送请求
  reqCount(order_id){
    let {countTime}=this.data;
    var timer = setInterval(() => {
      if(countTime>=5*60*1000){
        clearInterval(this.data.timer);
      }
      this.setData({
        countTime:countTime+3000
      })
      this.handelAssignDoctor(order_id);
    }, 3000);
    this.setData({
      timer: timer
    })
  },
  handelAssignDoctor(id) {
    assignDoctor(id).then(data => {
      if (data.user_id) {
        this.setData({
          chat_id: data.user_id,
          doctor_id: data.doctor_id,
          show:true,
          message:"已经为您匹配到医生，是否跳转到聊天页面？"
        });
        this.handleinquiryDetail();
        let {timer} = this.data;
        clearInterval(timer);
      }

    })
  },
  handelfllowDoctor(){
    let id=this.data.order.user_doctor.doctor_id
    fllowDoctor(id).then(data=>{
      this.setData({
        "order.user_doctor.follow":true
      })
       wx.showToast({
         title: '关注成功',
         icon:"none"
       })
    })
  },
  handenotfllowDoctor(){
    let id=this.data.order.user_doctor.doctor_id;
    notfllowDoctor(id).then(data=>{
      this.setData({
        "order.user_doctor.follow":false
      })
       wx.showToast({
         title: '已取消关注',
         icon:"none"
       })
    })
  },
  delOrder(){
    this.setData({
      show:true,
      message:"您是否确定删除本条订单记录？"
    })
  },
  goSickInfo(event){
    let order_inquiry_id=event.currentTarget.dataset.id;
    app.method.navigateTo({
      url: '/patient/pages/sickInfo/sickInfo?order_inquiry_id='+order_inquiry_id
    })
  },
  goSickerInfo(event){
    let order_inquiry_id=event.currentTarget.dataset.id;
    app.method.navigateTo({
      url: '/patient/pages/memberDetail/memberDetail?order_inquiry_id='+order_inquiry_id
    })
  },
  handleGoPay(){
    let {
      inquiry_no,
      inquiry_type,
      inquiry_mode,
      user_id,
      order_inquiry_id
    } = this.data.order;
    let chat_id= this.data.order.user_doctor.user_id;
    let doctor_id= this.data.order.user_doctor.doctor_id
    app.method.navigateTo({
      url: '/patient/pages/payOrder/payOrder?doctor_id='+doctor_id+'&inquiry_no='+inquiry_no+"&chat_id="+chat_id+"&inquiry_type="+ inquiry_type+"&inquiry_mode="+inquiry_mode+"&order_inquiry_id="+order_inquiry_id+"&fromType=detail"
    })
  },
  confirmCancelInquiry(){
    this.setData({
      show:true,
      message:"您是否确认取消本次问诊？"
    })
  },
  handelCancelOrder(){
    let { order_inquiry_id} = this.data.order;
    cancelOrder(order_inquiry_id).then(data=>{
      wx.showToast({
        title: '取消问诊成功',
        icon:'none'
      });
      this.handleinquiryDetail(true);
    })
  },
  confirmCancelPay(){
     this.setData({
      show:true,
      message:"您是否确认取消本次支付？"
     })
  },
  handleCancelPay(){
    let {order_inquiry_id} = this.data.order;
    cancelPay(order_inquiry_id).then(data=>{
      wx.showToast({
        title: '取消支付成功',
        icon:'none'
      })
      this.handleinquiryDetail(true);
    })
  },
  handleinquiryDetail(flag=false){
    let id=this.data.order_inquiry_id;
    inquiryDetail(id).then(data=>{
     this.setData({
      order:data
     })
     if(flag){
      let pages = getCurrentPages();
      let prevPage = pages[pages.length - 2]; //上一页
      this.setData({
        prevData:JSON.stringify({
            changeStatus: data.inquiry_status,
            changeId:id       
        })
      });
       prevPage.setData({
        changeStatus: data.inquiry_status,
        changeId:id          
      });
     };
     if(data.inquiry_status==4 || data.inquiry_status==5 || data.inquiry_status==6 || data.inquiry_status==3 ){
      this.setData({
        showPadding:false
       })
     }else{
      this.setData({
        showPadding:true
       })
   
     };
     if(data.inquiry_status==2){
       this.handelAssignDoctor(data.order_inquiry_id);
       this.reqCount(data.order_inquiry_id);
     }
    })
  },
  handleinquiryDel(){
    let id=this.data.order_inquiry_id;
    inquiryDel(id).then((data)=>{
         wx.showToast({
           title: '订单删除成功',
           icon:"none"
         });
         if(app.globalData.origion==1){
          this.handleinquiryDetail();
        }else if(app.globalData.origion==2){
          this.handleinquiryDetail();
        }else{
          let pages = getCurrentPages();
          //获取所需页面
          let prevPage = pages[pages.length - 2]; //上一页
          prevPage.setData({
            delId: id//需要传过去的数据
          });
          let {fromType}=this.data;
          if(fromType){
           wx.redirectTo({
             url: '/patient/pages/consultOrder/consultOrder',
           })
          }else{
            wx.navigateBack({
              delta:1,
            })
          }
        }
       
        
    })
  },
  goChat(){
    let chat_id=this.data.order.user_doctor.user_id;
    let {order_inquiry_id,inquiry_type}=this.data.order;
    app.method.navigateTo({
      url: '/TUIService/pages/index?currentConversationID='+chat_id+"&order_inquiry_id=" + order_inquiry_id + "&inquiry_type=" + inquiry_type
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
   if(options.fromType){
    this.setData({
      fromType:options.fromType
    })
   }
    this.setData({
      order_inquiry_id:options.order_inquiry_id
    });
    this.handleinquiryDetail();
    this.handleGetRate(options.order_inquiry_id)
  },

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

  },

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

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.timer);
    //this.goBack(false)
  },

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

  },

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

  },

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