// healthyService/pages/healthyDetail/healthyDetail.js
import {doctorDetail} from "../../../api/consultExpert"
import {family,addfamily} from "../../../api/familyDoc";
import {getServiceDetail,createServiceChatOrder} from "../../../api/health"
import {doctorService} from "../../../api/consultExpert"
import {throttle} from "../../../utils/util"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    order_no:'',
    confirmNext:'确定',
    order_inquiry_id:'',
    chat_id:'',
    showPicker:false,
    columns:[
        {text:"本人",value:1},
        {text:"父母",value:2},
        {text:"爱人",value:3},
        {text:"子女",value:4},
        {text:"亲戚",value:5},
         {text:"其他 ",value:6}
      ],
    showWarn:false,
    status:'',
      active:0,
      img_host:app.hostConfig().imghost,
      doctor_id:'',
      currentData:0,
      inquiry_mode:8,
      inquiry_type:1,
      current_price:'',
      avatar: '',
      user_name: '',
      doctor_title: '',
      doctor_id: '',
      doctor_title_name:'',
      user_id:'',
      is_online:'0',
      hospital: null,
      multi_point_enable:'',
      multi_point_status:'',
      hospital:{},
      priceList:[],
      show:false,
      currentFamilyId:'',
      realName:'',
      idCard:'',
      phoneNumber:'',
      relationId:'',
      sex:'',
      service_type:1,
      chat_id:'',
  },
  goHasOrder(){
    let {status,doctor_id,order_no}=this.data;
    if(status==4){
        let id=this.data.order_inquiry_id;
        app.method.navigateTo({
            url: '/patient/pages/orderDetail/orderDetail?order_inquiry_id='+id,
           })
    }else if(status==2){
        let id=this.data.order_no;
        app.method.navigateTo({
            url: '/healthyService/pages/healthyOrderDetail/healthyOrderDetail?order_service_id='+id,
           })
       
    }else if(status==3){
        app.method.navigateTo({
            url:'/patient/pages/expertDetail/expertDetail?doctor_id='+doctor_id
            })
    }else if(status==5){
        this.handleCreateServiceChatOrder(order_no)
    }
},
onConfirm(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
    })
  },
  
  inputChange(e) {
    this.setData({
      [e.target.dataset.id]: e.detail.value
    })
  },
  goNext:throttle(function() {
    this.handleGetServiceDetail();
    
  }),
  addFamily() {
    let {
      realName,
      idCard,
      phoneNumber,
      relationId,
      sex
    } = 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:'',
        relation:'',
        showAdd:false
      })
     
    })
  },
  showPatient(){
    this.setData({
     show:true  
    })
   },
  addPatient() {
    this.setData({
      showAdd: true,
      currentFamilyId: '',
      sex: ''
    })
  },
  selectPatient(e) {
    let currentFamilyId=e.currentTarget.dataset.familyid;
    let sex=e.currentTarget.dataset.sex;
    let name=e.currentTarget.dataset.name;
    let age=e.currentTarget.dataset.age;
     this.setData({
       currentFamilyId:currentFamilyId,
       sex:sex
     })
  },
  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
  },
  confirmNext() {
    if (!/^[\u4e00-\u9fa5]+(·[\u4e00-\u9fa5]+)*$/.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 (!/^1[3456789]\d{9}$/.test(this.data.phoneNumber)) {
      wx.showToast({
        title: `请输入有效的手机号码！`,
        icon: 'none',
      });
      return false;
    }
  },
  getFamily() {
    family().then((data) => {
      this.setData({
        family: this.transforpage(data)
      })
    })
  },
  goSick:throttle(function() {
    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
    })
    this.addFamily()

  }),
  //获取身份证号信息
  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;
    }
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  onCloseAdd() {
    this.setData({
      showAdd: false
    });
  },
  
  getDeatil(id) {
    doctorDetail(id).then((res) => {
      for (const key in this.data) {
        if (res[key]) {
          this.setData({
            [key]: res[key]
          })
        }
      };
     this.setData({
        chat_id:res.user_id
     })
    })
  },
  handleGetServiceDetail(){
    let {doctor_id,currentFamilyId,service_type,follow_package_item_id,chat_id,sex,inquiry_mode,inquiry_type}=this.data;
  getServiceDetail({
      doctor_id,
      family_id:currentFamilyId,
      service_type,
      follow_package_item_id

  }).then((res)=>{
      if(res.status==1){
          app.method.navigateTo({
              url:'/healthyService/pages/writeSick/writeSick?doctor_id='+doctor_id+"&family_id="+currentFamilyId+"&chat_id="+chat_id+"&inquiry_type="+inquiry_type+"&sex="+sex+"&inquiry_mode="+inquiry_mode+"&package_id="+follow_package_item_id
              })
      }else if(res.status==2){
          this.setData({
              showWarn:true,
              order_no:res.data.order_no,
              status:2,
              confirmNext:'确定',
              message:res.message
          })
          
      }else if(res.status==3){
          this.setData({
              showWarn:true,
              status:3,
              confirmNext:'前往',
              message:'本月问诊次数已用完，您可选择医生其他服务'
          })
      }else if(res.status==4){
          this.setData({
              showWarn:true,
              order_no:res.data.order_no,
              order_inquiry_id:res.data.order_inquiry_id,
              status:4,
              confirmNext:'确定',
              message:res.message
          })
      }else if(res.status==5){
          this.setData({
              showWarn:true,
              status:5,
              confirmNext:'前往',
              order_no:res.data.order_no,
              message:'是否使用剩余问诊次数？'
          })
         
          
      }

  })
},
  handleCreateServiceChatOrder(id){
    createServiceChatOrder(id).then(res=>{
        let order_inquiry_id=res.order_inquiry_id;
        let chat_id=this.data.chat_id;
        app.method.navigateTo({
            url: '/TUIService/pages/index?currentConversationID=' + chat_id + "&order_inquiry_id=" + order_inquiry_id + "&inquiry_type=1&fromType=chat" 
    })
  })
  },
  showPatient(){
   this.setData({
    show:true  
   })
  },
  getService(id){
    doctorService(id).then(res=>{
     for (let i = 0; i < res.length; i++) {
        if(res[i].inquiry_mode==8 && res[i].inquiry_type==1){
          this.setData({
            current_price:res[i].inquiry_price
          })
        };
         //
         
     }
       
    })
   },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
     this.setData({
        doctor_id:options.doctor_id,
     })
   
     this.getDeatil(options.doctor_id);
     this.getService(options.doctor_id);
     this.getFamily();
    
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})