// pages/medinceOrderDetail/medinceOrderDetail.js
const app = getApp()
import {detectionDetail,bindCheck,cancelCheckPay,delCheckOrder,cancelCheckOrder,checkInquiry} from "../../../api/checkSugar.js"
import {cancelPay} from "../../../api/consultOrder"
import {cancelOrder} from "../../../api/consultOrder"
import {fllowDoctor,notfllowDoctor} from "../../../api/consultExpert"
import {throttle} from "../../../utils/util"
import {getSign} from "../../../api/common"
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    order_no:'',
    time: 30 * 60 * 60 * 1000,
    showCover:true,
    isWait:true,
    cancelBtn:false,
     order:{},
     showError:false,
     pay_money:0,
    fileList:[],
    checkSatus:1,
    showCheckDialog:false,
    checkmessage:'',
    detection_bar_code:'',
    detection_code:'',
    order_detection_id:'',
    showDialog:false,
    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链接列表
    })
  },
  uploadFile(File) {
    wx.showLoading({
      title: '图片上传中...',
      mask: true
    })
    let THIS = this;
    getSign({
      user_type: 1,
      scene: 4
    }).then((resdata) => {
      let {
        accessid,
        dir,
        policy,
        signature,
        host
      } = resdata;
      let index = File.lastIndexOf("/");
      let filename = File.substring(index + 1, File.length);
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: host, // 仅为示例，非真实的接口地址
          filePath: File,
          name: 'file',
          formData: {
            OSSAccessKeyId: accessid,
            policy,
            key: dir + filename,
            signature
          },
          success(res) {
            if (res.statusCode === 204) {
              let url = host + '/' + dir + filename;
              THIS.setData({
                fileList: THIS.data.fileList.concat([url])
              })
            }
          },
          fail: err => {
            console.log(err);
          }
        });
      })
    })
  },
  upload() {
    if(this.data.fileList.length>=3){
     wx.showToast({
       title: '检测管照片最多上传3张',
       icon:"none"
     })
     return false
    };
    let THIS = this;
    wx.chooseMedia({
      count: 3-this.data.fileList.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success(res) {
        var imgList = res.tempFiles;
        var promiseFun = [];
        for (let i = 0; i < imgList.length; i++) {
          var file = imgList[i].tempFilePath;
          promiseFun.push(
            THIS.uploadFile(file)
          )
        };
        Promise.all(promiseFun).then((res) => {
          wx.showToast({
            title: '图片上传成功',
            icon: "none"
          })
          wx.hideLoading();
        });

      }
    })
  },
 
  goBack(){
    let {fromType}=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){    
        let url=decodeURIComponent(fromType);
        let goUrl='';
        if(url.indexOf('?')!=-1){
          goUrl='/'+url+"&fromType="+url;
        }else{
          goUrl='/sugarCheck/pages/checkOrder/checkOrder'
        }
        //处理聊天收到消息不及时；
        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',
          })
        }
       })
      }
    }
    
  },
  bluript(event){
    const {value}=event.detail;
    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)$/;
    let detection_status=this.data.order.detection_status;
    if(detection_status!=3){
      if(reg.test(value)){
        this.setData({
          showError:false
        })
      }else{
        this.setData({
          showError:true
        })
      }
    }
   
   
  },
  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()
    })
  }, 
  handleCheckInquiry:throttle(function(){
    let id=this.data.order.order_detection_id;
    checkInquiry(id).then(data=>{
        let {order_inquiry_id,order_no}=data.data;
         console.log(data);
       if(data.status==1){
         this.setData({
          order_inquiry_id:order_inquiry_id,
         })
        this.goChat();
       }else if(data.status==2){
         this.setData({
          showCheckDialog:true,
          order_inquiry_id:order_inquiry_id,
          checkSatus:2,
          checkmessage:'当前医生有您待支付的订单，点击“继续”将为您取消订单直接进入报告解读服务。'
         })
       }else if(data.status==3){
        this.setData({ 
          checkSatus:3,
          showCheckDialog:true,
          order_inquiry_id:order_inquiry_id,
          checkmessage:'当前医生有您待接诊的订单，点击“继续”将为您取消订单直接进入报告解读服务。'
        })
      }else if(data.status==4){
        this.setData({
          showCheckDialog:true,
         checkSatus:4,
         order_inquiry_id:order_inquiry_id,
         checkmessage:'当前医生有您接诊中的订单，点击“继续”将为您直接进入报告解读服务。'
        })
      }else if(data.status==5){
        this.setData({
            showCheckDialog:true,
           checkSatus:5,
           order_no:order_no,
           checkmessage:'存在未支付的服务包订单，点击“继续”将为您直接进入服务包订单详情。'
          })
      }
    })
  },1000),
  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)
    // })
  }),
  handleBindCheck:throttle(function(){
    let id=this.data.order.order_detection_id;
    let detection_status=this.data.order.detection_status;
    if(detection_status==3){
       wx.showToast({
         title: '您已提交，请等待结果',
         icon:"none"
       })
      return false
    }
    const {detection_bar_code,fileList}=this.data;
    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)$/;
    if(!reg.test(detection_bar_code)){
      wx.showToast({
        title: '检测码格式不正确',
        icon:"none"
      })
      this.setData({
        showError:true
      })
     return false
    }
    bindCheck(id,{
      detection_bar_code,
      detection_pic:fileList
    }).then(data=>{
      this.handleDetectionDetail();
      wx.showToast({
        title: '提交成功',
        icon:"none"
      })
    })
  }),
  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,
    })
  }),
 handleDetectionDetail(flag=false){
  let id =this.data.order_detection_id;
  detectionDetail(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,
      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:"是否确定要取消检测？"
  })
},
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();
    }else if(this.data.checkSatus==5){
        let {order_no}=this.data;
        app.method.navigateTo({
          url:  '/healthyService/pages/healthyOrderDetail/healthyOrderDetail?order_service_id='+order_no,
        })
    }
}),
handelCancelCheckOrder(flag=true){
  let id =this.data.order.order_detection_id;
  cancelCheckOrder(id).then(data=>{
    wx.showToast({
      title: '取消成功',
      icon:"none"
    })
    if(!flag){
      this.goChat();
    }
    this.handleDetectionDetail();
  })
},
handelCancelPayProduct(flag=true){
  let id =this.data.order.order_detection_id;
  cancelCheckPay(id).then(data=>{
    wx.showToast({
      title: '取消支付成功',
      icon:"none"
    })
    if(!flag){
      this.handleCheckInquiry();
    }
    this.handleDetectionDetail();
  })
},
copy(event){
  let text=event.target.dataset.text;
  wx.setClipboardData({
    data:text
  })
},
goPay:throttle(function(){
  let {order_detection_id,detection_no}=this.data.order;
  app.method.navigateTo({
    url: '/patient/pages/payOrder/payOrder?inquiry_no='+ detection_no +"&order_detection_id="+order_detection_id+"&order_type=3&fromType="+encodeURIComponent('sugarCheck/pages/checkOrder/checkOrder')
  })
}),
handelDelProduct(){
  let id =this.data.order.order_detection_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) {
    const cover=wx.getStorageSync('showCover');
    if(cover){
      this.setData({
        showCover:false
      })
    }
    if(options.fromType){
      this.setData({
        fromType:options.fromType
      })
    }
     let order_detection_id=options.order_detection_id;
     console.log(order_detection_id)
     if(order_detection_id){
       this.setData({
        order_detection_id
       });
       this.handleDetectionDetail();
     }
  },

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

  },

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

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

  },

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

  },

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

  },

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

  },

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