// pages/kids_information/kids_information.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    options: {},
    baseImgUrl: app.globalData.baseImgUrl,
    isShowPickerModel: false,
    phone:'',
    patriarchName:'',
    homeAddress:'',
    studyPlanName:'',
    isAddChild:1,
    studentImg:'',
    isAdd:false,
    isType:2,
    isWechat:1,
    isShow:false,
    pickerData: [
      {
        actIndex: 1,
        list: ['学前', '一年级', '二年级', '三年级', '四年级', '五年级', '六年级']
      },
      {
        actIndex: 0,
        list: ['语文', '数学', '英文']
      },
      {
        actIndex: 0,
        list: ['男', '女']
      },
      {
        actIndex: 0,
        list: ['基础', '巩固','培优']
      },
      {
        actIndex: 0,
        list: ['爸爸', '妈妈', '爷爷','奶奶','外公','外婆','其他']
      }
    ],
    pickerIndex: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData(options)
    console.log(options)
    if (!options.vipId) {
      const userId = app.globalData.userId || wx.getStorageSync('userId')
      const vipId = app.globalData.parentVipId || wx.getStorageSync(`parentVipId-${userId}`)
      options.vipId = vipId
      options.userId = userId
      this.setData({ options });
    }
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getMyInfo();
    const { isAddChild}=this.data;
    if (isAddChild == 1) {
      var list = wx.getStorageSync('list');
      var arr = [];
      for (var i in list) {
        arr = arr.concat(list[i].bookList)
      }
      var bookList = [];
      for (var i in arr) {
        bookList.push({ bookId: arr[i].bookId, subject: arr[i].subject, bookName: arr[i].bookName, })
      }
      console.log(bookList)
      if (bookList.length > 0) {
        this.setData({ isAdd: true });
      } else {
        this.setData({ isAdd: false });
      }
      this.setData({ bookList });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 路由跳转
   */
  redirectCtl: app.redirectCtl,

  /**
   * 路由跳转
   */
  navigateCtl: app.navigateCtl,
 
  
  /**
  * 我的信息
  */
  getMyInfo: function () {
    const {derver} = this.data;
    const postData = { fn: this.getChildInfo, param: { ...arguments } }
    wx.showLoading({
      title: '加载中',
    })
    app.post('/api/parents/parents/V2/getMyInfo', {}, 0, postData).then(res => {
      const { childList, phone } = res.data;
      if (!phone) {
        this.redirectCtl({ url: 'phone', method: { isFrist: 0, derver } }, true)
      }else{
        wx.hideLoading();
        this.setData({ isShow: true })
      }
      
    })
  },
  /**
   * 添加教辅
   */
  addTeaching: function () {
    const { vipId, grade, isAddChild, isAdd } = this.data;
    const { imgUrl, childName, sex, parentName, phone, courseName, school, family, studyPlan, parentRole } = this.data;
    var obj = { vipId, imgUrl, childName, sex, parentName, phone, courseName, grade, school, family, studyPlan, parentRole };
    var that = this;
    if (isAddChild != 1) {
      if (grade) {
        that.navigateCtl({ url: 'teaching', method: { vipId, grade, isAddChild, obj: JSON.stringify(obj) } }, true)
      } else {
        wx.showToast({
          title: '请先选择年级',
          icon: 'none'
        })
      }
    } else {
      if (grade) {
        that.navigateCtl({ url: 'teaching', method: { grade, isAddChild, isAdd } }, true)
      } else {
        wx.showToast({
          title: '请先选择年级',
          icon: 'none'
        })
      }
    }

  },
  /**
  * 添加机构
  */
  addOrgam: function () {
    const { vipId, grade, isAddChild, isAdd } = this.data;
    const { imgUrl, childName, sex, parentName, phone, courseName, school, family, studyPlan, parentRole } = this.data;
    var obj = { vipId, imgUrl, childName, sex, parentName, phone, courseName, grade, school, family, studyPlan, parentRole };
    var that = this;
    that.navigateCtl({ url: 'studyHouse', method: { vipId, grade, isAddChild, isAddOrgam: 1,isWechat:1, obj: JSON.stringify(obj) } }, true)
  },
  /**
   * 获取个人信息
   */
  // getInformation: function (e) {
  //   const postData = { fn: this.getInformation, param: { ...arguments } }
  //   const { vipId, school } = this.data
  //   app.post('/api/parents/parents/V2/getMyChildInfo', { vipId }, 0, postData).then(res => {
  //     // console.log(res.data)
  //     this.setData({ ...res.data })
  //     if (school && school != '' && res.data.school != school) {
  //       this.setData({ school:school })
  //     }
  //   })
  // },

  /**
   * 修改个人信息
   */
  updateInfor: function (obj, type) {
    const postData = { fn: this.updateInfor, param: { ...arguments } }
    app.post('/api/parents/parents/V2/upMyChildInfo', obj, 0, postData).then(res => {
      wx.showToast({
        title: '保存成功',
        icon: 'none'
      })
      if (type == 1) {
        this.setData(obj)
      }
    })
  },

  /**
   * 上传头像
   */
  uploadHeadIconCtl: function () {
    wx.chooseImage({
      count: 1,
      success: res => {
        this.uploadImage(res.tempFilePaths[0])
      },
      fail: res => {
        // wx.showToast({
        //   title: '选择拍照或者相册失败',
        //   icon: 'none'
        // })
      }
    })
  },

  /**
   * 上传头像接口
   */
  uploadImage: function (file) {
    app.uploadFile('/api/common/common/uploadForm', file, {}).then(res => {
      let { filePath } = JSON.parse(res).data.pics[0];
      console.log(filePath);
      this.setData({ imgUrl: filePath})
      // this.updateInfor({
      //   imageKey: filePath
      // }, 1)
    })
  },

  /**
   * input
   */
  inputCtl: function (e) {
    const mobileExp = /^1[0-9]{10}$/;
    const { temp = {}, type } = e.currentTarget.dataset
    const { value } = e.detail
    temp[type] = value;
    const { parentName, family,phone,childName } = temp;
    console.log(parentName)
    if (type == 'phone') {
      if (value != '') {
        if (!mobileExp.test(value)) {
          wx.showToast({
            title: '手机号码位数不对',
            icon: 'none',
            duration: 2000
          })
          return this.setData({ phone})
        } else {
          return this.setData({ phone })
        }
      }
    } else if (type == 'childName') {
      // if (value != '') {
        return this.setData({ childName })
      // }
    }  else if (type == 'parentName') {
      // if (value != '') {
        return this.setData({ parentName })

      // }
    } else if (type == 'family') {
      if (value != '') {
        return this.setData({ family })

      }
    }
    
    // if (this.data[type] != value) {
    //   this.updateInfor({ [type]: e.detail.value })
    // }
  },

  /**
   * picker
   */
  pickerCtl: function (e) {
    const { temp = {}, type, index } = e.currentTarget.dataset
    this.setData({
      pickerIndex: index,
      isShowPickerModel: true
    })
  },

  /**
   * picker选择列
   */
  checkPickerModel: function (e) {
    const { index } = e.currentTarget.dataset
    let { temp = {}, pickerIndex, pickerData } = this.data
    let { actIndex, list } = pickerData[pickerIndex]
    let str = `pickerData[${pickerIndex}].actIndex`;
    console.log(pickerIndex, pickerData)
    if (index < 0) {
      if (pickerIndex == 0) {
        if (this.data['grade'] != list[actIndex]) {
          temp['grade'] = list[actIndex]
          this.setData({ grade: list[actIndex] })
        }
      } else if (pickerIndex == 1) {
        if (this.data['courseName'] != list[actIndex]) {
          temp['courseName'] = list[actIndex]
          this.setData({ courseName: list[actIndex]})
        }
      } else if (pickerIndex == 2) {
        if (this.data['sex'] != actIndex + 1) {
          temp['sex'] = actIndex + 1
          this.setData({ sex: actIndex + 1 })
        }
      } else if (pickerIndex == 3) {
        if (this.data['studyPlan'] != list[actIndex]) {
          temp['studyPlan'] = list[actIndex]
          this.setData({ studyPlan: list[actIndex] })
        }
      } else if (pickerIndex == 4) {
        if (this.data['parentRole'] != list[actIndex]) {
          temp['parentRole'] = list[actIndex]
          this.setData({ parentRole: list[actIndex] })
        }
      } 
    }else {
      temp[str] = index
    }
    temp['isShowPickerModel'] = index > -1
    this.setData(temp)
  },
  
  /**
   * 添加孩子
   */
  addChildren:function(){
    var _that=this;
    const postData = { fn: this.addChildren, param: { ...arguments } }
    const { imgUrl, childName, sex, parentName, phone, grade, school, parentRole, bookList, isType, derver} = this.data;
    console.log(imgUrl, childName, sex, parentName, isType, phone, grade, school, bookList, derver, libId);
    if (!childName) {
      wx.showToast({
        title: '请输入孩子姓名',
        icon: 'none'
      })
      return
    }
    if (!parentName) {
      wx.showToast({
        title: '请输入家长姓名',
        icon: 'none'
      })
      return
    }
    if (!grade) {
      wx.showToast({
        title: '请输入年级',
        icon: 'none'
      })
      return
    }
    if (!school) {
      wx.showToast({
        title: '请输入在读学校',
        icon: 'none'
      })
      return
    }
    if (!parentRole) {
      wx.showToast({
        title: '请输入家长角色',
        icon: 'none'
      })
      return
    }
    app.post('/api/parents/parents/V2/addChild', {
      imgUrl,
      childName,
      sex,
      parentName,
      phone,
      grade,
      school,
      type: 2,
      parentRole,
      bookList,
      derver,
      libId
    }, 0, postData).then(res => {
      const { vipId } = _that.data;
      wx.showToast({
        title: '添加成功',
        icon: 'none',
        duration: 1000
      })
      wx.removeStorageSync('list')
      app.redirectCtl({ url: 'me', method: {} }, true)
      // _that.getMyInfo(vipId)
      // setTimeout((function callback() {
      //   wx.navigateBack({});
      // }).bind(this), 500);
      
    })
   
  }
  
})