import request from '~/api/request';

let mode = ''
let modeText = ''

Page({
  data: {
    personInfo: {
      username: '',
      sex: 1,
      id_number: '',
      birthday: '',
      operative_date: '',
      delivery_type: '',
      prenatal_check_type: '',
      gestational_week: '',
      conception_type: '',
      birth_number: '',
      parity_number: '',
      birth_weight: '',
      prenatal_check_remark: ''
    },
    genderOptions: [
      {
        label: '男',
        value: 1,
      },
      {
        label: '女',
        value: 2,
      }
      
    ],
    
    birthVisible: false,
    birthStart: '1970-01-01',
    birthEnd: new Date().toISOString().split('T')[0],
    birthTime: 0,
    birthFilter: (type, options) => (type === 'year' ? options.sort((a, b) => b.value - a.value) : options),
    addressText: '',
    addressVisible: false,
    provinces: [],
    cities: [],

    gridConfig: {
      column: 3,
      width: 160,
      height: 160,
    },
    timeValue: '',
    timePicker:new Date().toISOString().split('T')[0],
    idError: false,
    numberError: false,
    weekError: false,
    numberFormat: (v) => {
      const isNumber = /^\d+(\.\d+)?$/.test(v);
      if (isNumber) {
        return parseFloat(v).toFixed(2);
      }
      return v;
    },
    // 下拉
    selectList: [],
    selectValue: '',
    selectVisible: false,
    deliveryList:[{label: '顺产', value: 1},{label: '剖腹产', value: 2}], 
    prenatal_checkList: [{label: '有', value: 1},{label: '无', value: 2}], 
    parity_numberList: [{label: '1胎', value: 1},{label: '2胎', value: 2},{label: '3胎', value: 3},{label: '大于等于4胎', value: 4}],
    birth_numberList:[{label: '1产', value: 1},{label: '2产', value: 2},{label: '大于等于3产', value: 3}],
    conception_typeList: [{label: '自然受孕', value: 1},{label: '辅助生殖技术', value: 2}]
  },

  onLoad() {
    // this.initAreaData();
   this.getPersonalInfo()
  },
  async getPersonalInfo() {
    const info = await request('patient/basic/0')
    this.setData({
      personInfo: {
        username: info.username,
        sex: info.sex,
        id_number: info.id_number,
        birthday: info.birthday || '',
        operative_date: info.operative_date,
        delivery_type: info.delivery_type,
        prenatal_check_type: info.prenatal_check_type,
        gestational_week: info.gestational_week,
        conception_type: info.conception_type,
        birth_number: info.birth_number,
        parity_number: info.parity_number,
        birth_weight: info.birth_weight,
        prenatal_check_remark: info.prenatal_check_remark
      }
    })
  },
  

  getAreaOptions(data, filter) {
    const res = Object.keys(data).map((key) => ({ value: key, label: data[key] }));
    return typeof filter === 'function' ? res.filter(filter) : res;
  },

  getCities(provinceValue) {
    return this.getAreaOptions(
      areaList.cities,
      (city) => `${city.value}`.slice(0, 2) === `${provinceValue}`.slice(0, 2),
    );
  },

  initAreaData() {
    const provinces = this.getAreaOptions(areaList.provinces);
    const cities = this.getCities(provinces[0].value);
    this.setData({ provinces, cities });
  },

  onAreaPick(e) {
    const { column, index } = e.detail;
    const { provinces } = this.data;

    // 更改省份则更新城市列表
    if (column === 0) {
      const cities = this.getCities(provinces[index].value);
      this.setData({ cities });
    }
  },

  showPicker(e) {
    mode = e.currentTarget.dataset.mode;
    if(mode == "birth"){
      this.setData({
        birthVisible: true,
        timePicker: this.data.personInfo.birthday ? this.data.personInfo.birthday : new Date().toISOString().split('T')[0]
      });
    } else {
      this.setData({
        birthVisible: true,
        timePicker: this.data.personInfo.operative_date ? this.data.personInfo.operative_date : new Date().toISOString().split('T')[0]
      });
    }
    
   
  },

  hidePicker(e) {
    const { mode } = e.currentTarget.dataset;
    this.setData({
      [`${mode}Visible`]: false,
    });
  },

  onPickerChange(e) {
    const { value, label } = e.detail;
    console.log(mode, mode == 'birth')
    if(mode == 'birth'){
      this.setData({
        ['personInfo.birthday']: value
      })
    }else{
      this.setData({
        ['personInfo.operative_date']:value
      })
    }
    
  },

  personInfoFieldChange(field, e) {
    const { value } = e.detail;
    this.setData({
      [`personInfo.${field}`]: value,
    });
  },

  onNameChange(e) {
    this.personInfoFieldChange('username', e);
  },

  onGenderChange(e) {
    this.personInfoFieldChange('sex', e);
  },
  // onYearChange(e) {
  //   this.personInfoFieldChange('yearType', e);
  // },

  onIntroductionChange(e) {
    this.personInfoFieldChange('introduction', e);
  },

  onPhotosRemove(e) {
    const { index } = e.detail;
    // const { photos } = this.data.personInfo;

    // photos.splice(index, 1);
    // this.setData({
    //   'personInfo.photos': photos,
    // });
  },

  onPhotosSuccess(e) {
    const { files } = e.detail;
    // this.setData({
    //   'personInfo.photos': files,
    // });
  },

  onPhotosDrop(e) {
    const { files } = e.detail;
    // this.setData({
    //   'personInfo.photos': files,
    // });
  },

  async onSaveInfo() {
    // console.log(this.data.personInfo);
    const res = await request('patient/set_personal_information', 'get', {
      data: this.data.personInfo
    })
    wx.switchTab({
      url: `/pages/my/index`,
    });
  },
  onIdInput(e){
    // 18位身份证正则
    const { idError } = this.data;
      const reg18 = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(e.detail.value);
      if (idError == reg18) {
        this.setData({
          idError: !reg18,
        });
      }
      this.personInfoFieldChange('id_number', e);
  },
  onWeightInput(e){
    const { numberError } = this.data;
      const isNumber = /^\d+(\.\d+)?$/.test(e.detail.value);
      if (numberError === isNumber) {
        this.setData({
          numberError: !isNumber,
        });
      }
      this.personInfoFieldChange('birth_weight', e);
  },
  onWeekInput(e){
    const { weekError } = this.data;
      const isNumber = /^\d+(\.\d+)?$/.test(e.detail.value);
      if (weekError === isNumber) {
        this.setData({
          weekError: !isNumber,
        });
      }
      this.personInfoFieldChange('gestational_week', e);
  },
  showSelect(e){
    const { mode, list } = e.currentTarget.dataset;
    modeText = mode
    this.setData({
      selectVisible: true,
      selectValue: this.data.personInfo[mode] ? this.data.personInfo[mode] : '',
      selectList: list
    })
  },
  onSelectChange(e){
    const { value, label } = e.detail;
    this.setData({
      [`personInfo.${modeText}`]: value[0]
    })
  },


  onSaveInfo(){
    console.log(this.data.personInfo)
    let obj = this.data.personInfo
    obj.birth_weight = Number(obj.birth_weight)
    obj.gestational_week = Number(obj.gestational_week)
    if( obj.prenatal_check_type == 2){
      obj.prenatal_check_remark = '无'
    }
    request('patient/set_personal_information', 'post', obj)
  }
});
