const util = require("../../../utils/util.js");
const app = getApp();
Page({
  data: {
    makeTask:false,//是否为做任务
    taskId:'',
    list: [],
    isSelected: true,
    datas:{},
    ctype:0,
    msgType:0, //出行人信息/购买信息的默认显示项
    defaultType:0,//仅用于宝贝币任务的默认选中项
    showAddress:false,
    info:{
      contactPhone:'',
      mailAddress:'',
      email:'',
      street:''
    },
    accordWithAge:true
  },
  onLoad:function(options){
    console.log(options)
    if (!util.isObjEmpty(options)){
      this.setData({ datas: options, isSelected: (options.quantity ? false : true), ctype: options.sparent == 0 ? 1 : 0,msgType:options.defaultType,defaultType:options.defaultType,makeTask:options.makeTask,taskId:options.taskId });
    }
    let that = this;
    if (getCurrentPages().length == 1) {
      // var getLocation = util.promise();
      // getLocation.then(function (value) {
        if (that.data.msgType==1) {
          that.submit()
        } else {
          that.getList(true);
        }
        that.setData({ currentPages: getCurrentPages().length })
      // }, function (error) {
      // });
    } else {
      if (that.data.msgType==1) {
        that.submit()
      } else {
        that.getList(true);
      }
    }
  },
  onShow: function () {
    if (wx.getStorageSync("reload")){
      wx.removeStorageSync("reload");
      if (this.data.msgType==1) {
        this.submit()
      } else {
        this.getList(false);
      }
    }else{
      this.setData({ list: this.defaultIdcard(this.data.list) });
    }
  },
  onPullDownRefresh: function() {
    var self = this;
    wx.showNavigationBarLoading();
    setTimeout(function () {
      self.getList(false);
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }, 1500);
  },
  getList: function (load) {
    var self = this;
    util.ajax({
      func: "user/idcardinfo_list",
      data: { type: this.data.ctype == 0 ? 0 : -1 },
      load: load
    }, function (res) {
      if(res.code == 0){
        if (res.data.length>0 && self.data.isSelected) {
          res.data.map((el,i) => {
            if (!util.isEmpty(el.name) && !util.isEmpty(el.idcard) && !util.isEmpty(el.height) && !util.isEmpty(el.weight) && el.bodyType !=null && !util.isEmpty(el.clothesSize) && !util.isEmpty(el.shoesSize)) {
              el.perfect=0
            } else {
              el.perfect=1
            }
          });
          if (self.data.makeTask&&self.data.defaultType==0&&self.data.ctype == 0) {
            util.finishCoinTask(self.data.taskId).then(res=>{
              util.showTips(res,3000);
              self.setData({makeTask:false})
            })
          }
        }
        if (res.data.length<=0 && !self.data.isSelected) {
          let  obj = {currentTarget:{dataset:{act:'add',needclothessize:self.data.datas.needClothesSize,needshoesize:self.data.datas.needShoeSize}}}
          self.addCard(obj)
        }
        self.setData({ list: self.defaultIdcard(res.data) });
      }else{
        util.showTips(res.reason)
      }
    });
  },
  setTabbar(e){
    let index = e.currentTarget.dataset.index;
    this.setData({ msgType: index});
    if (index==1) {
      this.submit()
    }else{
      this.getList(true);
    }
  },
  // 儿童/亲子
  swtichTab(e){
    let index = e.currentTarget.dataset.index;
    this.data.ctype = index;
    this.setData({ ctype: this.data.ctype, list: [] });
    this.getList(true);
  },
  defaultIdcard: function (data) {
    if (typeof (data) == "undefined"){
      return "";
    }
    var idcards = wx.getStorageSync("idcards") || [], ids = "";
    for (var i in data) {
      data[i]['cardTypeStr'] = util.cardType(data[i]['cardType']);
      if (!util.isObjEmpty(data[i]['parent'])) {
        data[i]['parent']['cardTypeStr'] = util.cardType(data[i]['parent']['cardType']);
      }
      data[i]['default'] = false;
      if (!util.isObjEmpty(idcards) && !util.isObjEmpty(idcards.ids)){
        ids = idcards.ids.join(",");
        if (ids.indexOf(",") != -1) {
          if (ids.indexOf(data[i].id) != -1) {
            data[i]['default'] = true;
          }
        } else if(idcards.ids.length > 0) {
          if (data[i].id == ids) {
            data[i]['default'] = true;
          }
        }
      }
    }
    return data;
  },
  addCard: function (e) {
    if(this.data.ctype == 0){
      wx.navigateTo({
        url: "/pages/account/cards/addcard?" + util.toParam(e.currentTarget.dataset)
      });
    }else{
      wx.navigateTo({
        url: "/pages/account/cards/single?" + util.toParam(e.currentTarget.dataset)
      });
    }
  },
  checkboxChange:function(e){
    if (this.data.isSelected){
      return false;
    }
    var self = this, typeA = "", newArr = { ids: [], names: [], idCards: [], parentNames: [] }, arr = e.detail.value, count = arr.length, idcards = wx.getStorageSync("idcards") || [],tipArticle='';
    if (count > self.data.datas.quantity) {
      arr.pop();
    }
    let index = '';
    for (var i in arr) {
      var val = arr[i].split("|");
      newArr['ids'].push(val[0]);
      newArr['names'].push(val[1]);
      newArr['parentNames'].push(val[2]);
      newArr['idCards'].push(val[8]);
      if (this.data.ctype == 0 && util.isEmpty(val[2])){//监护人
        typeA = 1;
      }
      if (util.isEmpty(val[3]) || util.isEmpty(val[4]) || util.isEmpty(val[5])) {//体型身高
        typeA = 2;
      }
      if (this.data.ctype == 0 && val[6] == 1) {//内部评估
        typeA = 3;
      }
      if (self.data.datas.military!=1 && this.data.ctype == 0 && (util.ages(val[7]) != "儿童" || (util.getAge(val[7]) < self.data.datas.mage || util.getAge(val[7]) > self.data.datas.lage))){//单飞儿童年龄
        typeA = 4;
      }
      if (self.data.datas.military!=1 && this.data.ctype == 1 && util.ages(val[7]) == "儿童" && (util.getAge(val[7]) < self.data.datas.mage || util.getAge(val[7]) > self.data.datas.lage)) {//亲子儿童年龄
        typeA = 5;
      }
      if (this.data.ctype == 1 && util.ages(val[7]) == "成人" && (util.getAge(val[7]) < self.data.datas.adultMinAge || util.getAge(val[7]) > self.data.datas.adultMaxAge)) {//亲子成人年龄
        typeA = 6;
      }
      if (self.data.datas.needClothesSize==1 && util.isEmpty(val[10])) {
        typeA = 7;
      }
      if (self.data.datas.needShoeSize==1 && util.isEmpty(val[11])) {
        typeA = 8;
      }
      index = val[9];
      this.getChildAge(val[12]).then((res)=>{
        let arr=self.data.datas.ageLimit.split('-')
        if (self.data.datas.military==1 && (util.isEmpty(val[12]) || arr[0]>res.data || res.data>arr[1])) {
          typeA = 9;
        }
      },(res)=>{
        tipArticle=res.reason;
        typeA = 9;
      })
      
      if (self.data.datas.military==1 && (self.data.datas.campSex==1 ||self.data.datas.campSex==0) && self.data.datas.campSex != val[13]) {
        typeA = 10;
      }
    }
    let timer = setTimeout(() => {
      if (typeA == 1){
      wx.showModal({
        title: '提示',
        content: '请先编辑儿童的监护人，以便生成电子合同！',
        showCancel:false,
        confirmColor: '#ee3a43',
        confirmText:'确定'
      });
      self.setData({ list: self.defaultIdcard(self.data.list) });
      return false;
    }
    if (typeA == 2) {
      wx.showModal({
        title: '提示',
        content: '请补充数字类型的身高、体重和选择相对应的体型。',
        showCancel: false,
        confirmColor: '#ee3a43',
        confirmText:'确定'
      });
      self.setData({ list: self.defaultIdcard(self.data.list) });
      return false;
    }
    if (typeA == 3) {
      wx.showModal({
        title: '提示',
        content: '经过内部综合评估，目前我们的服务专业性暂时无法满足您的孩子正向成长的实际需求，对此我们深表遗憾。',
        showCancel: false,
        confirmColor: '#ee3a43',
        confirmText: '确定'
      });
      self.setData({ list: self.defaultIdcard(self.data.list) });
      return false;
    }
    if (typeA == 4) {
      wx.showModal({
        title: '提示',
        content: '本活动适合' + self.data.datas.mage + '-' + self.data.datas.lage + '岁的儿童报名，此儿童年龄不符，请检查。',
        showCancel: false,
        confirmColor: '#ee3a43',
        confirmText: '确定'
      });
      self.setData({ list: self.defaultIdcard(self.data.list) });
      return false;
    }
    if (typeA == 5) {
      wx.showModal({
        title: '提示',
        content: '本活动适合' + self.data.datas.mage + '-' + self.data.datas.lage + '岁的儿童报名，此儿童年龄不符，请检查。',
        showCancel: false,
        confirmColor: '#ee3a43',
        confirmText: '确定'
      });
      self.setData({ list: self.defaultIdcard(self.data.list) });
      return false;
    }
    if (typeA == 6) {
      wx.showModal({
        title: '提示',
        content: '本活动适合' + self.data.datas.adultMinAge + '-' + self.data.datas.adultMaxAge + '岁的成人报名，此成人年龄不符，请检查。',
        showCancel: false,
        confirmColor: '#ee3a43',
        confirmText: '确定'
      });
      self.setData({ list: self.defaultIdcard(self.data.list) });
      return false;
    }
    if (typeA == 7) {
      wx.showModal({
        title: '提示',
        content: '因活动需要，请补充该出行人衣服尺码',
        showCancel: false,
        confirmColor: '#ee3a43',
        confirmText: '确定'
      });
      self.setData({ list: self.defaultIdcard(self.data.list) });
      return false;
    }
    if (typeA == 8) {
      wx.showModal({
        title: '提示',
        content: '因活动需要，请补充该出行人鞋码',
        showCancel: false,
        confirmColor: '#ee3a43',
        confirmText: '确定'
      });
      self.setData({ list: self.defaultIdcard(self.data.list) });
      return false;
    }
    if (typeA == 9) {
      wx.showModal({
        title: '提示',
        content: tipArticle || '本活动适合' + self.data.datas.ageLimit + '岁的儿童报名，此儿童年龄不符，请检查。',
        showCancel: false,
        confirmColor: '#ee3a43',
        confirmText: '确定'
      });
      self.setData({ list: self.defaultIdcard(self.data.list) });
      return false;
    }
    if (typeA == 10){
      wx.showModal({
        title: '提示',
        content: `当前选择的排期只允许${self.data.datas.campSex==0?'女生':'男生'}报名`,
        showCancel:false,
        confirmColor: '#ee3a43',
        confirmText:'确定'
      });
      self.setData({ list: self.defaultIdcard(self.data.list) });
      return false;
    }
    let list = self.data.list;
    if(index && list[index].overdue == 1){  //overdue  3个月未修改 ——1是 0否（成人忽略）
      wx.showModal({
        title: '提示',
        content: '请再次确认儿童或成人的身高、体重、体型是否正确？后续将根据这个选择衣服尺码',
        cancelText:'编辑',
        cancelColor:'#ee3a43',
        confirmText:'确认正确',
        confirmColor:'#ee3a43',
        success: function(res) {
          if (res.confirm) {//确认正确
            wx.setStorageSync("idcards", newArr);
            if (count > self.data.datas.quantity){
              self.setData({ list: self.defaultIdcard(self.data.list) });
              wx.showModal({
                title: '提示',
                content: '您购买' + self.data.datas.quantity + '份，请选择' + self.data.datas.quantity +'名儿童或成人的身份信息！',
                cancelText:'关闭提示',
                confirmText:'继续返回',
                confirmColor:'#EE3A43',
                success: function (res) {
                  if (res.confirm) {
                    wx.navigateBack();
                  }
                }
              });
            } else if (arr.length == self.data.datas.quantity){
              self.clearVids();
              wx.navigateBack();
            }
          }else if(res.cancel){//编辑
            let listdata = list[index];
            let dataset = {};
            dataset['act'] = "edit";
            dataset['birthday'] = listdata.birthdayStr;
            dataset['cardtype'] = listdata.cardType;
            dataset['height'] = listdata.height;
            dataset['id'] = listdata.id;
            dataset['idcard'] = listdata.idcard;
            dataset['name'] = listdata.name;
            if (this.data.ctype == 0) dataset['parentid'] = listdata.parent.id || '';
            dataset['sex'] = listdata.sex;
            dataset['weight'] = listdata.weight;
            wx.navigateTo({
              url: "/pages/account/cards/" + (this.data.ctype == 0? "addcard?":"single?") + util.toParam(dataset)
            });
          }
        }
      })
    }else{
      wx.setStorageSync("idcards", newArr);
      self.common(count,arr.length);
    }
    clearTimeout(timer);
    }, 200);
    console.log(arr,newArr)
  },
  // 获取儿童年龄
  getChildAge(id){
    let that=this;
    return new Promise(function (resolve, reject) {
      util.ajax({
        func: "v2/order/age",
        data: {
          sid:that.data.datas.sid,
          id:id
        },
        load:false
      }, function (res) {
        if (res.code==0) {
          resolve(res);
        } else {
          reject(res);
        }
      })
    })
    
  },
  clearVids:function(){
    let idcards = wx.getStorageSync("idcards") || [];
    if (idcards['ids'].length == 1){
      wx.removeStorageSync('vids');
    }
  },
  common:function(count,arrLength){
    var self = this;
    if (count > self.data.datas.quantity){
      self.setData({ list: self.defaultIdcard(self.data.list) });
      wx.showModal({
        title: '提示',
        content: '您购买' + self.data.datas.quantity + '份，请选择' + self.data.datas.quantity +'名儿童的身份信息！',
        cancelText:'关闭提示',
        confirmText:'继续返回',
        confirmColor:'#EE3A43',
        success: function (res) {
          if (res.confirm) {
            wx.navigateBack();
          }
        }
      });
    } else if (count == self.data.datas.quantity){
      self.clearVids();
      wx.navigateBack();
    }
  },
  // 提交购买信息
  submit(e){
    let that=this,info=this.data.info,type=e?true:false;
    if (!util.isEmpty(info.contactPhone) && util.isPhone(info.contactPhone)) {
      util.showTips('手机号格式不正确');
      return false;
    }
    var myreg = /^([a-zA-Z0-9]+[_|\_|\.|-]+)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.|-]+)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/gi;
    if (!util.isEmpty(info.email) && !myreg.test(info.email)) {
      util.showTips('电子邮箱格式不正确');
      return false;
    }
    info.mailAddress = info.mailAddress || '';
    info.street = info.street || '';
    util.ajax({
      func: "v2/user/buy/info",
      data: type?info:{},
      method:type?'post':'get'
    }, function (res) {
      if (res.code==0) {
        if (type) {
          if (!that.data.makeTask) {
            util.showTips(res.reason)
          }
          if (that.data.makeTask&&that.data.defaultType==1&&type) {
            let haveEmpty=true;
            for (const key in info) {
              if (Object.hasOwnProperty.call(info, key) && util.isEmpty(info[key])) {
                haveEmpty=false;
              }
            }
            if (haveEmpty) {
              util.finishCoinTask(that.data.taskId).then(res=>{
                util.showTips(res,3000);
                that.setData({makeTask:false})
              })
            }
          }
        } else {
          that.setData({info:res.data})
        }
      } else {
        util.showTips(res.reason)
      }
    })
  },
  // 获取购买信息
  getAddressInfo(){
    let that=this;
    util.ajax({
      func: "",
    }, function (res) {
      if (res.code==0) {
        that.setData({info:res.data})
      } else {
        util.showTips(res.reason)
      }
    })
  },
  chooseAddress(){
    this.setData({showAddress:true})
  },
  bindInfo(e){
    let type=e.currentTarget.dataset.type,value=e.detail.value;
    switch (type) {
      case "contactPhone":
        this.data.info.contactPhone=value;
        break;
      case "email":
        this.data.info.email=value;
        break;
      case "street":
        this.data.info.street=value;
        break;
    }
    this.setData({info:this.data.info})
  },
  // 邮寄地址
  submitAddress(e){
    let data = e.detail;
    data.address=data.address.replace(/\s+/g,' ')
    this.setData({ 'info.mailAddress': data.name + ' ' + data.mobile + ' ' + data.provincial + ' ' + data.address});
  },
  close(){
    this.setData({showAddress:false})
  },
  onShareAppMessage() {
    return {
      title: '儿童的身份信息',
      path: '/pages/account/cards/index'
    }
  }
})