// index.js
// 获取应用实例
const app = getApp();
import {homeData} from "../../api/index.js"
import{delDoctor} from "../../api/familyDoc"
import {popup} from "../../api/common"
import {setBarData,throttle} from "../../utils/util"
let urlHost=app.hostConfig().agreehost;
Page({
  data: {
    show:false,
    showCode:false,
    isOld:false,
    codeMsg:'',
    active:0,
    showEntryTip:false,
    showEntryTip_second:false,
    beforeClose(action){
      return new Promise((resolve) => {
        if (action === 'confirm') {
          resolve(true);
        } else {
          // 拦截取消操作
          resolve(false);
        } 
    })
  },
    showAlert:false,
    showIntro:false,
    banner:[],
    recommend_doctor:[],
    my_doctor:[],
    module:[],
    delId:'',
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static',
    popupData:null
  
  },
  onChange(event){
      console.log(event.detail.name)
   this.setData({
       active:event.detail.name
   })
  },
  confirm:throttle(function(event){
    if(event.detail){
      this.handelDelDoctor();
    }
  }),
  goH5:throttle(function(event){
      if(!this.isHasToken()){
         wx.reLaunch({
           url: '/patient/pages/login/login',
         })
         return 
      }
    let {url,name,type,title}=event.currentTarget.dataset;
    if(url.indexOf("http")!=-1){
     let urlName=(decodeURIComponent(url))
     if(this.verifySuffix(urlName)){
       wx.navigateTo({
         url:'/'+url+'&name='+encodeURIComponent(name)
       })
     }else{
      app.method.navigateTo({
        url:"/patient/pages/linkPage/linkPage?url="+encodeURIComponent(url)
      })
     }
     
    }else{
        if(type==4){
            app.method.navigateTo({
                url:'/'+url+'?title='+title
              })
         }else{
            wx.navigateToMiniProgram({
                appId: 'wxdee7006582529713',
                path:url,
                envVersion: 'release',
                success(res) {
                  // 打开成功
                }
              })
         }
      
    }
   
  }),
  verifySuffix(fileName) {
   let suffix = `(bmp|jpg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp|jpeg)`
    let regular = new RegExp(`.*\.${suffix}`)
    return regular.test(fileName)
  },
  handlePopup(){
    popup({
      popup_type:2
    }).then(data=>{
     if(data.length!=0){
       this.setData({
        popupData:data[0].popup_content
       });
       if(data[0].popup_content.hasOwnProperty("inquiry_type")){
        this.setData({
         isOld:false
        })
       }else{
        this.setData({
          isOld:true
         })
       }
       let showFuli=wx.getStorageSync('showFuli');
       console.log("showFuli"+showFuli)
       if(!showFuli){
          this.setData({
            show:true
          });
       }
     }
    })
  },
  handelDelDoctor(){ 
    let {delId,my_doctor}=this.data;
    delDoctor(delId).then(data=>{
       for (let i = 0; i < my_doctor.length; i++) {
        if(my_doctor[i].doctor_id==delId){
            my_doctor.splice(i,1);
          this.setData({
            my_doctor:my_doctor
          })
        }
       
     }
       wx.showToast({
         title: '成功删除该医生',
         icon:"none"
       });
    })
  },
 confirmDel(event){
   let id=event.currentTarget.dataset.id;
    this.setData({
      showAlert:true,
      delId:id
    })
 },
  handleMyDoctor(){
    myDoctor({
      my_doctor_type:1,
      page:1,
      per_page:3
    }).then((data)=>{
       let result=data.data;
       this.setData({
        my_doctor:result
      })
    })
  },
  goMydoctor:throttle(function(){
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
     
        app.method.navigateTo({
            url: '/patient/pages/myDoctor/myDoctor',
          })
     
  
  }),
  
  onConfirmEntry(){
    //wx.setStorageSync('hasEntry', true);
    this.setData({
      showEntryTip:false
    })
    wx.showTabBar({
      animation: true
    })
  },
  onCloseEntry(){
    this.setData({
      showEntryTip_second:true,
      showEntryTip:true
    })
    
  },
  onConfirmEntry_second(){
    this.setData({
      showEntryTip_second:false,
      //showEntryTip:false,
    });
    //wx.setStorageSync('hasEntry', true);
    // wx.showTabBar({
    //   animation: true
    // })
  },
  onCloseEntry_second(){
     wx.showTabBar({
       animation: true
     });
     this.setData({
      showEntryTip_second:false,
      showEntryTip:false,
    });
     wx.exitMiniProgram({success: (res) => {}})
   },
  goAgreement:throttle(function(event){
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
    let id=event.currentTarget.dataset.id;
    app.method.navigateTo({
      url:"/patient/pages/linkPage/linkPage?url="+encodeURIComponent(urlHost+'/basic/file/agreement.htm?id='+id)
    })
  }),
  goCheck:throttle(function(){
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
    // let that=this;
    // wx.scanCode({
    //   onlyFromCamera: true,
    //   scanType:['qrCode','barCode','datamatrix','pdf417'],
    //   success (res) {
    //     const reg=/^SD[A-Z]{2}\d{2}[A-Z]\d{5}$/
    //    if(res.result.test(reg)){
    //     that.setData({
    //       codeMsg:res.result,
    //       showCode:true
    //     })
    //    }
        
    //   }
    // })
    app.method.navigateTo({
      url: '/sugarCheck/pages/sugarDetail/sugarDetail',
    })
  }),
  goMall:throttle(function(){
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
    wx.navigateToMiniProgram({
      appId: 'wxdee7006582529713',
      path:"/pages/home/dashboard/index",
      envVersion: 'release',
      success(res) {
        // 打开成功
      }
    })
  }),
  freeConsult:throttle(function(){
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
    app.method.navigateTo({
      url: '/patient/pages/expertConsult/expertConsult?type=free'
    })
  }),
  handleFocus:throttle(function(event){
    wx.hideKeyboard();
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
     if(event.detail){
      app.method.navigateTo({
            url: '/patient/pages/search/search',
          })
     }
  }),
 
  goExpertDetail:throttle(function(event){
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
    let id=event.currentTarget.dataset.id;
   app.method.navigateTo({
     url: '/patient/pages/expertDetail/expertDetail?doctor_id='+id
   })
  }),
  goquickExpert:throttle(function(){
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
    app.method.navigateTo({
      url:'/patient/pages/expertConsult/expertConsult' //'/patient/pages/quickConsult/quickConsult'
    })
  }),
  goExpertAndCloseOld:throttle(function(){
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
    app.method.navigateTo({
      url:'/patient/pages/expertConsult/expertConsult'
    })
    this.onClickHide();
  }),
  goExpertAndClose:throttle(function(event){
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
    let id=event.currentTarget.dataset.id;
    let url='';
    if(id==1){
      url='/patient/pages/index/expertConsult'
    }else if(id==2){
      url='/patientpages/quickConsult/quickConsult'
    }else if(id==3){
      url='/patient/pages/expertConsult/expertConsult?type=free'
    }else if(id==4){
      url='/patient/pages/quickConsult/quickConsult?inquiry_type=4'
    }else if(id==5){
      url='/sugarCheck/pages/sugarDetail/sugarDetail'  
    }
    if(id!==6){
      app.method.navigateTo({
        url:url                        //'/pages/expertConsult/expertConsult'
      })
    } 
    this.onClickHide();
  }),
  goExpert:throttle(function(){
    //   wx.showToast({
    //     title: '敬请期待',
    //     icon:'none'
    //   })
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
    app.method.navigateTo({
      url: '/patient/pages/hivConsult/hivConsult'
    })
  }),
  goconsultandbuy:throttle(function(){
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
       app.method.navigateTo({
      url: '/patient/pages/expertConsult/expertConsult?type=buyYao'
    })
    // app.method.navigateTo({
    //   url: '/patient/pages/quickConsult/quickConsult?inquiry_type=4'
    // })
   
  }),
  goHealth:throttle(function(){
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
    app.method.navigateTo({
       url: '/healthyService/pages/healthyIntro/healthyIntro'
    })
}),
goVisit:throttle(function(){
    if(!this.isHasToken()){
        wx.reLaunch({
          url: '/patient/pages/login/login',
        })
       
     }
    app.method.navigateTo({
       url: '/healthyService/pages/visitList/visitList'
    })
}),
  watchBack(){
    let total=app.globalData.totalUnread;
    setBarData(total)
   },
  onClickHide() {
    this.setData({ show: false });
    wx.showTabBar();
    wx.setStorageSync('showFuli',true);
  },
  getData(){
    homeData().then((data)=>{
      let result=this.data;
     for (const key in data) {
        this.setData({
           [key]:data[key]
        })
     };
    
    })
  },
  closeIntro(){
  this.setData({
    showIntro:false
  });
  wx.showTabBar({
    animation: true,
  });
  wx.setStorageSync('hasIntro',true)
  },
  onLoad(options) {
      console.log("index onload");
     if(options.doctor_id){
        if(!this.isHasToken()){
            wx.reLaunch({
              url: '/patient/pages/login/login',
            })
           
         }
       wx.redirectTo({
        url: '/patient/pages/expertDetail/expertDetail?doctor_id='+options.query.doctor_id,
      })
     }
   
    this.setData({
      beforeClose: this.data.beforeClose.bind(this),
  })
    wx.removeTabBarBadge({
      index:1
    });
    //this.handleMyDoctor();
  },
  isHasToken(){
    let token='';
    const { envVersion } = wx.getAccountInfoSync().miniProgram;
    if(envVersion=='release'){
      token = wx.getStorageSync('AUTH_TOKEN');
    }else{
      token = wx.getStorageSync('DEV_AUTH_TOKEN');
    }
    if(token){
        return true
    }else {
        return false;
    }
  },
  onShow(){
   let isIntro=wx.getStorageSync('hasIntro');
   //let isEntry=wx.getStorageSync('hasEntry');
   app.watch(this.watchBack.bind(this))//注册监听
   this.setData({
    img_host:app.hostConfig().imghost
  });
   if(!isIntro){
     this.setData({
      showIntro:true,
     });
     wx.hideTabBar({
      animation: true
    })
   };
 
  //  if(!isEntry){
  //   this.setData({
  //     showEntryTip:true
  //    });
  //    wx.hideTabBar({
  //     animation: true
  //   })
  //  }else{
  //   this.setData({
  //     showEntryTip:false
  //    });
  //    wx.showTabBar({
  //     animation: true
  //   })
  //  }
    this.getData();
    this.handlePopup();
    app.globalData.origion=0;
   
    if(!app.globalData.totalUnread && app.globalData.totalUnread!=0){
        if(this.isHasToken()){
            app.imLogin();
        }
     
    }else{
      let total=app.globalData.totalUnread;
      setBarData(total)
    }
    wx.getPrivacySetting({
      success: res => {
        console.log(res)
        if (res.needAuthorization) {
          // 需要弹出隐私协议
          this.setData({
            showEntryTip:true
          })
          wx.hideTabBar({
            animation: true
          })
        } else {
          this.setData({
            showEntryTip:false
          })
          wx.showTabBar({
            animation: true
          })
  
        }
      },
      fail: () => {},
      complete: () => {}
    })
 
  },
  onShareTimeline(){
    return {
      title: '肝胆相照互联网医院，复诊购药一站式服务',
      query: '/pages/index/index'
    }
  },
  onShareAppMessage() {
    return {
      title: '肝胆相照互联网医院，复诊购药一站式服务',
      path: '/pages/index/index'
    }
  }
  


})
