// pages/newTeam/newTeam.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isAgree: false, // 是否同意志愿者注册协议
    index: 0,
    array: ['区域1','区域2','区域3','区域4'],
    photo: '', // 用于页面显示的photo链接
    uploadPhoto: '', // 用于传到后台的photoId
    teamName: '',
    count:'',
    teamWatchword: '',
    content: '',

    tempObj: {}, // 用于临时存储字典表返回的数据
    tempArray: [], // 用于临时存储字典表返回的数据

    teamCityIndex: 0,
    teamCityResult: '请选择服务区域',
    teamCity: {}, // 服务区域-市
    teamCityArray: [], // 服务区域-市
    
    teamCountyIndex: 0,
    teamCountyResult: '请选择旗县区',
    teamCounty: {}, // 服务区域-旗县区
    teamCountyArray: [], // 服务区域-旗县区

    teamAreaIndex: 0,
    teamAreaResult: '请选择乡镇村',
    teamArea: {}, // 服务区域-乡镇村
    teamAreaArray: [], // 服务区域-乡镇村

    countyShowStatus: true,
    areaShowStatus: true
  },
  getToken: function() {
    var self = this;
    return new Promise(resolve =>{
      wx.getStorage({
        key: 'token',
        success(res) {
          self.setData({
            token: res.data
          })
          return resolve();
        }
      })
    })
  },
  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    })
  },
  /**
   * 上传活动照片
   */
  uploadPhoto: function () {
    var self = this
    wx.chooseImage({
      success (res) {
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        app.restAjax.file(app.restAjax.path(app.volunteerUrl + '/app/file/uploadimage', []), tempFilePaths[0], 
          'image', {
            headers: {
              token: self.data.token
            }
          }, function(code, data) {
            if('200' == code) {
              var data = data.substr(9, data.length);
              data = data.substr(0, data.length - 2);
              self.setData({
                photo: app.volunteerUrl + '/route/file/download/true/' + data,
                uploadPhoto: data
              })
            }
        }, function(code, data) {
          app.dialog.msg(data.msg)
        }, function() {
          
        })
      }
    })
   },
   cityChange: function(e) {
     var self = this;
     self.setData({
       teamCityIndex: e.detail.value,
       areaShowStatus: true,
       teamArea: {},
       teamAreaArray: []
     })
 
     this.getDataFromArea(self.data.teamCity[self.data.teamCityIndex].areaId, 2).then(result => {
       if(self.data.tempObj.length > 0) {
         self.setData({
           teamCounty: self.data.tempObj,
           teamCountyArray: self.data.tempArray,
           countyShowStatus: false,
           tempObj: {},
           tempArray: []
         })
       }else {
         self.setData({
           teamCounty: {},
           teamCountyArray: [],
           countyShowStatus: true,
           tempObj: {},
           tempArray: []
         })
       }
     });
   },
   countyChange: function(e) {
     var self = this;
     self.setData({
       teamCountyIndex: e.detail.value
     })
 
     this.getDataFromArea(self.data.teamCounty[self.data.teamCountyIndex].areaId, 2).then(result => {
       if(self.data.tempObj.length > 0) {
         self.setData({
           teamArea: self.data.tempObj,
           teamAreaArray: self.data.tempArray,
           areaShowStatus: false,
           tempObj: {},
           tempArray: []
         })
       }else {
         self.setData({
           teamArea: {},
           teamAreaArray: [],
           areaShowStatus: true,
           tempObj: {},
           tempArray: []
         })
       }
     })
   },
   areaChange: function(e) {
    var self = this;
    self.setData({
      teamAreaIndex: e.detail.value
    })
  },
  userAgree: function(e) {
    var type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '../userAgree/userAgree?type=' + type,
    })
  },
   changeAgree: function (e) {
    if(e.detail.value == ''){
      this.setData({
        isAgree: false
      })
    }else{
      this.setData({
        isAgree: true
      })
    }
  },
  submitRegister: function () {
    var self = this;
    if(!self.data.isAgree) {
      wx.showToast({
        title: '请阅读并同意《团队注册服务协议》',
        icon: 'none',
        duration: 1500
      })
      return false;  
    }
    var teamVO  = {
      photo: self.data.uploadPhoto,
      teamName: self.data.teamName,
      count:self.data.count,
      teamWatchword: self.data.teamWatchword,
      content: self.data.content,
      agree: self.data.isAgree,
      teamCity: self.data.teamCity[self.data.teamCityIndex] != '' 
                  && self.data.teamCity[self.data.teamCityIndex] != null
                  && self.data.teamCity[self.data.teamCityIndex] != 'undefined' ?
                  self.data.teamCity[self.data.teamCityIndex].dictionaryId : 
                  '',
      teamCounty: self.data.teamCounty[self.data.teamCountyIndex] != ''
                    && self.data.teamCounty[self.data.teamCountyIndex] != null
                    && self.data.teamCounty[self.data.teamCountyIndex] != 'undefined' ?
                    self.data.teamCounty[self.data.teamCountyIndex].dictionaryId : 
                    '',
      teamArea: self.data.teamArea[self.data.teamAreaIndex] != ''
                  && self.data.teamArea[self.data.teamAreaIndex] != null
                  && self.data.teamArea[self.data.teamAreaIndex] != 'undefined' ?
                  self.data.teamArea[self.data.teamAreaIndex].dictionaryId : 
                  '',
    };
    app.restAjax.post(app.restAjax.path(app.volunteerUrl + '/wechat-miniapp/team/saveteam', []), 
      teamVO, {
        headers: {
          'token': self.data.token
        }
      }, function(code, data) {
		    if('200' == code) {
          app.dialog.msg('注册成功')
          wx.navigateTo({
            url: '../volunteer/volunteer',
          })
        }
    }, function(code, data) {
      app.dialog.msg(data.msg)
    }, function() {
      
    })
  },
   /**
   *从字典表拉取数据 
   */
  getDataFromDict: function(dictId, type) {
    var self = this;
    return new Promise(resolve => {
      app.restAjax.get(app.restAjax.path(app.volunteerUrl + '/app/datadictionary/listdictionarybyparentid/' + dictId, []), 
      {}, {
        headers: {
          token: self.data.token
        }
      }, function(code, data) {
          if('200' == code) {
            var array = [];
              for(var item of data) {
                delete item.dictionaryParentId;
                delete item.dictionaryParentName;
                delete item.dictionarySummary;
                delete item.dictionaryCode;
                delete item.dictionarySort;
                delete item.subDictionary;
                delete item.parent;
                
                array.push(item.dictionaryName);
              }
              self.setData({
                tempArray: array
              })
            }
            self.setData({
              tempObj: data
            })
            return resolve();
      }, function() {

      }, function() {
        
      })
    })
  },
  /**
   *从区域表拉取数据
   */
  getDataFromArea: function(dictId, type) {
    var self = this;
    return new Promise(resolve => {
      app.restAjax.get(app.restAjax.path(app.volunteerUrl + '/app/area/listallbyparentidrelease/' + dictId, []), 
        {}, {
          headers: {
            'token': self.data.token
          }
        }, function(code, data) {
          console.log(data)
          if('200' == code) {
            if(data || type === 2) {
              var array = [];
              for(var item of data) {
                delete item.areaParentId;
                delete item.areaParentName;
                delete item.areaCode;
                delete item.areaCityCode;
                delete item.areaMergerName;
                delete item.areaShortName;
                delete item.areaZipCode;
                delete item.areaLevel;
                delete item.areaLng;
                delete item.areaLat;
                delete item.areaPinyin;
                delete item.areaFirst;
                delete item.subArea;
                delete item.parent;
                
                array.push(item.areaName);
              }
              self.setData({
                tempArray: array
              })
            }
            self.setData({
              tempObj: data
            })
          }
        return resolve();
      }, function() {

      }, function() {
        
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this;
    this.getToken().then(result => {
      console.log(self.data.token)
      this.getDataFromArea('640675', 2).then(result => {
        self.setData({
          teamCity: self.data.tempObj,
          teamCityArray: self.data.tempArray,
          tempObj: {},
          tempArray: []
        })
      })
    })
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})