const util = require("../../../utils/util")
Page({
  data: {
    showData: false, //是否显示页面
    info: {},
    activiteInfo: {},
    orderId: '',
    childInfo: [],
    childArr: [],
    remark: '',
    mailAddress: '',
    userinfo: wx.getStorageSync('WXuserInfo'),
    cardTypeStr: '',
    clothesCode: [],
    shoesCode: [],
    showCodePopup: false,
    otype: 2,
    // 过敏信息
    // allergy: "无",
    // 饮食信息
    // special: "无",
    catesFlag: false,
    Passporturl: "",
    documentType: 0,
    // 身份证正面
    positive: "",
    // 身份证反面
    otherSide: '',
    // 户口本页
    Household: "",
    firstPagePath: '', //上一个页面路由地址
    information: false,
    idCard: false,
    allergy: '', //过敏是否
    diet: '', //是否禁忌
    bloodOrMedical: '', //是否特殊
    especiallyRemark: '', //是否特别备注
    photoType: 0,
  },

  onLoad: function (options) {
    // console.log(null==false);
    // console.log('options', options)
    let pages = getCurrentPages(); //页面对象
    let prevpage = pages[pages.length - 2]; //上一个页面对象
    let path = prevpage.route;
    this.setData({
      orderId: options.orderId || '',
      cardTypeStr: util.cardType(options.cardtype),
      firstPagePath: path
    })
    this.getOrderDetail();
    this.getDetail();
  },
  //  获取过敏信息
  // getallergy(e) {
  //   console.log(e);
  //   this.setData({
  //     allergy: e.detail.value
  //   })
  //   //  console.log(this.data.allergy);
  // },
  // 获取饮食禁忌
  // getdiet(e) {
  //   this.setData({
  //     taboo: e.detail.value
  //   })
  // },
  // // 获取特殊血型
  // getspecial(e) {
  //   // console.log(e);
  //   this.setData({
  //     special: e.detail.value
  //   })
  // },
  getTaboo(e) {
    console.log(e);
    let index = e.currentTarget.dataset.index
    let type = e.currentTarget.dataset.name
    let value = e.detail.value
    let data = this.data.childArr
    data[index][type] = value
    this.setData({
      childArr: data,
    })
  },
  // 点击证件要求弹框
  certificates() {
    this.setData({
      catesFlag: true
    })
  },
  // 弹框点击确定
  sure() {
    this.setData({
      catesFlag: false
    })
  },
  // 上传护照信息
  upPassport(e) {
    let index = e.currentTarget.dataset.index
    let arr = this.data.childArr
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res);
        util.uploadFile("oss/policy", res.tempFilePaths[0], {
          type: "attendants"
        }, true).then((res) => {
          console.log(res);
          if (res.code == 0) {
            arr[index].passport = res.url
            that.setData({
              childArr: arr
            })
            // that.setData({
            //   Passporturl: that.data.Passporturl
            // })
            // console.log(that.data.Passporturl);
          }
        });
      }
    })

  },
  // 切换证件类型
  bindinputTwo(e) {
    // console.log(e);
    this.setData({
      documentType: e.detail.value
    })
  },
  // 上传身份证正面
  upId(e) {
    let index = e.currentTarget.dataset.index
    let arr = this.data.childArr
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        util.uploadFile("oss/policy", res.tempFilePaths[0], {
          type: "attendants"
        }, true).then((res) => {
          console.log(res);
          if (res.code == 0) {
            arr[index].idCardFront = res.url
            that.setData({
              childArr: arr
            })
            // that.data.positive = res.url
            // that.setData({
            //   positive: that.data.positive
            // })
            // console.log(that.data.positive);
          }
        });
      }
    })

  },
  // 上传反面身份证
  upsideID(e) {
    let index = e.currentTarget.dataset.index
    let arr = this.data.childArr
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res);
        util.uploadFile("oss/policy", res.tempFilePaths[0], {
          type: "attendants"
        }, true).then((res) => {
          console.log(res);
          if (res.code == 0) {
            arr[index].idCardBack = res.url
            that.setData({
              childArr: arr
            })
            // that.data.otherSide = res.url
            // that.setData({
            //   otherSide: that.data.otherSide
            // })
            // console.log(that.data.otherSide);
          }
        });
      }
    })
  },
  // 上传儿童户口本
  upHousehold(e) {
    let index = e.currentTarget.dataset.index
    let arr = this.data.childArr
    // console.log(index);
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res);
        util.uploadFile("oss/policy", res.tempFilePaths[0], {
          type: "attendants"
        }, true).then((res) => {
          console.log(res);
          if (res.code == 0) {
            arr[index].childPage = res.url
            that.setData({
              childArr: arr
            })
            // that.data.Household = res.url
            // that.setData({
            //   Household: that.data.Household
            // })
            // console.log(that.data.Household);
          }
        });
      }
    })
  },
  // 删除图片
  delImage(e) {
    let arr = this.data.childArr
    let index = e.currentTarget.dataset.index
    // console.log(e.currentTarget.dataset.type=="Passporturl);
    let type = e.currentTarget.dataset.type
    console.log(arr[index], type);
    // let url = e.currentTarget.dataset.url
    //儿童护照
    if (type == "Passporturl") {
      arr[index].passport = ''
      this.setData({
        childArr: arr
      })
    } else if (type == "positive") { //正面
      arr[index].idCardFront = ''
      this.setData({
        childArr: arr
      })
    } else if (type == "otherSide") { //反面
      arr[index].idCardBack = ''
      this.setData({
        childArr: arr
      })
    } else if (type == "Household") { //儿童页
      arr[index].childPage = ''
      this.setData({
        childArr: arr
      })
    }

  },
  onShow: function () {

  },
  // 邮寄地址不可更改提示
  popTip() {
    util.showTips('订单已发货，无法修改地址。');
  },
  // 关闭弹窗
  close() {
    this.setData({
      showCodePopup: false
    })
  },
  // 打开尺码推荐弹窗
  CodeDetail() {
    this.setData({
      showCodePopup: true
    })
  },
  // 提交
  submit(e) {
    console.log(this.data.childArr);
    let that = this,
      data = {},
      arr = [];
    if (this.data.documentType == 0) {
      that.setData({
        photoType: 1
      })
    } else {
      that.setData({
        photoType: 2
      })
    }
    for (let i = 0; i < this.data.childArr.length; i++) {
      let obj = {};
      obj.id = this.data.childArr[i].id;
      console.log(obj.id);
      obj.oid = this.data.childArr[i].oid;
      obj.name = this.data.childArr[i].name;
      obj.height = this.data.childArr[i].height;
      obj.weight = this.data.childArr[i].weight;
      obj.bodyType = this.data.childArr[i].bodyType;
      obj.clothesSize = this.data.childArr[i].clothesSize;
      obj.shoesSize = this.data.childArr[i].shoesSize;
      obj.cardType = this.data.childArr[i].cardType
      obj.passport = this.data.childArr[i].passport == null ? '' : this.data.childArr[i].passport; //儿童护照
      obj.idCardFront = this.data.childArr[i].idCardFront == null ? '' : this.data.childArr[i].idCardFront; //儿童身份证正面
      obj.idCardBack = this.data.childArr[i].idCardBack == null ? '' : this.data.childArr[i].idCardBack; //儿童身份证反面
      obj.childPage = this.data.childArr[i].childPage == null ? '' : this.data.childArr[i].childPage; //儿童页
      obj.allergy = this.data.childArr[i].allergy == null ? '' : this.data.childArr[i].allergy;
      obj.diet = this.data.childArr[i].diet == null ? '' : this.data.childArr[i].diet;
      obj.bloodOrMedical = this.data.childArr[i].bloodOrMedical == null ? '' : this.data.childArr[i].bloodOrMedical;
      obj.especiallyRemark = this.data.childArr[i].especiallyRemark == null ? '' : this.data.childArr[i].especiallyRemark;
      obj.photoType = this.data.photoType;
      arr.push(obj)
      console.log(obj);
      if (util.isEmpty(obj.name)) {
        util.showTips('请填写 出行人' + (i + 1) + ' 的姓名。');
        return false;
      }
      if (util.isEmpty(obj.height) || util.isEmpty(obj.weight) || util.isEmpty(obj.bodyType)) {
        util.showTips('请补充 出行人' + (i + 1) + ' 的身高、体重和选择相对应的体型。');
        return false;
      }
      if (that.data.activiteInfo.clothesSize == 1 && util.isEmpty(obj.clothesSize)) {
        util.showTips('因活动需要，请选择 出行人' + (i + 1) + ' 的衣服尺码。');
        return false;
      }
      if (that.data.activiteInfo.needIdcard == 1 && util.isEmpty(obj.shoesSize)) {
        util.showTips('因活动需要，请选择 出行人' + (i + 1) + ' 的鞋码。');
        return false;
      }
      if (that.data.idCard) {
        if (util.isEmpty(obj.allergy)) {
          util.showTips('请填写 出行人' + (i + 1) + '是否有药物或食物过敏');
          return false;
        }
        if (util.isEmpty(obj.diet)) {
          util.showTips('请填写 出行人' + (i + 1) + '是否有饮食禁忌');
          return false;
        }
        if (util.isEmpty(obj.bloodOrMedical)) {
          util.showTips('请填写 出行人' + (i + 1) + '是否特殊血型/有无病史');
          return false;
        } 
        if (util.isEmpty(obj.especiallyRemark)) {
          util.showTips('请填写 出行人' + (i + 1) + '是否有特别备注');
          return false;
        }
      }

    }
    if (that.data.activiteInfo.smailAddress == 'yes' && util.isEmpty(that.data.mailAddress)) {
      util.showTips('邮寄地址不能为空');
      return false;
    }
    if (that.data.activiteInfo.sremark == 'yes' && util.isEmpty(that.data.remark)) {
      util.showTips('备注信息不能为空');
      return false;
    }
    // data.idcards = JSON.stringify(arr);
    data.idcards = arr;
    data.mailAddress = that.data.mailAddress;
    data.orderid = that.data.orderId;
    data.remark = that.data.remark;

    util.ajax({
      func: "v2/order/attendants/save",
      data: data,
      method: 'POST'
    }, function (res) {
      console.log(res);
      if (res.code == 0) {
        util.showTips(res.reason);
        setTimeout(() => {
          if (that.data.firstPagePath == 'pages/order/orderDetailList/index') { //小程序码进入
            wx.redirectTo({
              url: '/pages/order/detail/index?orderid=' + that.data.orderId + '&otype=' + that.data.otype + '&presellStatus=0',
            })
          } else { //订单详情页进入
            wx.navigateBack({
              delta: 1
            })
          }
        }, 500);
      } else {
        util.showTips(res.reason);
      }
    })
  },
  // 修改邮寄地址
  chooseAddress() {
    this.setData({
      showAddress: true
    })
  },
  submitAddress(e) {
    let that = this,
      data = e.detail;
    this.setData({
      'mailAddress': data.name + ' ' + data.mobile + ' ' + data.provincial + ' ' + data.address
    });
  },
  // 填写备注
  textareaInput(e) {
    let value = e.detail.value;
    this.setData({
      remark: value
    })
  },
  // 输入框填写/体型/尺码
  bindinput(e) {
    let index = e.currentTarget.dataset.index,
      type = e.currentTarget.dataset.name,
      value = e.detail.value,
      data = this.data.childArr;
    data[index][type] = value;
    console.log(e, data);
    if (type == 'clothesIndex') {
      data[index].clothesSize = data[index].clothesCode[value];
    }
    if (type == 'shoesIndex') {
      data[index].shoesSize = data[index].shoesCode[value];
    }
    this.setData({
      childArr: data
    })
  },
  // 获取年龄段的尺码
  satisfy(obj) {
    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 newDate = new Date(obj.birthdayStr).getTime();
    // let ageType = oldDate < newDate ? true : false; // true 表示不满18
    if (oldDate < newDate) {
      obj.clothesCode = [110, 120, 130, 140, 150, 160, 165, 170, 175, 180, 185];
      obj.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 (obj.sex == 1) {
        obj.clothesCode = [165, 170, 175, 180, 185];
        obj.shoesCode = [39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49];
      } else {
        obj.clothesCode = [155, 160, 165, 170, 175];
        obj.shoesCode = [33, 34, 35, 36, 37, 38, 39, 40, 41];
      }
    }
    obj.clothesIndex = this.getCodeIndex(obj.clothesCode, obj.clothesSize);
    obj.idCardType = util.cardType(obj.cardType)
    obj.shoesIndex = this.getCodeIndex(obj.shoesCode, obj.shoesSize);
    return obj;
  },
  // 获取尺码索引
  getCodeIndex(arr, val) {
    let index = -1;
    arr.forEach((el, i) => {
      if (!util.isEmpty(val)) {
        if (el == val) {
          index = i;
        }
      } else {
        index = -1;
      }
    });
    return index;
  },
  // 获取出行人信息
  getDetail() {
    let that = this;
    util.ajax({
      func: "v2/order/attendants",
      load: false,
      data: {
        "orderid": that.data.orderId
      }
    }, function ({
      data,
      code
    }) {
      console.log(data);
      if (code == 0) {
        data.forEach((e) => {
          // sparent为0时是亲子营,articleType为1时满足条件
          // 不是亲子营且满足活动条件
          if (e.sparent != 0 && e.articleType) {
            that.setData({
              information: true,
              idCard: true
            })
          }
          // 非亲子营
          else if (e.sparent) {
            that.setData({
              idCard: true
            })
          } else if (e.sparent == 0) {
            that.setData({
              idCard: false
            })
          }
        })
        let arr = [];
        data.forEach(el => {
          // console.log(el);
          if (!util.isEmpty(el.attendants)) {
            el.attendants = JSON.parse(el.attendants)
            el.config = JSON.parse(el.config)
            el.attendants = that.satisfy(el.attendants[0]);
            el.attendants.oid = el.oid;
            el.attendants.passport = el.passport;
            el.attendants.idCardFront = el.idCardFront;
            el.attendants.idCardBack = el.idCardBack;
            el.attendants.childPage = el.childPage;
            el.attendants.allergy = el.allergy
            el.attendants.diet = el.diet
            el.attendants.bloodOrMedical = el.bloodOrMedical
            el.attendants.especiallyRemark = el.especiallyRemark
            arr.push(el.attendants)
          }
        });
        console.log(arr);
        that.setData({
          childArr: arr,
          showData: true
        })
      } else {
        util.showTips(res.reason + ' ,将自动返回上一页');
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 2000);
      }
    })
  },
  // 获取订单活动信息
  getOrderDetail() {
    let that = this;
    util.ajax({
      func: "v2/order/detail",
      load: false,
      data: {
        "orderid": that.data.orderId,
        otype: that.data.otype,
      }
    }, function (res) {
      console.log(res);
      if (res.code == 0) {
        that.setData({
          info: res.data,
          mailAddress: res.data.mailAddress || '',
          remark: res.data.remark || ''
        })
        that.getActiviteInfo(res.data.aid)
      } else {
        if (that.data.otype == 2) {
          that.setData({
            otype: 3
          })
          that.getOrderDetail()
        } else {
          util.showTips(res.reason);
        }
      }
    })
  },
  // 获取活动详情信息
  getActiviteInfo(aid) {
    let that = this;
    util.ajax({
      func: "v2/article/detail",
      load: false,
      data: {
        "aid": aid
      }
    }, function (res) {
      if (res.code == 0) {
        that.setData({
          activiteInfo: res.data
        })
      } else {
        util.showTips(res.reason);
      }
    })
  },
  errorImg() {
    this.data.info.logo = "/images/noimg.png";
    this.setData({
      info: this.data.info
    });
  },
  onShareAppMessage: function () {
    return {
      title: '为保证更好的参与活动，快来核对参与者信息吧~',
      path: '/pages/order/orderDetailList/index?aid=' + this.data.info.aid,
      imageUrl: '../images/share.png'
    }
  }
})