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
    }],
    errorStatus: {
      name: false,
      gender: false,
      id: false,
      birthday: false,
      age: false,
      birth_weight: false,
      operative_date: false,
      parity_number: false,
      birth_number: false,
      conception_type: false,
      gestational_week: false,
      prenatal_check_type: false,
      delivery_type: false,
    },
  },

  onLoad() {
    // this.initAreaData();
    this.getPersonalInfo()
  },
  async getPersonalInfo() {
    const info = await request('patient/basic/0')
    this.setData({
      personInfo: {
        username: info.username,
        age: info.age,
        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 {
      if(this.data.personInfo.operative_date){
        return;
      }
      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,
    });
  },
  getAgeByBirthday(birthday) {
    if (!birthday) return '';
    const today = new Date();
    const birthDate = new Date(birthday);

    let years = today.getFullYear() - birthDate.getFullYear();
    let months = today.getMonth() - birthDate.getMonth();
    let days = today.getDate() - birthDate.getDate();

    if (days < 0) {
      months--;
      days += new Date(today.getFullYear(), today.getMonth(), 0).getDate();
    }
    if (months < 0) {
      years--;
      months += 12;
    }
    if (years <= 0 && months <= 0) {
      // 小于一个月，显示几周
      const diffTime = today - birthDate;
      const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
      if (diffDays < 7) {
        return `${diffDays}天`;
      } else {
        const weeks = Math.floor(diffDays / 7);
        return `${weeks}周`;
      }
    }
    if (years <= 0) {
      return `${months}个月`;
    }
    return `${years}岁零${months}个月`;
  },
  onPickerChange(e) {
    const {
      value,
      label
    } = e.detail;
    console.log(mode, mode == 'birth')
    if (mode == 'birth') {
      this.setData({
        ['personInfo.birthday']: value,
        ['personInfo.age']: this.getAgeByBirthday(value),
        ['errorStatus.birthday']: false
      })
    } else {
      this.setData({
        ['personInfo.operative_date']: value,
        ['errorStatus.operative_date']: false
      })
    }

  },

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

  onNameChange(e) {
    this.personInfoFieldChange('username', e);
    const value = e.detail.value;
    // Validate name length (2-20)
    if (value.length < 2 || value.length > 20) {
      this.setData({ 'errorStatus.name': true });
    } else if (this.data.errorStatus.name) {
      this.setData({ 'errorStatus.name': false });
    }
  },

  onGenderChange(e) {
    this.personInfoFieldChange('sex', e);
    if (this.data.errorStatus.gender) {
      this.setData({ 'errorStatus.gender': false });
    }
  },
  // 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() {
    let obj = this.data.personInfo;
    let errorStatus = {};
    // Name must be 2-20 characters
    errorStatus.name = !obj.username || obj.username.length < 2 || obj.username.length > 20;
    errorStatus.gender = !obj.sex;
    errorStatus.id = obj.id_number ? !/^[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(obj.id_number) : false;
    errorStatus.birthday = !obj.birthday;
    errorStatus.age = !obj.age;
    errorStatus.birth_weight = !/^\d+(\.\d+)?$/.test(obj.birth_weight);
    errorStatus.operative_date = !obj.operative_date;
    errorStatus.parity_number = !obj.parity_number;
    errorStatus.birth_number = !obj.birth_number;
    errorStatus.conception_type = !obj.conception_type;
    errorStatus.gestational_week = !/^\d+(\.\d+)?$/.test(obj.gestational_week) || Number(obj.gestational_week) <= 0;
    errorStatus.prenatal_check_type = !obj.prenatal_check_type;
    errorStatus.delivery_type = !obj.delivery_type;
    errorStatus.prenatal_check_remark = !obj.prenatal_check_remark;
    this.setData({ errorStatus });
    if (Object.values(errorStatus).some(v => v)) {
      return;
    }
    obj.birth_weight = Number(obj.birth_weight);
    obj.gestational_week = Number(obj.gestational_week);
    if (obj.prenatal_check_type == 2) {
      obj.prenatal_check_remark = '无';
    }
    await request('patient/set_personal_information', 'post', obj);
    wx.showToast({
      title: '提交成功',
      icon: 'success',
      duration: 2000, 
      complete: () => {
        wx.switchTab({
          url: '/pages/my/index'
        })
      }
    })
  },
  onIdInput(e) {
    // 18位身份证正则
    const value = e.detail.value;
    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]$/;
    if (this.data.errorStatus.id) {
      this.setData({ 'errorStatus.id': false });
    }
    this.personInfoFieldChange('id_number', e);
    // 如果输入合法身份证号，自动提取出生日期
    if (reg18.test(value)) {
      const birthStr = value.substr(6, 8); // YYYYMMDD
      const birthDate = `${birthStr.substr(0, 4)}-${birthStr.substr(4, 2)}-${birthStr.substr(6, 2)}`;
      this.setData({
        'personInfo.birthday': birthDate,
        'personInfo.age': this.getAgeByBirthday(birthDate)
      });
    }
  },
  onWeightInput(e) {
    // const isNumber = /^\d+(\.\d+)?$/.test(e.detail.value);
    // if (this.data.errorStatus.birth_weight) {
    //   this.setData({ 'errorStatus.birth_weight': false });
    // }
    if(!e.detail.value || e.detail.value == 0){
      this.setData({ 'errorStatus.birth_weight': true });
    } else {
      this.setData({ 'errorStatus.birth_weight': false });
    }
    this.personInfoFieldChange('birth_weight', e);
  },
  onWeekInput(e) {
    console.log(e.detail.value == true)
    if(!e.detail.value || e.detail.value == 0){
      this.setData({ 'errorStatus.gestational_week': true });
    } else {
      this.setData({ 'errorStatus.gestational_week': false });
    }
    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],
      [`errorStatus.${modeText}`]: false
    })

  },
  onPrenatalCheckRemarkChange(e) {
    this.setData({
      ['personInfo.prenatal_check_remark']: e.detail.value,
      ['errorStatus.prenatal_check_remark']: false
    })
   
  },
});