// pages/kids_information/kids_information.js
import { routers, viewImage, sharePage, isFn, getGlobalVal, formatDateTime, formateNumber,curatorName,formatEncrypt } from '../../utils/util.js'
import { AddChild,AddChildV1} from '../../utils/api.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const { globalData, saveUserInfo, getWxloginCode, checkStatus } = getApp()
const { baseImgUrl, thumbnail } = globalData
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    options: {},
    baseImgUrl,
    isShowPickerModel: false,
    phone:'',
    patriarchName:'',
    homeAddress:'',
    studyPlanName:'',
    isAddChild:0,
    studentImg:'',
    isAdd:false,
    imgUrl:'',
    school: '',
    childName: '',
    parentName: '',
    sex: 0,
    grade: '',
    parentRole:'',
    pickerData: [
      {
        actIndex: 0,
        list: ['一年级', '二年级', '三年级', '四年级', '五年级', '六年级']
      },
      {
        actIndex: 0,
        list: ['语文', '数学', '英文']
      },
      {
        actIndex: 0,
        list: ['男', '女']
      },
      {
        actIndex: 0,
        list: ['基础', '巩固','培优']
      },
      {
        actIndex: 0,
        list: ['爸爸', '妈妈', '爷爷','奶奶','外公','外婆','其他']
      }
    ],
    pickerIndex: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData(options)
    console.log(options)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const obj = { navigateTo, redirectTo, navigateBack, viewImage }
    for (const i in obj) {
      this[i] = obj[i]
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      var list = wx.getStorageSync('list');
    var bookList = [];
      for (var i in list) {
        bookList = bookList.concat(list[i].bookList)
      }   
      console.log(bookList)
      // var bookList = [];
      // for (var i in arr) {
      //   bookList.push({ bookId: arr[i].bookId, subject: arr[i].subject, bookName: arr[i].bookName, })
      // }
      // 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,
  /**
   * 添加教辅
   */
  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'
        })
      }
    }
    
  },

  
  /**
   * 上传头像
   */
  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 })

      }
    }
  },

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

  /**
   * 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(index, pickerIndex)
    // if (index < 0) {
      if (pickerIndex == 0) {
        if (this.data['grade'] != list[actIndex]) {
          temp['grade'] = list[index]
          
          // this.setData({ grade: list[actIndex] })
        }
      } else if (pickerIndex == 1) {
        if (this.data['courseName'] != list[actIndex]) {
          temp['courseName'] = list[index]
          // this.setData({ courseName: list[actIndex]})
        }
      } else if (pickerIndex == 2) {
        // if (this.data['sex'] != actIndex + 1) {
        temp['sex'] = Number(index) + 1
        // console.log(String(index) )
          // this.setData({ sex: actIndex + 1 })
        // }
      } else if (pickerIndex == 3) {
        if (this.data['studyPlan'] != list[actIndex]) {
          temp['studyPlan'] = list[index]
          // this.setData({ studyPlan: list[actIndex] })
        }
      } else if (pickerIndex == 4) {
        if (this.data['parentRole'] != list[actIndex]) {
          temp['parentRole'] = list[index]
          // this.setData({ parentRole: list[actIndex] })
        }
      } 
    // }else {
    //   temp[str] = index
    // }
    temp['isShowPickerModel'] = false
    this.setData(temp)
  },
  /**
   * 添加孩子
   */
  addChildren:function(cb){
    const continuousFn = { fn: this.addChildren, param: { ...arguments } }
    var that = this;
    const { childName, parentName, phone, grade, school, parentRole, imgUrl, sex, bookList, classId='',className} = this.data;
    // console.log(childName, parentName, phone, grade, school, parentRole, imgUrl, sex, bookList, classId);
    if (!childName) {
      wx.showToast({
        title: '请输入学生姓名',
        icon: 'none'
      })
      return
    }
    if (!parentName) {
      wx.showToast({
        title: '请输入家长姓名',
        icon: 'none'
      })
      return
    }
    if (!phone) {
      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
    }
    AddChildV1({ data: {
       childName:formatEncrypt(childName),
       parentName:formatEncrypt(parentName),
       phone:formatEncrypt(phone),
       grade, 
       school:formatEncrypt(school), 
       parentRole, 
       imgUrl, 
       sex:Number(sex), 
       bookList, 
       classId
    }, continuousFn }).then(res => {
      wx.showToast({
        title: '添加成功',
        duration: 1000
      })
      wx.removeStorageSync('list')
      setTimeout((function callback() {
        wx.navigateBack({
          delta: 2
        })
      }).bind(this), 1000);
      if (isFn(cb)) cb()
    }).catch(res => {
      if (isFn(cb)) cb()
    })
  },
  
})