// pages/expertDetail/expertDetail.js
const app = getApp()
import {
  doctorDetail,
  doctorService,
  isReceivepatient,
  commentList,
  fllowDoctor,
  notfllowDoctor,
  doctorList
} from "../../../api/consultExpert"
import {throttle} from "../../../utils/util"
Page({
  /**
   * 页面的初始数据
   */
  data: {
    toView:'item0',
    tab3Height:500,
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static',
    showDialog:false,
    currentData:0,
    avatar: '',
    register_cert:'',
    user_name: '',
    doctor_title: '',
    doctor_id: '',
    doctor_title_name:'',
    user_id:'',
    is_online:'0',
    avg_response_time: 0,
    be_good_at: '',
    department_custom_name: '',
    served_patients_num: 0,
    number_of_fans: 0,
    hospital: null,
    canTuwen:false,
    canVideo:false,
    canDiffcult:false,
    canHealthy:false,
    canVisit:false,
    healthyPrice:'',
    visitPrice:'',
    brief_introduction:'',
    multi_point_status: 0,
    multi_point_enable:0,
    iden_auth_status:0,
    is_img_expert_reception: 0,
    is_img_welfare_reception: 0,
    days: 0,
    praise_rate: 0,
    doctor_inquiry_config: [],
    doctor_expertise: [],
    value: 3,
    show: false,
    isHide: false,
    current_inquiry_config: null,
    inquiry_type:'',
    inquiry_mode:'',
    follow: false,
    id:'',
    restNumber:0,//剩余名额
    expertInquiry_price:'',
    freePrice:'',
    freeAmount:0,
    expertAmount:0,
    hasFree:false,
    hasExpert:false,
    recieveStatus:0,
    commentList: [],
    hasVideoList:false,
   
    totalComment:0,
    isFinished:false,
    isReceivePatient:false, //是否可接诊
    service_content:'【医生填写的服务内容】',
    service_process:'【医生填写的服务流程】',
    cycle:'',
    rounds:''
  },
  getHeight(id){
      console.log("id:"+id);
    wx.createSelectorQuery().select('#swiperitem'+id).boundingClientRect( (rect)=>{
        this.setData({
            tab3Height:(rect.height)
        })
       
      }).exec()
  },
  handleThrottle:throttle(function(e){
    let {type}=e.currentTarget.dataset;
    this.goSelectPatient()
  }),
 
  goVideo:throttle(function(){
    app.method.navigateTo({
        url:'/patient/pages/videoList/videoList'
    })
  }),
  previewImg(){
      let {register_cert}=this.data;
    wx.previewImage({
        current: 'register_cert', // 当前显示图片的http链接
        urls: [register_cert] // 需要预览的图片http链接列表
      })
  },
  goSelectPatient() {
   
    //判断是否能接诊
    this.handleIsReceivepatient();
  },
  showPop() {
    this.setData({
      show: true
    })
  },
  goBack(){
    wx.navigateBack({
      delta: 1,
    })
  },
  toggleFllow(){
    if(this.data.follow){
      this.handenotfllowDoctor()
    }else{
      this.handelfllowDoctor()
    }
  },
  notAsk(e){
    let {type}=e.currentTarget.dataset
   wx.showToast({
     title:type==0?'该医生暂不就诊':'该问诊暂未开通',
     icon:"none"
   })
  },
  
bindchange(e){
  const that  = this;
  that.setData({
      currentData: e.detail.current
  })
},
 goVisit:throttle(function(){
     let doctorid=this.data.doctor_id;
     if(this.data.canVisit){
         app.method.navigateTo({
            url:'/healthyService/pages/visitDetail/visitDetail?doctor_id='+doctorid
        })
     }else{
          app.method.navigateTo({
            url:'/healthyService/pages/visitList/visitList'
        })
     }
    
  }),
  goHealthy:throttle(function(){
     let doctorid=this.data.doctor_id;
     let price=this.data.healthyPrice;
     if(this.data.canHealthy){
          app.method.navigateTo({
                url:'/healthyService/pages/healthyDetail/healthyDetail?doctor_id='+doctorid+"&price="+price
            })
     }else{
         app.method.navigateTo({
                url:'/healthyService/pages/healthyIntro/healthyIntro'
            })
     }
       
  }),
  switchTab(e){
   let {id}=e. currentTarget.dataset;
   this.setData({
     currentData:Number(id)
   })
   if(id==0){
    this.getHeight(1)
       this.setData({
         inquiry_type:this.data.current_inquiry_config.inquiry_type,
         inquiry_mode:this.data.current_inquiry_config.inquiry_mode  
       })
     
   }else if(id==1){
    this.setData({
        inquiry_type:1,
        inquiry_mode:9,
        tab3Height:0
      })
      this.goVisit();
   }else if(id==2){
    this.setData({
        inquiry_type:1,
        inquiry_mode:8,
        tab3Height:0
      })
      this.goHealthy();
   }else if(id==3){
    this.getHeight(4);
    let {hasVideoList,canVideo}=this.data;
    this.setData({
        inquiry_type:1,
        inquiry_mode:2,
      })
      this.getVideoDoctorList();
    // if(hasVideoList && !canVideo){
    //   this.goVideo();
    //  }
   }else {
    this.getHeight(5)
    this.setData({
        inquiry_type:1,
        inquiry_mode:6
      }) 
   }
  
  },
  confirm(event) {
    let {id}=this.data;
    if (event.detail) {
      app.method.navigateTo({
        url: '/patient/pages/orderDetail/orderDetail?order_inquiry_id=' + id,
      })
    }
  },
  handleIsReceivepatient() {
    let {doctor_id,inquiry_mode,inquiry_type}=this.data;
    isReceivepatient({
      inquiry_type: inquiry_type,
      inquiry_mode: inquiry_mode,
      doctor_id: doctor_id
    }).then(data => {
      let recieveStatus=data.status;
      if (recieveStatus == 1) {
        app.method.navigateTo({
          url: '/patient/pages/selectPatient/selectPatient?chat_id='+ this.data.user_id+"&doctor_id="+this.data.doctor_id+"&inquiry_type="+ inquiry_type+"&inquiry_mode="+inquiry_mode
        })
      } else if (recieveStatus == 2) {
        this.setData({
          showDialog: true,
          id: data.data.order_inquiry_id
        })
    
      } else if (recieveStatus == 3) {
        wx.showToast({
          title: '当前不可问诊',
          icon: "none"
        })
      }
    
    })
  },
  handelfllowDoctor(){
    let id=this.data.doctor_id
    fllowDoctor(id).then(data=>{
      this.setData({
        follow:true
      })
       wx.showToast({
         title: '关注成功',
         icon:"none"
       })
    })
  },
  handenotfllowDoctor(){
    let id=this.data.doctor_id;
    notfllowDoctor(id).then(data=>{
      this.setData({
        follow:false
      })
       wx.showToast({
         title: '已取消关注',
           icon:"none"
       })
    })
  },
  goComment() {
    app.method.navigateTo({
      url: '/patient/pages/comment/comment?doctor_id=' + this.data.doctor_id,
    })
  },
  onClose() {
    this.setData({
      show: false
    })
  },
  getEvaluationList() {
    let {doctor_id}=this.data;
    commentList({
      doctor_id,
      evaluation_type:1,
      page: 1,
      per_page: 3
    }).then((res) => {
      this.setData({
        commentList: res.data,
        totalComment:res.total_quantity
      })
    })
  },
  loopArr(arr,type){
    let inquiry_mode='';
    let inquiry_price='';
    let recieveStatus='';
    let duration='';
    let work_num_day=0;
    let times_number=0;
    let order_inquiry_count=0;
    let order_type=type;
    for (let i = 0; i <  arr.length; i++) {
      if(arr[i].inquiry_type==type && arr[i].inquiry_mode==1 ){
        recieveStatus=arr[i].work_num_day-arr[i].order_inquiry_count;
        inquiry_mode=arr[i].inquiry_mode;
        inquiry_price=arr[i].inquiry_price;
        duration=arr[i].duration;
        work_num_day=arr[i].work_num_day;
        times_number=arr[i].times_number;
        order_inquiry_count=arr[i].order_inquiry_count;
      }
    }
     //如果公益问诊 次数为0 则去看是否有专家问诊
        if(type==3 && recieveStatus==0){
          
          for (let i = 0; i <  arr.length; i++) {
            if(arr[i].inquiry_type==1 && arr[i].inquiry_mode==1 && arr[i].is_enable==1){
              order_type=1;
              recieveStatus=arr[i].work_num_day-arr[i].order_inquiry_count;
              inquiry_mode=arr[i].inquiry_mode;
              console.log(arr[i].inquiry_price)
              inquiry_price=arr[i].inquiry_price;
              duration=arr[i].duration;
              work_num_day=arr[i].work_num_day;
              times_number=arr[i].times_number;
              order_inquiry_count=arr[i].order_inquiry_count;
            }
          }
        }
        console.log(inquiry_price)
    this.setData({
        inquiry_type:order_type,
        inquiry_mode:inquiry_mode,
        restNumber:recieveStatus,
        current_inquiry_config: {
        inquiry_type:order_type,
        inquiry_mode:inquiry_mode,
        inquiry_price:inquiry_price,
        recieveStatus:recieveStatus,
        duration,
        work_num_day,
        times_number,
        order_inquiry_count
      }
    })
  },
  hasOtherInquiry(arr){
    if(arr){
        for (var i = 0; i < arr.length; ++i) {
            if(arr[i].inquiry_type==1 && arr[i].inquiry_mode==1){
                if(arr[i].is_enable==1){
                    this.setData({
                        hasExpert:true
                    }) 
                };
               this.setData({
                expertAmount:arr[i].work_num_day-arr[i].order_inquiry_count,
                expertInquiry_price: arr[i].inquiry_price
               })
            }
            if(arr[i].inquiry_type==1 && arr[i].inquiry_mode==2){
                if(arr[i].is_enable==1){
                    this.setData({
                        canVideo:true
                    }) 
                };
                this.setData({
                    videoPrice:arr[i].inquiry_price
                })
            };
            if(arr[i].inquiry_type==1 && arr[i].inquiry_mode==6){
                if(arr[i].is_enable==1){
                    this.setData({
                        canDiffcult:true,
                      
                    })
                }
                this.setData({
                    rounds: arr[i].times_number,
                    cycle:arr[i].duration,
                    yinanPrice:arr[i].inquiry_price
                })
            }
                if(arr[i].inquiry_type==1 && arr[i].inquiry_mode==8){
                if(arr[i].is_enable==1){
                this.setData({
                    canHealthy:true
                })
            }
            this.setData({
                healthyPrice: arr[i].inquiry_price
            })
       }
       if(arr[i].inquiry_type==1 && arr[i].inquiry_mode==9){
                if(arr[i].is_enable==1){
                this.setData({
                    canVisit:true
                })
            }
            this.setData({
                visitPrice: arr[i].inquiry_price
            })
       }

        }
    }
  },
  formatInquiryStatus(arr){
    var  a='3';
    console.log(arr);
    if(arr){
      for (var i = 0; i < arr.length; ++i) {
         if(arr[i].inquiry_type==1 && arr[i].inquiry_mode==1){
             if(arr[i].is_enable==1 ){
                 this.setData({
                    hasExpert:true
                 })
                a='2';
             }
            this.setData({
                expertAmount:arr[i].work_num_day-arr[i].order_inquiry_count,
                expertInquiry_price: arr[i].inquiry_price
            })
           
        };
        if(arr[i].inquiry_type==1 && arr[i].inquiry_mode==6){
            if(arr[i].is_enable==1){
                this.setData({
                    canDiffcult:true
                })
            }
           this.setData({
              yinanPrice: arr[i].inquiry_price,
              rounds: arr[i].times_number,
              cycle:arr[i].duration
           })  
       };
       if(arr[i].inquiry_type==1 && arr[i].inquiry_mode==8){
                if(arr[i].is_enable==1){
                this.setData({
                    canHealthy:true
                })
            }
            this.setData({
                healthyPrice: arr[i].inquiry_price
            })
       }
       if(arr[i].inquiry_type==1 && arr[i].inquiry_mode==9){
                if(arr[i].is_enable==1){
                this.setData({
                    canVisit:true
                })
            }
            this.setData({
                visitPrice: arr[i].inquiry_price
            })
       }
        if(arr[i].inquiry_type==1 && arr[i].inquiry_mode==2){
            if(arr[i].is_enable==1){
                this.setData({
                    canVideo:true,
                 
                })
            }
            this.setData({
                videoPrice:arr[i].inquiry_price
            })
        };
        if(arr[i].inquiry_type==1 && arr[i].inquiry_mode==6){
            if(arr[i].is_enable==1 ){
                this.setData({
                    canDiffcult:true,
                  
                }) 
            }
            console.log(' yinanPrice:'+arr[i].inquiry_price)
            this.setData({
                yinanPrice:arr[i].inquiry_price,
                rounds: arr[i].times_number,
                cycle:arr[i].duration
            })
        }
        if(arr[i].inquiry_type==3){
            this.setData({
                freePrice:arr[i].inquiry_price,
                freeAmount:arr[i].work_num_day-arr[i].order_inquiry_count,
            })
            if(arr[i].is_enable==1){
                this.setData({
                    hasFree:true
                 })
                return '1'    
            }
         
        };
      }
   
    }
    return a
  },
  // 禁止用户滑动
  catchTouchMove() {
    //return false;
  },

  getDeatil(id) {
    doctorDetail(id).then((res) => {
      for (const key in this.data) {
        if (res[key]) {
          this.setData({
            [key]: res[key]
          })
        }
      };
  
    })
  },
  getVideoDoctorList(){
      let {canVideo}=this.data;
    doctorList({
      page:1,
      inquiry_type:1,
      inquiry_mode:2,
      per_page:10
    }).then((res)=>{
     
       if(res.data.length==0){
        this.setData({
            hasVideoList:false
        });
    
       }else{
          this.setData({
            hasVideoList:true
          })
          if(!canVideo){
               this.goVideo();
          }

       }
    })
   },
   getService(id){
    doctorService(id).then(res=>{
        let doctor_inquiry_config = res;
        let inquiryType=this.formatInquiryStatus(res);
       
        console.log("inquiryType:"+inquiryType)
        if(inquiryType==1){
         this.loopArr(doctor_inquiry_config,3);
         this.hasOtherInquiry(doctor_inquiry_config)
         this.setData({
            canTuwen:true
        });
          
        }else if(inquiryType==2){
         this.loopArr(doctor_inquiry_config,1);
         this.setData({
             canTuwen:true
         })
        }else{
         this.setData({
               current_inquiry_config:null
             })
        }
        this.setData({
           isFinished:true
         })
         for (let i = 0; i < res.length; i++) {
             if(res[i].inquiry_type==1 && res[i].inquiry_mode==6){
                 this.setData({
                    service_content: res[i].service_content ,
                    service_process:res[i].service_process 
                 })
                 break;
             }
         }
        
         
        if(this.data.canTuwen){
            this.setData({
                currentData:0,
                toView:'item0',
                inquiry_type:this.data.current_inquiry_config.inquiry_type,
                inquiry_mode:this.data.current_inquiry_config.inquiry_mode  
            })
            this.getHeight(1)
        }else{
            if(this.data.canVideo){
                let {hasVideoList,canVideo}=this.data;
                this.setData({
                    currentData:3,
                    inquiry_type:1,
                    inquiry_mode:2,
                    toView:'item3'
                  })
                  this.getVideoDoctorList();
                 this.getHeight(4)
            }else{
                if(this.data.canDiffcult){            
                    this.setData({
                        currentData:4,
                        toView:'item4',
                        inquiry_type:1,
                        inquiry_mode:6
                    }) 
                    this.getHeight(5)
                }else{ 
                    this.setData({
                    currentData:0,
                    toView:'item0'
                    })
                    this.getHeight(1) 
                }
            }
        }
    })
   },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const scene = options.scene?decodeURIComponent(options.scene):'';
    let doctor_id='';
    if(scene){
      doctor_id=scene.split('=')[1]
    }else{
      doctor_id=options.doctor_id
    };
    console.log(options)
    this.setData({
      doctor_id:doctor_id
    })
    
    this.getDeatil(doctor_id);
  
    this.getEvaluationList();
    //this.getVideoDoctorList();
   
  },

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

  },

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

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

  },

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

  },

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

  },

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

  },
  // onShareTimeline(){
  //   const {user_name,doctor_title_name,hospital,avatar,img_host,doctor_id}=this.data;
  //   return {
  //     title: '【'+ user_name +'】 '+ doctor_title_name+' '+hospital.hospital_name,
  //     imageUrl:avatar?avatar:img_host+'/doctor_avatar.png',
  //     query:'doctor_id='+doctor_id
  //   }
  // },
  onShareAppMessage() {
    const {user_name,doctor_title_name,hospital}=this.data;
    return {
      title: '【'+ user_name +'】 '+ doctor_title_name+' '+hospital.hospital_name
    }
  }
  
  /**
   * 用户点击右上角分享
   */
  
})