const util = require("../../../utils/util.js");
const app = getApp();
Page({
  data: {
    info:{},
    parents:[],
    endDate:"2019-01-01",
    birthday: "2010-01-01",
    sex: 1,
    cardTypeStr:"",
    cardType:"",
    parentid:0,
    mask:false,
    parentBirthday:'',
    clothesCode:[110,120,130,140,150,160,165,170,175,180,185],
    shoesCode:[20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45],
    clothesIndex:'',
    shoesIndex:'',
    showCodePopup:false,
    needclothessize:'1',
    needShoeSize:'1'
  },
  onLoad: function (options) {
    console.log(options)
    options.cardtype = options.cardtype || 0;
    options.bodyType = options.bodytype;
    this.setData({ info: util.urlDecode(options), sex: options.sex || 1, birthday: options.birthday || "2010-01-01", cardTypeStr: util.cardType(options.cardtype), cardType: options.cardtype, parentid: options.parentid || 0,needclothessize:options.needclothessize==undefined?1:(options.needclothessize || 0),needShoeSize:options.needshoesize==undefined?1:(options.needshoesize || 0)});
    if (options) {
      this.satisfy();
      if (options.clothessize) {
        this.data.clothesCode.forEach((el,i) => {
          if (el==options.clothessize) {
            this.setData({clothesIndex:i})
          }
        });
      }
      if (options.shoessize) {
        this.data.shoesCode.forEach((el,i) => {
          if (el==options.shoessize) {
            this.setData({shoesIndex:i})
          }
        });
      }
    }
    this.setTitle();
  },
  onShow:function(){
    var val = wx.getStorageSync("parentid"), isDel = wx.getStorageSync("isDel");
    if (!util.isEmpty(val)){
      isDel && val == this.data.parentid ? val = 0 : val;
      if (isDel){
        wx.removeStorageSync("isDel");
      }
      this.setData({ parentid: val});
      wx.removeStorageSync("parentid");
    }
    this.getGuardian(true);
  },
  addParent:function(e){
    wx.navigateTo({
      url: '/pages/account/cards/person?' + util.toParam(e.currentTarget.dataset)
    })
  },
  getGuardian:function(load){
    var self = this;
    util.ajax({
      func:"user/idcardinfo_list",
      data: {type: 1},
      load: load
    },function(res){
      if (res.code == 0 && res.data.length > 0){
        self.data.parents = util.defaultIdcard(res.data);
        self.setData({ parents: self.data.parents});
      }
    });
  },
  setTitle: function (){
    wx.setNavigationBarTitle({
      title: (this.data.info.act == "add" ? "新增" : this.data.info.act == "edit" ? "修改" : "") +"出行人信息"
    })
  },
  selectCard:function(){
    var self = this;
    wx.showActionSheet({
      itemList: util.config.cardTypeArr,
      success: function (res) {
        self.setData({ cardType: res.tapIndex, cardTypeStr: util.cardType(res.tapIndex)});
      }
    })
  },
  // 判断是否成年
  satisfy() {
    var nowDate = new Date(); // 当前时间
    var mouth = nowDate.getMonth() + 1;
    var day = nowDate.getDate();
    var year = nowDate.getFullYear() - 18;
    var oldDate = '';
    wx.getSystemInfo({
      success (res) {
        oldDate = res.platform=='ios'?new Date(year + '/' + mouth + '/' + day).getTime():new Date(year + '-' + mouth + '-' + day).getTime()
      }
    })
    // var oldDate = new Date(year + '-' + mouth + '-' + day).getTime();
    var newDate = new Date(this.data.birthday).getTime();
    // let ageType = oldDate < newDate ? true : false; // true 表示不满18
    if (oldDate < newDate) {
      this.setData({clothesCode:[110,120,130,140,150,160,165,170,175,180,185],shoesCode:[20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45]})
    } else {
      if (this.data.sex==1) {
        this.setData({clothesCode:[165,170,175,180,185],shoesCode:[39,40,41,42,43,44,45,46,47,48,49]})
      } else {
        this.setData({clothesCode:[155,160,165,170,175],shoesCode:[33,34,35,36,37,38,39,40,41]})
      }
    }
  },
  selectCode(e){
    let type= e.currentTarget.dataset.type,index=e.detail.value;
    switch (type) {
      case "clothes":
        this.setData({clothesIndex:index,})
        break;
      case "shoes":
        this.setData({shoesIndex:index})
        break;
    }
  },
  // 关闭弹窗
  close(){
    this.setData({showCodePopup:false})
  },
  // 打开尺码推荐弹窗
  CodeDetail(){
    this.setData({showCodePopup:true})
  },
  radioChange:function(e){
    this.setData({parentid: e.detail.value,parentBirthday:e.detail.birthdayStr});
  },
  bindDateChange:function(e){
    this.setData({
      birthday: e.detail.value,
      clothesIndex:'',
      shoesIndex:''
    })
    this.satisfy()
  },
  changeSex(e){
    this.setData({ 
      sex: e.detail.value,
      clothesIndex:'',
      shoesIndex:''
    });
    this.satisfy()
  },
  del() {
    var self = this;
    wx.showModal({
      title: '温馨提示',
      content: '您确定不需要该儿童信息了吗？',
      confirmColor: '#EE3A43',
      success: function (res) {
        if (res.confirm) {
          util.ajax({
            func: "user/delete_idcardinfo",
            data: { id: self.data.info.id }
          }, function (data) {
            if(data.code == 0){
              wx.setStorageSync('reload',true);
              wx.navigateBack();
            }else
              util.showTips(data.reason);
          });
        }
      }
    });
  },
  formSubmit:function(e){
    var data = e.detail.value,parents= {};
    if(util.isEmpty(data.name)) {
      util.showTips('请填写您的姓名。');
      return false;
    }
    if (util.isEmpty(data.cardType)) {
      util.showTips('请选择证件的类型。');
      return false;
    }
    if (!util.identityCodeValid(data.cardType, data.idcard)) {
      util.showTips('请填写正确的' + util.cardType(data.cardType) + '。');
      return false;
    }
    if (util.ages(data['birthday']) != "儿童" || (util.getAge(data.birthday) < 3 || util.getAge(data.birthday) > 17)) {
      util.showTips('请输入3-17周岁以内的儿童身份证信息。');
      return false;
    }
    if (this.data.cardtype == '0' && !util.isEmpty(data['idcard']) && parseInt(data['idcard'].substr(16, 1)) % 2 != data['sex']) {
      util.showTips('选择的性别与身份证不符。');
      return false;
    }
    var nowYear = new Date().getFullYear();
    if (util.isEmpty(data['idcard']) && parseInt(nowYear - data['idcard'].substring(6, 10)) >= 18) {
      util.showTips('选择的身份类型与身份证不符。');
      return false;
    }

    if (util.isEmpty(data['height']) || /[^0-9]/g.test(data['height'])) {
      util.showTips('请填写数字类型的身高。');
      return false;
    }
    if (util.isEmpty(data['weight']) || /[^0-9]/g.test(data['weight'])) {
      util.showTips('请填写数字类型的体重。');
      return false;
    }
    if (util.isEmpty(data['bodyType'])) {
      util.showTips('请选择儿童体型，以便活动服装选择。');
      return false;
    }
    if (util.isEmpty(data['pid'])) {
      util.showTips('请添加或选择一个监护人，以便生成电子旅游合同。');
      return false;
    }
    this.data.parents.forEach(item => {
      if(item.id == data['pid']) {
        parents.birthday = item.birthdayStr
      }
    })
    if(util.getAge(parents.birthday) < 18){
      util.showTips('请选择18周岁以上的监护人。');
      return false;
    }
    data['clothesSize']=this.data.clothesCode[this.data.clothesIndex] || '';
    data['shoesSize']=this.data.shoesCode[this.data.shoesIndex] || '';
    data['position'] = "儿童";
    var url = this.data.info.act == "add" ? "user/add_idcardinfo" : "user/update_idcardinfo";
    util.ajax({
      func: url,
      data:data
    },function(res){
      if(res.code == 0){
        wx.setStorageSync("reload",true);
        wx.navigateBack();
      } else {
        wx.showToast({
          title: res.reason,
          icon: "none"
        });
      }
    });
  },
  prompt:function(){
    this.setData({mask:true})
  },
  maskBtn:function(){
    this.setData({mask:false})
  },
  cardBlur:function(e){
    let val = e.detail.value;
    if (this.data.cardType == '0' && util.identityCodeValid(0, val) ){
      var year = parseInt(val.substr(6,4));
      var month = parseInt(val.substr(10,2));
      var day = parseInt(val.substr(12,2));
      if(month<10) month = '0'+month;
      if(day<10) day = '0'+day;
      var birthday = year + '-' + month + '-' + day;
      this.setData({ birthday, sex: util.getSex(val).toString() });
      this.satisfy()
    }
  }
})