// pages/memberDetail/memberDetail.js
const app = getApp()
const dayjs=require("../../../utils/dayjs.min.js");
import {sickInfo} from "../../../api/consultOrder"
import {sickList,nation,job} from "../../../api/common"
import {getProvince,getCity,getCountry} from "../../../api/consultExpert"
import {familyDetail,editfamilyDetail,addfamily,getpersonal,addPersonal,editPersonal,getHealthy,addHealthy,editHealthy} from "../../../api/familyDoc"
import {throttle} from "../../../utils/util"
let provinceArr = [];
let cityArr = [];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static',
    isloading:false,
    show: false,
    showPicker: false,
    showNation:false,
    showJob:false,
    showSick:false,
    showCity: false,
    tab:1,
    date: '',
    sex:'',
    order: null,
    showMarital: false,
    pickercolumns: [{
        text: "本人",
        value: 1
      },
      {
        text: "父母",
        value: 2
      },
      {
        text: "爱人",
        value: 3
      },
      {
        text: "子女",
        value: 4
      },
      {
        text: "亲戚",
        value: 5
      },
      {
        text: "其他 ",
        value: 6
      }
    ],
    province_id: '',
    city_id: '',
    county_id: '',
    family_id:'',
    columns: [{
        values: [],
        className: 'column1',
      },
      {
        values: [],
        className: 'column2',
        defaultIndex: 1,
      },
      {
        values: [],
        className: 'column3',
        defaultIndex: 1,
      }
    ],
    sickcolumns:[],
    nationcolumns:[],
    jobcolumns:[],
    maritalColumn: [{
      text: '未婚',
      value: 0
    }, {
      text: '已婚 ',
      value: 1
    }, {
      text: '离异 ',
      value: 2
    }],
    hasPersonal:false, //判断个人情况有无数据；
    hasHealthy:false, //判断健康情况有无数据
    relation_name: '',
    marital_name: '',
    
    user_info: {
      name: '',
      fromtype:'',
      id_number: '',
      province_id: '',
      city_id: '',
      county_id: '',
      province:'',
      county:'',
      city: '',
      relation: '',
      mobile: '',
      height: '',
      weight: '',
      marital_status:null,
      nation_name: '',
      nation_id:'',
      job_name: '',
      job_id: '',
      is_default: 0
    },
    startIndex:3,
    personInfo: {
      family_id:'',
      family_personal_id:'',
      is_allergy_history:null,
      allergy_history:'',
      is_family_history:null,
      family_history:'',
      is_pregnant:null,
      pregnant:'',
      is_operation:null,
      operation:'',
      drink_wine_status:null,
      smoke_status:null,
      chemical_compound_status:null,
      chemical_compound_describe:''
    },
    healthyInfo:{
      family_health_id:'',
      disease_class_id:'',
      disease_class_name:'',
      diagnosis_date:'',
      diagnosis_hospital:'',
      drugs_name:'',
      is_take_medicine:null
    },
    notallowEdit: false,
    currentDate: new Date().getTime(),
    minDate: new Date('1900/01/01 00:00:00').getTime(),
    maxDate: new Date().getTime(),
    hideGuomin: false,
    hideFamilysick: false,
    hideChemical: false,
    hideOperation:false,
    hidePregnant:false,
    hideDrug:false,
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    }
  },
  onConfirmPicker(event) {
    const {
      value
    } = event.detail;
    this.setData({
      relation_name: `${value.text}`,
      'user_info.relation': `${value.value}`,
      showPicker: false
    });
  },

  openPicker() {
   if(!this.data.notallowEdit){
    this.setData({
      showPicker: true
    })
   }
  },

  getSick() {
    sickList({
      disease_class_name: ''
    }).then((data) => {
      this.setData({
        sickcolumns: data
      })
    })
  },
  goBack(){
    wx.navigateBack({
      delta: 1,
    })
  },
  onConfirmSick(event) {
    const {
      value
    } = event.detail;
    this.setData({
     "healthyInfo.disease_class_name": `${value.disease_class_name}`,
     "healthyInfo.disease_class_id": `${value.disease_class_id}`,
      showSick: false
    })
  },
  showSick() {
    this.setData({
      showSick: true
    })
  },
  onCancelSick() {
    this.setData({
      showSick: false
    })
  },
  onConfirmNation(event) {
    const {
      value
    } = event.detail;
    this.setData({
     "user_info.nation_name": `${value.nation_name}`,
     "user_info.nation_id": `${value.nation_id}`,
     showNation: false
    })
  },
  showNation() {
    if (!this.data.notallowEdit) {
      this.setData({
        showNation: true
      })
    }
   
  },
  onCancelNation() {
    this.setData({
      showNation: false
    })
  },
  onConfirmJob(event) {
    const {
      value
    } = event.detail;
    this.setData({
     "user_info.job_name": `${value.job_name}`,
     "user_info.job_id": `${value.job_id}`,
      showJob: false
    })
  },
  showJob() {
    if (!this.data.notallowEdit) {
      this.setData({
        showJob: true
      })
    }
    
  },
  onCancelJob() {
    this.setData({
      showJob: false
    })
  },
  handelFocus(e) {
    let key = e.target.dataset.id;
    let value = e.target.dataset.value;
    let obj="personInfo."+value;
    if (!e.detail.value) {
      this.setData({
        [key]: false,
        [obj]: e.detail.value
      })
    } else {
      this.setData({
        [key]: true,
        [obj]: e.detail.value
      })
    }
  },
  handleIpt(e){
     let key = e.target.dataset.id;
     let obj="user_info."+key;
     if(key=='height' || key=="weight"){
      this.setData({
        [obj]:e.detail.value
      })
     }else{
      this.setData({
        [obj]: e.detail.value
      })
     }
    
  },
  handelHealthyIpt(e){
    let key = e.target.dataset.id;
    let value=e.target.dataset.value;
    let obj="healthyInfo."+value;
    if (!e.detail.value) {
      this.setData({
        [key]: false,
        [obj]: e.detail.value
      })
    } else {
      this.setData({
        [key]: true,
        [obj]: e.detail.value
      })
    }
  },
  onChangeRadio(event) {
    let key = event.target.dataset.id;
    let obj= "personInfo."+key;
    this.setData({
       [obj]:Number(event.detail)
    });
    if(key=="chemical_compound_status" && event.detail==1){
      this.setData({
        "personInfo.chemical_compound_describe":''
      })
    }else if(event.detail==0){
       if(key=="is_allergy_history"){
         this.setData({
         "personInfo.allergy_history":'',
         hideGuomin:false
         })
       };
       if(key=="is_pregnant"){
        this.setData({
          "personInfo.pregnant":'',
           hidePregnant:false
          })
       }
       if(key=="is_family_history"){
        this.setData({
          "personInfo.family_history":'',
           hideFamilysick:false
          })
       }
    }
  },
  onChangeHealthyRadio(event) {
    let key = event.target.dataset.id;
    let obj= "healthyInfo."+key;
    this.setData({
       [obj]:Number(event.detail)
    });
    if(event.detail==0){
      this.setData({
        "healthyInfo.drugs_name":'',
        hideDrug:false
      })
    }
  },
  closePicker() {
    this.setData({
      showPicker: false
    })
  },
  openMaritalPicker() {
    if(!this.data.notallowEdit){
      this.setData({
        showMarital: true
      })
    }
   
  },
  closeMaritalPicker() {
    this.setData({
      showMarital: false
    })
  },
  onConfirmMaritalPicker(event) {
    const {
      value
    } = event.detail;
  
    this.setData({
      showMarital: false,
      marital_name:value.text,
     'user_info.marital_status':value.value
    })
  },
  onConfirm(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
  
    for (let index = 0; index < value.length; index++) {
      if (index === 0) {
        this.setData({
          "user_info.province_id": value[index].area_id,
          "user_info.province":value[index].area_name
        })
      } else if (index == 1) {
        this.setData({
          "user_info.city_id": value[index].area_id,
          "user_info.city":value[index].area_name
        })
      } else {
        this.setData({
          "user_info.county_id": value[index].area_id,
          "user_info.county":value[index].area_name

        })
      }
    }
    this.setData({
      showCity: false
    })
  },
  onChangePicker(event) {
    const {
      picker,
      index
    } = event.detail;
    if (index === 0) {
      let currentIndex = picker.getIndexes()[0]
      this.cityList(provinceArr[currentIndex].area_id);
    } else if (index === 1) {
      let currentIndex = picker.getIndexes()[1]
      this.countryList(cityArr[currentIndex].area_id);
    }

  },
  onCancel() {
    this.setData({
      showCity: false
    })
  },
  onOpenCity() {
    if (!this.data.notallowEdit) {
      this.setData({
        showCity: true
      })
    }
  },
  provinceList() {
    getProvince().then((res) => {
      provinceArr = res;
      let province = [];
      for (let i = 0; i < res.length; i++) {
        province.push(res[i]);
      };
      this.setData({
        'columns[0].values': province,
      })
      this.cityList(res[0].area_id);

    })
  },
  cityList(area_id) {
    getCity({
      area_id: area_id
    }).then((res) => {
      this.isLoding = true;
      cityArr = res;
      let city = [];
      for (let i = 0; i < res.length; i++) {
        city.push(res[i]);
      };
      this.setData({
        'columns[1].values': city
      })
      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
      })
    })
  },
  validateHealthyInfo(){
   let {is_take_medicine,drugs_name}=this.data.healthyInfo;
   if(is_take_medicine==1){
    if(!drugs_name){
      wx.showToast({
        title: `服药内容不能为空`,
        icon: 'none',
      });
      return false;
    }else if(drugs_name.length>50){
      wx.showToast({
        title: `服药内容不能超过50个字`,
        icon: 'none',
      });
      return false;
    }
   }
   return true
  },
  validatePersonInfo(){
    let {is_allergy_history,allergy_history,is_family_history,family_history,is_operation,operation,chemical_compound_status,chemical_compound_describe,is_pregnant,pregnant}=this.data.personInfo;
    if(is_allergy_history==1){
      if(!allergy_history){
        wx.showToast({
          title: `过敏史内容不能为空`,
          icon: 'none',
        });
        return false;
      }else if(allergy_history.length>50){
        wx.showToast({
          title: `过敏史内容不能超过50个字`,
          icon: 'none',
        });
        return false;
      }
    }
    if(is_family_history==1){
      if(!family_history){
        wx.showToast({
          title: `家族史内容不能为空`,
          icon: 'none',
        });
        return false;
      }else if(family_history.length>50){
        wx.showToast({
          title: `家族史内容不能超过50个字`,
          icon: 'none',
        });
        return false;
      }
    };
    if(is_pregnant==1){
      if(!pregnant){
        wx.showToast({
          title: `备孕、妊娠、哺乳期描述不能为空`,
          icon: 'none',
        });
        return false;
      }else if(pregnant.length>50){
        wx.showToast({
          title: `备孕、妊娠、哺乳期描述不能超过50个字`,
          icon: 'none',
        });
        return false;
      }
    }
    if(is_operation==1){
      if(!operation){
        wx.showToast({
          title: `手术史内容不能为空`,
          icon: 'none',
        });
        return false;
      }else if(operation.length>50){
        wx.showToast({
          title: `手术史内容不能超过50个字`,
          icon: 'none',
        });
        return false;
      }
    }
    if(chemical_compound_status!=1 && chemical_compound_status){
      if(!chemical_compound_describe){
        wx.showToast({
          title: `化合物内容不能为空`,
          icon: 'none',
        });
        return false;
      }else if(chemical_compound_describe.length>50){
        wx.showToast({
          title: `化合物内容不能超过50个字`,
          icon: 'none',
        });
        return false;
      }
    }

    return true;
  },
  validateBasicInfo() {
    let {
      name,
      id_number,
      mobile,
      height,
      weight
    } = this.data.user_info;
    // /^[\u4e00-\u9fa5]+(·[\u4e00-\u9fa5]+)*$/
  
    if (!/^([\u4e00-\u9fa5\·]{2,10})$/.test(name)) {
      wx.showToast({
        title: `姓名要求在2-10个汉字`,
        icon: 'none',
      });
      return false;
    };
    if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(id_number)) {
      wx.showToast({
        title: `请输入有效的身份证号`,
        icon: 'none',
      });
      return false;
    };
    if (mobile) {
      if (!/^1[3456789]\d{9}$/.test(mobile)) {
        wx.showToast({
          title: `请输入有效的手机号码！`,
          icon: 'none',
        });
        return false;
      }
    }
    if (height) {
      if (!/^3[5-9](\.\d+)?$|^[4-9][0-9](\.\d+)?$|^1[0-9][0-9](\.\d+)?$|^2[0-4][0-9](\.\d+)?$|250/.test(height)) {
        wx.showToast({
          title: `请输入范围内身高！`,
          icon: 'none',
        });
        return false;
      }
    };
    if (weight) {
      if (!/^[2-9](\.\d+)?$|^[1-9][0-9](\.\d+)?$|^1[0-9]{1,2}(\.\d+)?$|200/.test(weight)) {
        wx.showToast({
          title: `请输入范围内体重！`,
          icon: 'none',
        });
        return false;
      }
    }
    return true
  },
  getNation(){
    nation().then(data=>{
        this.setData({
          nationcolumns:data
        })
    })
  },
 getJob(){
    job().then(data=>{
      this.setData({
        jobcolumns:data
      })
    })
  },

  //提交基本信息
  handleBasicInfo:throttle(function() {
    let id = this.data.family_id;
    id ? this.handleEditfamilyDetail(id) : this.handleAddfamily();
  }),
  //提交个人信息
  handlePersonInfo:throttle(function() {
    let id = this.data.personInfo.family_personal_id;
    this.data.hasPersonal ? this.handleEditPerson(id) : this.handleAddPerson() 
  }),
   //提交健康情况
   handleHealthyInfo:throttle(function() {
    let id = this.data.healthyInfo.family_health_id;
    this.data.hasHealthy? this.handleEditHealthy(id) : this.handleAddHealthy() 
  }),
  handleAddfamily() {
    let {
      name,
      id_number,
      province_id,
      city_id,
      county_id,
      relation,
      mobile,
      is_default,
      height,
      weight,
      marital_status,
      nation_id,
      job_id
    } = this.data.user_info;
    if (this.validateBasicInfo()) {
      addfamily({
        card_name: name,
        id_number,
        type: 1,
        province_id,
        city_id,
        county_id,
        mobile,
        relation,
        height:Number(height).toFixed(1),
        weight:Number(weight).toFixed(1),
        is_default,
        marital_status,
        nation_id,
        job_id
      }).then(data => {
        let sex=this.getIdInfo(id_number).sex;
        this.setData({
          tab: 2,
          family_id:data.family_id,
          sex:sex
        })
        // wx.showToast({
        //   title: '添加成功',
        // })
      })
    }
  },
  handleGetHealthy(id){
    getHealthy(id).then(data=>{
      for (const key in data) {
        if (data[key] || data[key]==0) {
           this.setData({
            hasHealthy:true,
            ['healthyInfo.'+key]:data[key]
           })
        }
      }
      if(data.drugs_name){
        this.setData({
          hideDrug:true
        })
      }
    })
  },
  hnadleGetpersonal(id) {
    getpersonal(id).then(data => {
      for (const key in data) {
        if (data[key] || data[key]==0) {
        
           this.setData({
            hasPersonal:true,
            ['personInfo.'+key]:data[key]
           })
         
        }
      };
      if(data.allergy_history){
        this.setData({
          hideGuomin:true
        })
      };
      if(data.family_history){
       this.setData({
         hideFamilysick:true
       })
     };
     if(data.operation){
      this.setData({
        hideOperation:true
      })
     };
     if(data.pregnant){
      this.setData({
        hidePregnant:true
      })
     }

     if(data.chemical_compound_status && data.chemical_compound_status!=1){
      if(data.chemical_compound_describe){
        this.setData({
          hideChemical:true
        })
      }
     }
    
    })
  },
  handleAddPerson() {
     this.setData({
      'personInfo.family_id':this.data.family_id
     })
     if(this.validatePersonInfo()){
      //  this.setData({
      //   isloading:true
      //  })
      addPersonal(this.data.personInfo).then(data=>{
        this.setData({
          tab:3
        })
      })
     }
    
  },
  handleAddHealthy(){
    this.setData({
      'healthyInfo.family_id':this.data.family_id
     });
     if(this.validateHealthyInfo()){
      //  this.setData({
      //   isloading:true
      //  })
        addHealthy(this.data.healthyInfo).then(data=>{
             wx.showToast({
               title: '添加成功',
               icon:"none"
             })
            //  this.setData({
            //   isloading:false
            //  })
             wx.navigateBack({
               delta: 1,
             })
          
      })
     }
    
  },
  handleEditHealthy(id) {
    this.setData({
      'healthyInfo.family_id':this.data.family_id
     });
     if(this.validateHealthyInfo()){
      // this.setData({
      //   isloading:true
      //  })
        editHealthy(id,this.data.healthyInfo).then(data=>{
          wx.showToast({
            title: '修改成功',
            icon:"none"
          })
          // this.setData({
          //   isloading:false
          //  })
           wx.navigateBack({
            delta: 1,
          })
        
        })
     }
    },
  handleEditPerson(id) {
    this.setData({
      'personInfo.family_id':this.data.family_id
     });
     if(this.validatePersonInfo()){
      // this.setData({
      //   isloading:true
      //  })
        editPersonal(id,this.data.personInfo).then(data=>{
          this.setData({
            tab:3
          })
        })
     }
    },
  handleEditfamilyDetail(id) {
    let {
      name,
      id_number,
      province_id,
      city_id,
      county_id,
      mobile,
      height,
      weight,
      marital_status,
      nation_id,
      is_default,
      job_id,
      relation
    } = this.data.user_info;
    if (this.validateBasicInfo()) {
      // this.setData({
      //   isloading:true
      //  })
      editfamilyDetail(id, {
        card_name: name,
        id_number,
        type: 1,
        is_default,
        relation,
        province_id,
        city_id,
        county_id,
        mobile,
        height:height?Number(height).toFixed(1):'',
        weight:weight?Number(weight).toFixed(1):'',
        marital_status,
        nation_id,
        job_id
      }).then(data => {
        let sex=this.getIdInfo(id_number).sex;
        this.setData({
          tab:2,
          sex:sex
        })
      })
    }
  },
  handelFamilyDetail(id) {
    familyDetail(id).then(data => {
      let obj = {};
      for (const key in data) {
        if (data[key]) {
          obj[key] = data[key]
        }
      }
      let json = {
        1: '本人',
        2: '父母',
        3: '爱人',
        4: '子女',
        5: '亲戚',
        6: '其他'
      };
      // 与患者关系（1:本人 2:父母 3:爱人 4:子女 5:亲戚 6:其他 ）
      let marryjson = {
        0: '未婚',
        1: '已婚',
        2: '离异'
      };
      //婚姻状况（0:未婚 1:已婚 2:离异）
      let relation_name = json[data.relation];
      let marital_name = marryjson[data.marital_status]
      this.setData({
        user_info: obj,
        relation_name: relation_name,
        marital_name: marital_name,
        "user_info.name": data.card_name
      });
      if(data.sex!=2){
        this.setData({
          startIndex:2
        })
      }
    })

  },
    //获取身份证号信息
    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;
      }
  },
  getsickInfo(id) {
    sickInfo({
      order_inquiry_id: id
    }).then(data => {
      let currentInfo = this.data.user_info;
      let obj = {};
      for (const key in currentInfo) {
        if (data[key]) {
          obj[key] = data[key]
        }
      }
      let json = {
        1: '本人',
        2: '父母',
        3: '爱人',
        4: '子女',
        5: '亲戚',
        6: '其他'
      };
      // 与患者关系（1:本人 2:父母 3:爱人 4:子女 5:亲戚 6:其他 ）
      let realtion = data.relation;
      let relation_name = json[realtion];
      this.setData({
        user_info: obj,
        relation_name: relation_name
      });
    })
  },
  openPop() {
    this.setData({
      show: true
    })
  },
  handleClose() {
    this.setData({
      show: false
    })
  },

  handleConfirm(event) {
    this.setData({
      show: false, 
      "healthyInfo.diagnosis_date": dayjs(event.detail).format('YYYY-MM-DD')
    });

  },
  onChange({detail}) {
    // 需要手动对 checked 状态进行更新
    this.setData({
      "user_info.is_default": detail?1:0
    });
  },
  openTips(){
   if(this.data.family_id){
     wx.showToast({
       title: '该项不能修改',
       icon:'none'
     })
   }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.order_inquiry_id) {
      this.getsickInfo(options.order_inquiry_id);
      this.setData({
        notallowEdit: true
      })
    };
    let family_id = options.family_id;
    if (family_id) {
      this.setData({
        family_id: family_id
      })
      this.handelFamilyDetail(family_id);
      this.hnadleGetpersonal(family_id);
      this.handleGetHealthy(family_id)
    }
    if(options.fromtype){
      this.setData({
        fromtype:options.fromtype
      })
    }
    this.provinceList();
    this.getSick();
    this.getNation();
    this.getJob();
  },

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

  },

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

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  
})