// pages/sugarDetail/sugarDetail.js
const app = getApp()
import {throttle} from "../../../utils/util"
import {family,addfamily} from "../../../api/familyDoc";
import {getProject,hasCreate} from "../../../api/checkSugar"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static',
    showdialog:false,
    cancelBtn:false,
    messageTitle:'',
   opacity:0,
   nation_id:'',
   nation_name:'',
   show:false,
   projectImg:'',
   detection_project_id:1,
   idCard:'',
   relation:'',
   phoneNumber:'',
   card_name:'',
   realName:'',
   showAdd:false,
   currentName:'',
   age:"",
   currentFamilyId:'',
   showPicker:false,
   family:[],
   columns: [{
    text: "本人",
    value: 1
  },
  {
    text: "父母",
    value: 2
  },
  {
    text: "爱人",
    value: 3
  },
  {
    text: "子女",
    value: 4
  },
  {
    text: "亲戚",
    value: 5
  },
  {
    text: "其他 ",
    value: 6
  }
]
  },
  onConfirmPicker(event) {
    const {value} = event.detail;
    this.setData({
      relationId: `${value.value}`,
      relation: `${value.text}`,
      showPicker: false
    });
  },

  openPicker() {
    this.setData({
      showPicker: true
    })
  },
  closePicker() {
    this.setData({
      showPicker: false
    })
  },
  addPatient(){
    this.setData({
      showAdd:true,
      currentFamilyId:"",
      sex:""
    })
  },
  onCloseAdd() {
    this.setData({
      showAdd: false
    });
  },
  onClose(){
    this.setData({
      show:false
    })
  },
  showPatient(){
  this.setData({
    show:true
  })
  },
  onConfirm(event) {
    const { value} = event.detail;
    this.setData({
      relationId: `${value.value}`,
      relation:`${value.text}`,
      showPicker:false
    });
  },
  inputChange(e){
    this.setData({
      [e.target.dataset.id]: e.detail.value
  })
  },
  handelGetProject(){
    let {detection_project_id}=this.data;
    getProject(
      detection_project_id
    ).then(data=>{
      this.setData({
        projectImg:data.img_path
      })
    })
  },
  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,
      })
    }
  },
  handleHasCreate(){
    let {currentFamilyId,sex,currentName,detection_project_id,age,nation_id,nation_name}=this.data;
    hasCreate({
      family_id:currentFamilyId,
      detection_project_id:detection_project_id
    }).then(data=>{
      if(data){
        this.setData({
          showdialog:true,
          messageTitle:"当前患者存在进行中检测订单",
          order_detection_id: data,
          cancelBtn:true
        })
      }else{
        let cur_nation_id=nation_id?nation_id:'';
        let cur_nation_name=nation_name?nation_name:'';
        app.method.navigateTo({
          url: '/sugarCheck/pages/sugarSickInfo/sugarSickInfo?family_id='+currentFamilyId+"&real_name="+currentName+"&detection_project_id="+detection_project_id+"&sex="+sex+"&age="+age+"&nation_id="+cur_nation_id+"&nation_name="+cur_nation_name
        })
      }
    })
  },

  //获取身份证号信息
  getIdInfo(IdCard){
    var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if(reg.test(IdCard)){
		let sex
        if (parseInt(IdCard.substr(16, 1)) % 2 === 1) {
			sex = '1'
		} else {
			sex = '2'
		}
		var ageDate = new Date()
		var month = ageDate.getMonth() + 1
		var day = ageDate.getDate()
		var age = ageDate.getFullYear() - IdCard.substring(6, 10) - 1
		if (IdCard.substring(10, 12) < month || (IdCard.substring(10, 12) === month && IdCard.substring(12, 14) <= day)) {
			age++
		}
		if (age <= 0) {
			age = 1
		}
		return { sex, age}
	}else{
        return false;
    }
},
  addFamily(){
    let {realName,idCard,phoneNumber,relationId}=this.data;
    addfamily({
      card_name:realName,
      type:1,
      id_number:idCard,
      mobile:phoneNumber,
      is_default:0,
      relation:relationId    
    }).then((data)=>{
      this.getFamily();
      this.setData({
        currentFamilyId:data.family_id,
        realName:'',
        idCard:'',
        phoneNumber:'',
        relationId:'',
        showAdd:false,
        relation:'',
        show:true
      })
    })
  },
  selectPatient(e){
    const {familyid,sex,card_name,age,nation,nation_name}=e.currentTarget.dataset;
     this.setData({
        currentFamilyId:familyid,
        sex:sex,
        nation_name:nation_name,
        age:age,
        nation_id:nation,
        currentName:card_name
     })
  },
  getFamily(){
    family().then((data)=>{
      this.setData({
        family:this.transforpage(data)
      })
    })
  },
  transforpage(arr) {
    const pages = []
    let newArr=arr.concat([{
      type:"add"
    }])
    newArr.forEach((item, index) => {
      const page = Math.floor(index / 2)
      if (!pages[page]) {
        pages[page] = []
      }
      pages[page].push(item)
    });
    return pages
  },
  goBack(){
    console.log("origion:"+app.globalData.origion)
    if(app.globalData.origion==1){
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }else if(app.globalData.origion==2){
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }else{
      wx.navigateBack({
        delta: 1,
        fail:function(){
          wx.reLaunch({
            url: '/pages/index/index',
          })
        }
      })
    }
  
  },
  handleThrottleSick:throttle(function(){

    this.goSick()
  }),
  goSick(){
    
    if (!/^([\u4e00-\u9fa5\·]{2,10})$/.test(this.data.realName)) {
      wx.showToast({
        title: `姓名要求在2-10个汉字`,
        icon: 'none',
      });
      return false;
    };
    if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(this.data.idCard)){
      wx.showToast({
        title: `请输入有效的身份证号`,
        icon: 'none',
      });
      return false;
    };
    if(this.data.phoneNumber){
      if(!/^1[3456789]\d{9}$/.test(this.data.phoneNumber)){
        wx.showToast({
          title: `请输入有效的手机号码！`,
          icon: 'none',
        });
        return false;    
      }
    };
    let idInfo=this.getIdInfo(this.data.idCard);
     if(idInfo.age<6){
      wx.showToast({
        title: `六岁以下儿童不支持线上问诊`,
        icon: 'none',
      });
      return false;  
     }
   
     this.setData({
       sex:idInfo.sex,
       age:idInfo.age,
       nation_id:'',
       nation_name:'',
       currentName:this.data.realName
     })
    this.addFamily();
  
  },
  onPageScroll: function(e) {
    let opacity=0;
    if(e.scrollTop/(86*2)>=1){
      opacity=1
    }else{
      opacity=e.scrollTop/(86*2)
    }
    this.setData({
      opacity:opacity
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      img_host:app.hostConfig().imghost
    }); 
    this.handelGetProject();
    this.getFamily()
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

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

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // }
})