// pages/medinceOrderDetail/medinceOrderDetail.js
const app = getApp()
import {serviceDetail,cancelCheckPay,delCheckOrder,cancelCheckOrder,serviceEquityDetail,createServiceChatOrder,checkService} from "../../../api/health"
import {cancelPay} from "../../../api/consultOrder"
import {cancelOrder} from "../../../api/consultOrder"
import {fllowDoctor,notfllowDoctor} from "../../../api/consultExpert"
import {throttle} from "../../../utils/util"

import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    confirmText:'确定',
    restProduct:0,
    columns:[],
    showMoneyDetail:true,
    status:'',
    order_no:'',
    showWarn:false,
    order_inquiry_id:'',
    messageWarn:'',
    showJuan:true,
    refund:{},
    time: 30 * 60 * 60 * 1000,
    showCover:true,
    showExpand:true,
    isWait:true,
    cancelBtn:false,
     order:{},
     equity:{},//权益
     showError:false,
     showProduct:true,
     productList:[],
     yaoList:[],
     pay_money:0,
    fileList:[],
    checkSatus:1,
    showCheckDialog:false,
    checkmessage:'',
    detection_bar_code:'',
    detection_code:'',
    order_service_id:'',
    showDialog:false,
    inquiryList:[],
    toggleList:[],
    juanList:[{
     id:1,
     name:'1、价值5元的全品类药品优惠劵2张'
    },{
        id:2,
        name:' 2、价值100元的肝胆商城优惠劵1张'
       }],
    message:'',
    fromType:'',
    user_doctor:{},
    order:{},
    patient_family_data:'',
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static'
  },
  onClickHide() {
    this.setData({ showCover: false });
    wx.setStorageSync("showCover",true);
  },
  closeError(){
    this.setData({ showError: false });
  },
  delImg(event) {
    let id = event.currentTarget.dataset.id;
    this.data.fileList.splice(id, 1);
    this.setData({
      fileList: this.data.fileList
    })
  },
  previewImage(event) {
    let id = event.currentTarget.dataset.id;
    let urls = this.data.fileList;
    wx.previewImage({
      current: urls[id], // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
  toggleDetail(){
    this.setData({
        showMoneyDetail:!this.data.showMoneyDetail
    })
  },
  toggleJuan(){
    this.setData({
        showJuan:!this.data.showJuan
    })
    let arr=[{
        id:1,
        name:'1、价值5元的全品类药品优惠劵2张'
       },{
           id:2,
           name:' 2、价值100元的肝胆商城优惠劵1张'
          }]
  if(!this.data.showJuan){
   this.setData({
       juanList:arr.slice(0,1)
   })
  }else{
    this.setData({
        juanList:arr
    })
  }
  },
 toggleExpand(){
   this.setData({
       showExpand:!this.data.showExpand
   })
   let list=this.data.toggleList;
   if(!this.data.showExpand){
    this.setData({
        inquriyList:list.slice(0,1)
    })
   }else{
     this.setData({
        inquriyList:list
     })
   } 
 },
 toggleProduct(){
    this.setData({
        showProduct:!this.data.showProduct
    })
    let list=this.data.yaoList;
    if(!this.data.showProduct){
     this.setData({
         productList:list.slice(0,1)
     })
    }else{
      this.setData({
        productList:list
      })
    } 
  },
  goApp:throttle(function(e){
   
   wx.navigateToMiniProgram({
                appId: 'wxdee7006582529713',
                path:'/pages/home/dashboard/index',
                envVersion: 'release',
                success(res) {
                  // 打开成功
                }
              })
 }),
  goWelfare:throttle(function(e){
    let {status}=e.currentTarget.dataset;
    app.method.navigateTo({
        url:'/patient/pages/myWelfare/myWelfare?status='+status
    })
 }),
 goInquiry:throttle(function(e){
    let {id}=e.currentTarget.dataset;
    app.method.navigateTo({
        url:'/patient/pages/orderDetail/orderDetail?order_inquiry_id='+id
    })
 }),
 goProduct:throttle(function(e){
    let {id}=e.currentTarget.dataset;
    app.method.navigateTo({
        url:'/patient/pages/medinceOrderDetail/medinceOrderDetail?order_product_id='+id
    })
 }),
 goHasOrder(){
  
    let status=this.data.status;
    // let {order_service_type,user_doctor,order_service_no}=this.data.order;
   
    if(status==4){
        let id=this.data.order_inquiry_id;
        app.method.navigateTo({
            url: '/patient/pages/orderDetail/orderDetail?order_inquiry_id='+id,
           })
    }else if(status==2){
        let id=this.data.order_no;
        app.method.navigateTo({
            url: '/healthyService/pages/healthyOrderDetail/healthyOrderDetail?order_service_id='+id,
           })
       
    }else if(status==1){
        let id=this.data.order_no;
        this.handleCreateServiceChatOrder(id)
    }else if(status==3){
        let doctor_id=this.data.order.user_doctor.doctor_id;
       app.method.navigateTo({
          url:'/patient/pages/expertDetail/expertDetail?doctor_id='+doctor_id
          })
    }

},
 handleCheckService:throttle(function(){
    let {order_service_no}=this.data.order;
   
    checkService(order_service_no).then((res)=>{
      if(res.status==1){
          console.log(res.data.order_no)
        this.setData({
            showWarn:true,
            status:1,
            confirmText:'前往',
            order_no:res.data.order_no,
            messageWarn:'是否使用剩余问诊次数？'
        }) 
      }else if(res.status==2){
          this.setData({
              showWarn:true,
              order_no:res.data.order_no,
              status:2,
              confirmText:'确定',
              messageWarn:res.message
          })      
      }else if(res.status==3){
        this.setData({
            showWarn:true,
            status:3,
            confirmNext:'前往',
            messageWarn:'本月问诊次数已用完，您可选择医生其他服务'
        })     
      }else if(res.status==4){
          this.setData({
              showWarn:true,
              order_no:res.data.order_no,
              order_inquiry_id:res.data.order_inquiry_id,
              status:4,
              confirmText:'确定',
              messageWarn:res.message
          })
      }

  })
}),
goXuFei:throttle(function(){
    let {order_service_type,user_doctor,amount_total}=this.data.order;
    let url=order_service_type==2?'/healthyService/pages/visitDetail/visitDetail?doctor_id='+user_doctor.doctor_id:'/healthyService/pages/healthyDetail/healthyDetail?doctor_id='+user_doctor.doctor_id
    app.method.navigateTo({
        url:url
    })
}),
handleCreateServiceChatOrder(id){
  createServiceChatOrder(id).then(res=>{
      let order_inquiry_id=res.order_inquiry_id;
      let chat_id=this.data.user_doctor.user_id;
    //   /TUIService/pages/index?currentConversationID='+currentConversationID+'&order_inquiry_id='+custom.order_inquiry_id+'&inquiry_type='+custom.inquiry_type
      app.method.navigateTo({
          url: '/TUIService/pages/index?currentConversationID=' + chat_id + "&order_inquiry_id=" + order_inquiry_id + "&inquiry_type=1&fromType=chat" 
  })
})
},
  goBack(){
     
    let {fromType}=this.data;
    console.log(fromType)
    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){    
        let url=decodeURIComponent(fromType);
        let goUrl='';
        if(url.indexOf('?')!=-1){
          goUrl='/'+url+"&fromType="+url;
        }else{
          goUrl='/healthyService/pages/healthyOrder/healthyOrder'
        }
        console.log(goUrl)
        //处理聊天收到消息不及时；
        if(url.indexOf("TUIService/pages/index")!=-1){
         app.method.navigateTo({
           url:goUrl
         })
        }else{
          wx.redirectTo({
            url:  goUrl
          })
        }
      
      }else{
       wx.navigateBack({
         delta: 1,
         fail:function(){
          wx.reLaunch({
            url: '/pages/index/index',
          })
        }
       })
      }
    }
    
  },
  handelServiceEquityDetail(id){
    serviceEquityDetail(id).then(res=>{
      let package_product=res.order_service_package_product;
      console.log(res.order_inquiry);
      this.setData({
        equity:res,
        inquriyList:res.order_inquiry,
        toggleList:res.order_inquiry,
        productList:res.order_product,
        yaoList:res.order_product,
        restProduct:package_product.length>0?package_product[0].quantity-package_product[0].used_quantity:0
      })
    })
  },
  chnageIpt(event){
    const {value}=event.detail;
     this.setData({
      detection_bar_code:value
     })
  },
  handleCancelInquiryPay(){
    let {order_inquiry_id} = this.data;
    cancelPay(order_inquiry_id).then(data=>{
      wx.showToast({
        title: '取消支付成功',
        icon:'none'
      })
      //this.handleCheckInquiry();
    })
  },
  handelCancelInquiryOrder(){
    let id=this.data.order_inquiry_id;
    cancelOrder(id).then(data=>{
      wx.showToast({
        title: '订单取消成功',
        icon:"none"
      });
      //this.handleCheckInquiry();
     // this.goChat()
    })
  }, 

  goReport:throttle(function(){
    wx.showLoading({
      mask:true,
      title: '正在打开文件...',
    });
    let url=this.data.order.detection_result_pdf;
    const randfile = new Date().getTime() + '检测报告';
    const newPath = `${wx.env.USER_DATA_PATH}/${randfile}`;
    wx.downloadFile({
      // 示例 url，并非真实存在
      url:url,
      filePath: newPath,
      success: function (res) {
        //const filePath = res.tempFilePath
        wx.openDocument({
          fileType:"pdf",
          showMenu:true,
          filePath: newPath,
          success: function (res) {
           wx.hideLoading()
            console.log('打开文档成功')
          },
          fail:function(error){
            wx.hideLoading()
            wx.showToast({
              title:res,
              icon:"none"
            })
          }
        })
      },
      fail:function(error){
        wx.showToast({
          title:error,
          icon:"none"
        })
      }
     
    })
    // app.method.navigateTo({
    //   url:"/pages/linkPage/linkPage?url="+encodeURIComponent(url)
    // })
  }),
  
  goChat:throttle(function(){
    let {user_id}=this.data.user_doctor;
    let order_inquiry_id=this.data.order.order_inquiry_id;
    let anther_order_inquiry_id=this.data.order_inquiry_id;
    let id='';
    if(!order_inquiry_id && !anther_order_inquiry_id){
      wx.showToast({
        title: '服务器错误',
        icon:'none'
      });
      return false
    };
    if(order_inquiry_id){
      id=order_inquiry_id
    }else if(anther_order_inquiry_id){
      id=anther_order_inquiry_id
    }
    app.method.navigateTo({
      url: '/TUIService/pages/index?currentConversationID=' + user_id + "&order_inquiry_id=" + id+ "&inquiry_type=5"
    })
  }),
  orderMsg(){
    wx.requestSubscribeMessage({
      tmplIds: ['82rKSdbKkbFK_tHmIMnHyfyRJq9ujvmAsTjRHdxmCdE'],
      success (res) { 
        Dialog.confirm({
          title: '温馨提示',
          confirmButtonOpenType:'contact',
          message: '立即联系客服',
        }).then(() => {
            // on confirm
          }).catch(()=>{
            
          })
      }
    }) 
  },
  goSugar:throttle(function(){
    app.method.navigateTo({
      url: '/sugarCheck/pages/sugarDetail/sugarDetail',
    })
   }),
  goExpert:throttle(function(){
    let id=this.data.user_doctor.doctor_id;
    app.method.navigateTo({
      url: '/patient/pages/expertDetail/expertDetail?doctor_id='+id,
    })
  }),
 handleServiceDetail(flag=false){
  let id =this.data.order_service_id;
  serviceDetail(id).then(data=>{
    if(flag){
      let pages = getCurrentPages();
      let prevPage = pages[pages.length - 2]; //上一页
       prevPage.setData({
        changeStatus:data.detection_status,
        changeId:id          
      });
     };
     let pay_money=(Number(data.amount_total)-Number(data.coupon_amount_total)).toFixed(2);
     this.setData({
      order:data,
      detection_bar_code:data.detection_bar_code,
      user_doctor:data.user_doctor,
      refund:data.order_refund[0],
      pay_money
     });
   
  
     if(data.detection_pic && data.detection_pic.length>0){
        this.setData({
          fileList:data.detection_pic
        })
     }
  })
},
goScan:throttle(function(){
  let that=this;
  wx.scanCode({
    onlyFromCamera: true,
    scanType:['qrCode','barCode','datamatrix','pdf417'],
    success (res) {
      const reg=/^SDB[A-Z](?:2[3-9]|2[0-2])[SP](?:1688[6-9]|1689\d|169\d\d|1[7-9]\d\d\d|[2-9][0-9]{4}|99999)$/;
      console.log(res.result);
     if(reg.test(res.result)){
      that.setData({
        detection_bar_code:res.result,
        showCode:true,
        showError:false
      })
     }else{
      that.setData({
        showDialog:true,
        cancelBtn:false,
        message:'无法识别，请手动输入检测码'
      })
     }
      
    }
  })
}),
confirmCancelOrder(){
  this.setData({
    showDialog:true,
    cancelBtn:true,
    message:"是否确定要取消订单？"
  })
},
goChat:throttle(function(){
    let user_id=this.data.order.user_id;
 app.method.navigateTo({
    url: '/TUIService/pages/index?currentConversationID=' + user_id + "&order_inquiry_id=" + id+ "&inquiry_type=1"
 })
}),
goSickInfo(event){
    let order_no=this.data.order_service_id;
    app.method.navigateTo({
      url: '/healthyService/pages/sickInfo/sickInfo?order_no='+order_no
    })
  },
confirmDelOrder(){
 this.setData({
   showDialog:true,
   cancelBtn:true,
   message:"您确定是要删除订单记录么？"
 })
},
confirmCancelPay(){
  this.setData({
    showDialog:true,
    cancelBtn:true,
    message:"您确定取消支付么？"
  })
 },
confirm:throttle(function(event){
  if(event.detail && this.data.message=="您确定是要删除订单记录么？"){
    this.handelDelProduct();
  }else if(event.detail && this.data.message=="您确定取消支付么？"){
    this.handelCancelPayProduct();
  }else if(event.detail && this.data.message=="是否确定要取消订单？"){
    this.handelCancelCheckOrder();
  }
}),
//未支付2 //待接诊需要重新请求检测订单3
confirmCheck:throttle(function(){
    if(this.data.checkSatus==2){
      this.handleCancelInquiryPay();
    }else if(this.data.checkSatus==3){
      this.handelCancelInquiryOrder();
    }else if(this.data.checkSatus==4){
       this.goChat();
    }
}),
handelCancelCheckOrder(flag=true){
  let id =this.data.order.order_service_no;
  cancelCheckOrder(id).then(data=>{
    wx.showToast({
      title: '取消成功',
      icon:"none"
    })
    this.handleServiceDetail();
    this.handelServiceEquityDetail(this.data.order_service_id)

  })
},
handelCancelPayProduct(flag=true){
  let id =this.data.order.order_service_no;
  cancelCheckPay(id).then(data=>{
    wx.showToast({
      title: '取消支付成功',
      icon:"none"
    })
    if(!flag){
      this.handleCheckInquiry();
    }
    this.handleServiceDetail();
  })
},
copy(event){
  let text=event.target.dataset.text;
  wx.setClipboardData({
    data:text
  })
},

goPay:throttle(function(){
  let {order_service_id,order_service_no,order_service_type}=this.data.order;
  let order_type=order_service_type==1?5:4;
  let inquiry_mode=order_service_type==1?9:8;
  app.method.navigateTo({
    url: '/patient/pages/payOrder/payOrder?inquiry_no='+ order_service_no +"&order_service_id="+order_service_no+"&order_type="+order_type+"&fromType="+encodeURIComponent('healthyService/pages/healthyOrder/healthyOrder')+"&inquiry_mode="+inquiry_mode
  })
}),
handelDelProduct(){
  let id =this.data.order.order_service_id;
  delCheckOrder(id).then(data=>{
    let pages = getCurrentPages();
    //获取所需页面
    let prevPage = pages[pages.length - 2]; //上一页
    prevPage.setData({
      delId: id//需要传过去的数据
    });
    wx.navigateBack({
     delta: 1,
   })
    wx.showToast({
      title: '订单删除成功',
      icon:"none"
    });
    
  })
},
goPrescriptionDetail:throttle(function(event){
  let id=event.currentTarget.dataset.id;
  app.method.navigateTo({
    url: '/patient/pages/prescriptDetail/prescriptDetail?order_prescription_id='+id,
  })
}),
handelfllowDoctor(){
  let id=this.data.user_doctor.doctor_id
  fllowDoctor(id).then(data=>{
    this.setData({
      "user_doctor.follow":true
    })
     wx.showToast({
       title: '关注成功',
       icon:"none"
     })
  })
},
handenotfllowDoctor(){
  let id=this.data.user_doctor.doctor_id;
  notfllowDoctor(id).then(data=>{
    this.setData({
      "user_doctor.follow":false
    })
     wx.showToast({
       title: '已取消关注',
       icon:"none"
     })
  })
},
toggleFllow(){
  if(this.data.order.user_doctor.follow){
    this.handenotfllowDoctor()
  }else{
    this.handelfllowDoctor()
  }
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
   
    if(options.fromType){
      this.setData({
        fromType:options.fromType
      })
    }
     let order_service_id=options.order_service_id;
     console.log(order_service_id)
     if(order_service_id){
       this.setData({
        order_service_id
       });
       this.handleServiceDetail();
      this.handelServiceEquityDetail(order_service_id)
     }
  },

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

  },

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

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

  },

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

  },

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

  },

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

  },

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