// pages/sugarSickInfo/sugarSickInfo.js
import {nation} from "../../../api/common"
import {getLocation,getDiseaseList,getDoctorList,createDetection,getPurposeList,getProject,getArea} from "../../../api/checkSugar"
import {getProvince,getCity,getCountry} from "../../../api/consultExpert"
import {throttle} from "../../../utils/util"
import Dialog from '@vant/weapp/dialog/dialog';
import {client_type} from "../../../utils/isPc"
let wait_time=15;

const beforeClose = (action) =>
  new Promise((resolve) => {
    console.log(action,wait_time);
     try {
      if (action === 'confirm' && wait_time<=0) {
        resolve(true);
      }else if (action === 'cancel') {
        resolve(true);
      }else {
        // 拦截取消操作
        resolve(false);
      }
     } catch (error) {
       
     }
  });
const app = getApp();
let provinceArr=[{area_id:'', area_name: "全国"}];
let cityArr=[];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showSick:false,
    showNation:false,
    showDoctor:false,
    currentPatientName:'',
    showNationSelect:false,
    showCity:false,
    confirmtext:"同意",
    currentPosition:"全国",
    detection_project_id:1,
    sick_name:'',
    real_name:'',
    doctor_name:'',
    nation_name:'',
    nation_id:'',
    purpose_id:'',
    purpose_name:'',
    confirmColor:"#bfbfbf",
    nationcolumns:[],
    sickList:[],
    sex:"",
    age:'',
    showAgree:false,
    messageAgree:'',
    doctorList:[],
    timer:null,
    doctorResult:'',
    select_doctor_id:'',
    showdialog:false,
    order_detection_id:'',
    messageTitle:"",
    cancelBtn:false,
    columns: [{
      values: [],
      className: 'column1',
    },
    {
      values: [],
      className: 'column2',
      defaultIndex: 1,
    },
    {
      values: [],
      className: 'column3',
      defaultIndex: 1,
    }
  ],
    sickResult:[],
    disease_ids:[],
    area:{
      province_id:'',
      city_id:'',
      county_id:''
    },
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static'
  },
  cancelAgree(){
    this.setData({
      showAgree: false
    })
  },
 
  confirmAgree(event){
    if (event.detail ) {
      this.setData({
        showAgree: false
      })
    }
  },
  cancelAlert(){
    this.setData({
      showdialog: false
    })
  },
  confirm(event) {
    if (event.detail) {
      this.setData({
        showdialog: false
      })
    }
    if(this.data.messageTitle=="当前患者存在进行中检测订单"){
      let {order_detection_id}=this.data;
      app.method.navigateTo({
        url: '/sugarCheck/pages/checkOrderDetail/checkOrderDetail?order_detection_id='+ order_detection_id,
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      family_id:options.family_id,
      real_name:options.real_name,
      sex:options.sex,
      age:options.age,
      nation_id:options.nation_id,
      nation_name:options.nation_name,
      detection_project_id:options.detection_project_id
    })
    // {{real_name}}（{{sex==1?'男':'女'}} | {{age}}岁 {{showNationSelect?" | "+nation_name:''}}）
    let sex=options.sex==1?'男':'女';
    if(options.nation_id){
      this.setData({
        currentPatientName:options.real_name+"（"+sex+" | "+options.age+"岁 | "+options.nation_name+"）",
        showNationSelect:false
      })
    }else{
      this.setData({
        currentPatientName:options.real_name+"（"+sex+" | "+options.age+"岁"+"）",
        showNationSelect:true
      })
    }

    this.handelGetProject();
    this.handleWxLocation();
    this.getNation();
    this.handlegetDiseaseList();
    this.handleGetPurposeList();
  },
  handleWxLocation(){
    let that=this;
    try {
      wx.getFuzzyLocation({
        type: 'gcj02',
        success (res) {
          if(res.errMsg=='getFuzzyLocation:ok'){
            const latitude = res.latitude;
            const longitude = res.longitude;
            that.handleGetLocation(longitude,latitude);
          }
         
        },
        fail(err){
          console.log(err)
          console.log("获取位置信息失败")
          that.handleGetDoctorList();
        }
       })
    } catch (error) {
      
    }
   
  },
  goAgree(){
    let {detection_project_id}=this.data;
    app.method.navigateTo({
     url:'/patient/pages/agreement/agreement?detection_project_id='+detection_project_id
    })
  },
  handelGetProject(){
    let {detection_project_id}=this.data;
    getProject(
      detection_project_id
    ).then(data=>{
      this.setData({
        nodes:data.informed_consent_form
      })
    })
  },
  handleCreateDetection:throttle(function(){
   
    let {nation_id,doctorResult,sickResult,real_name,purpose_id,showNationSelect,disease_ids,timer}=this.data;
    let detection_disease_class_ids='';
    sickResult.forEach((item)=>{
       if(!detection_disease_class_ids){
        detection_disease_class_ids+=item
       }else{
       detection_disease_class_ids+=","+item
       }
    })
    if(!real_name){
      wx.showToast({
        title:"请输入真实姓名",
        icon:"none"
      });
      return false
    };
    if(!nation_id && showNationSelect){
      wx.showToast({
        title:"请选择民族",
        icon:"none"
      });
      return false
    };
    if(disease_ids.length==0){
      wx.showToast({
        title:"请选择既往病史",
        icon:"none"
      });
      return false
    };
    if(!purpose_id){
      wx.showToast({
        title:"请选择目的",
        icon:"none"
      });
      return false
    };
    if(!doctorResult){
      wx.showToast({
        title:"请选择申请医生",
        icon:"none"
      });
      return false
    };
    wait_time=15;
    this.setData({
      confirmColor:wait_time==0?"#3CC7C0":"#bfbfbf"
    });
    Dialog.confirm({
      title: '知情同意书',
      width:'710rpx',
      message: '弹窗内容',
      selector:"#agreeDialog",
      confirmButtonText	:wait_time==0?"同意":"同意("+wait_time+"S)",
      beforeClose:beforeClose,
    }).then(() => {
       this.goPay();
      // on confirm
    }).catch(() => {
      console.log("none")
      // on cancel
    });
    if(this.data.timer){
      clearInterval(this.data.timer);
    };
    let timerSetInterval=setInterval(()=>{
   
       if(wait_time<=1){
         clearInterval(timer);
         wait_time=0;
         this.setData({
            waitTime:0,
           confirmColor:"#3CC7C0",
           confirmtext:"同意",
          })
          return false
       }
       wait_time--;
       
      this.setData({
        confirmtext:"同意("+wait_time+"S)",
      })
    },1000)
    this.setData({
      timer:timerSetInterval
    })

  }),
  goPay:throttle(function(){
    let {family_id,nation_id,detection_project_id,doctorResult,sickResult,purpose_id}=this.data;
    let detection_disease_class_ids='';
    sickResult.forEach((item)=>{
       if(!detection_disease_class_ids){
        detection_disease_class_ids+=item
       }else{
       detection_disease_class_ids+=","+item
       }
    })
    createDetection({
      company_id:1,
      patient_id:wx.getStorageSync('CLIENT_USER_ID'),
      family_id,
      doctor_id:doctorResult,
      nation_id,
      purpose_id,
      detection_disease_class_ids,
      detection_project_id,
      client_type:client_type
    }).then(data=>{
      if(data.status==1){
        app.method.navigateTo({
          url: '/patient/pages/payOrder/payOrder?&inquiry_no=' + data.data.inquiry_no + "&order_detection_id="+ data.data.order_no+"&order_type=3&fromType="+encodeURIComponent('sugarCheck/pages/checkOrder/checkOrder')
        })
      }else if(data.status==2){
        this.setData({
          showdialog:true,
          messageTitle:"当前患者存在进行中检测订单",
          order_detection_id: data.data.order_no,
          cancelBtn:true
        })
      }
    })
  }),
  onChangeSick(event) {
    console.log(event.detail)
    let result=event.detail;
    this.setData({
      sickResult:result ,
    });
    const {sickList}=this.data;
    for (let i = 0; i < sickList.length; i++) {
      let temp="sickList["+i+"].check";
      if(result.indexOf(sickList[i].id)!==-1){
         this.setData({
          [temp]:true
         })
      }else{
        this.setData({
          [temp]:false
         })
      }
    }
    //console.log(sickList);
   
  },
  onChangeDoctor(event) {
   // console.log(event)
    this.setData({
      doctorResult: event.detail,
    });
  },
  showNation() {
    this.setData({
      showNation: true
    })
  
},
onCancelNation() {
  this.setData({
    showNation: false
  })
},
onConfirmNation(event) {
  const {
    value
  } = event.detail;
  this.setData({
   "nation_name": `${value.nation_name}`,
   "nation_id": `${value.nation_id}`,
   showNation: false
  })
},
openPurpose(){
  this.setData({
    showPurpose: true
  })
},
onConfirmPurpose(event) {
  const {
    value
  } = event.detail;
  this.setData({
   "purpose_name": `${value.purpose_name}`,
   "purpose_id": `${value.purpose_id}`,
   showPurpose: false
  })
},
onCancelPurpose(){
  this.setData({
    showPurpose: false
  })
},
getNation(){
  nation().then(data=>{
      this.setData({
        nationcolumns:data
      })
  })
},
handleGetArea(){
  getArea().then(data=>{
    console.log('获取地址')
    console.log(data)
    let position ='';
    if(data.province || data.city || data.county){
      position=data.province+data.city+data.county
    }else{
      position="全国"
    }
     this.setData({
       area:data,
       currentPosition:position
     })
     this.handleGetDoctorList();
  })
},
handleGetLocation(lon,lat){
  getLocation({
    lon,
    lat
  }).then(data=>{
    this.handleGetArea();
    
  })
},
handleGetPurposeList(){
  getPurposeList().then(data=>{
    this.setData({
      purposecolumns:data
    })
  })
},
handlegetDiseaseList(){
  getDiseaseList({
    detection_project_id:1
  }).then(data=>{
    //let arr=[];
    data.forEach(item=>{
      item.check=false;
    })
    this.setData({
      sickList:data
    })
  })
},
handleGetDoctorList(){
  const {area}=this.data;
  const postData={
    company_id:1,
    province_id:area.province_id,
    city_id:area.city_id,
    county_id:area.county_id
  }
  getDoctorList(postData).then(data=>{
    this.setData({
      doctorList:data
    })
  })
},
toggleSick(event) {
  
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxessick-${index}`);
    checkbox.toggle();
  },
  onClickDcotor(event){
    const {name,userid,doctorname,hospital} = event.currentTarget.dataset;
    console.log(userid,name)
    this.setData({
      doctorResult: name,
      doctor_name:doctorname+"（"+hospital+"）",
      showDoctor:false
    });
  },
  noop() {},
  onConfirmSick() {
    let {sickResult,sickList}=this.data;
    this.setData({
      showSick: false,
      disease_ids:sickResult
    });
    let sick_name="";
    sickList.forEach((item)=>{
      if(sickResult.indexOf(item.id)!=-1){
         if(!sick_name){
          sick_name+=item.name;
         }else{
          sick_name+=" | "+item.name
         }
      }
    })
  this.setData({
    sick_name
  }) 
  },
  closeDoctor(){
    this.setData({
      showDoctor: false
    })
  },
  openCity(){
    this.provinceList()
    this.setData({
      showCity:true
    })
  },
  openSick() {
    this.setData({
      showSick: true
    })
  },
  openDoctor(){
    this.setData({
      showDoctor:true
    })
  },
  closeSick() {
    this.setData({
      showSick: false
    })
  },
  provinceList(){
    getProvince().then((res)=>{
       provinceArr= provinceArr.concat(res);
      let province=[{area_id:'', area_name: "全国"}];//
       for (let i = 0; i < res.length; i++) {
        province.push(res[i]);   
       };
       this.setData({
        'columns[0].values':province
      })
      //this.cityList(province[0].area_id);

    })
  },
  cityList(area_id){
    getCity({
      area_id:area_id
    }).then((res)=>{
     
      cityArr=res;
      let city=[];
      for (let i = 0; i < res.length; i++) {
         city.push(res[i]);   
       };
       this.setData({
        'columns[1].values':city,
        // 'area.county_id':res[0].area_id
      })
      this.countryList(res[0].area_id);  
    })
  },
  countryList(area_id){
    getCountry({
      area_id:area_id
    }).then((res)=>{
      let area=[];
      for (let i = 0; i < res.length; i++) {
        area.push(res[i]);   
       };
       this.setData({
        'columns[2].values':area,
        isLoding:false
      })
    })
  },
  onConfirm(event) {
    const {value} = event.detail;
    let currentPosition=''
    for (let index = 0; index < value.length; index++) {
      if(!value[0].area_id){
        currentPosition="全国";
        this.setData({
          area:{
            province_id:'',
            city_id:'',
            county_id:'',
            province:'',
            city:'',
            county:''
          }
        })
      }else{
          currentPosition+=value[index].area_name;
        if(index===0){
          this.setData({
            'area.province_id':value[index].area_id
          })
        }else if(index==1){
          this.setData({
            'area.city_id':value[index].area_id,
          })
        }else if(index==2){
         this.setData({
          'area.county_id':value[index].area_id
         })
        }
    }
  }
    this.setData({
      currentPosition:currentPosition,
      showCity: false
    });
    console.log(this.data.area);
    this.handleGetDoctorList();
  },
  onChangePicker(event) {
    const { picker, value, index } = event.detail;
   if(index===0){
      let currentIndex=picker.getIndexes()[0];
      if(provinceArr[currentIndex].area_id){
        this.cityList(provinceArr[currentIndex].area_id);
      }else{
        this.setData({
         'columns[1].values':[],
         'columns[2].values':[]
        })
      }
   }
  },
  onCancel() {
    this.setData({
      showCity: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

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

    clearInterval(this.data.timer);
    // this.setData({
    //   sickResult:[],
    //   doctorResult:''
    // })
  },

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

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

  },

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

  },

})