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

  /**
   * 页面的初始数据
   */
  data: {
    token: '',
    volunteerMsg: [],
    isAgree: false, // 是否同意志愿者注册协议
    openExperience: 0,
    tempObj: {}, // 用于临时存储字典表返回的数据
    tempArray: [], // 用于临时存储字典表返回的数据
    serviceType: {}, // 服务类别
    serviceTypeValue: '', // 用户选择的服务类别ID
    serviceIndustry: {}, // 服务领域或行业
    serviceIndustryValue: '', // 用户选择的服务领域或行业ID

    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();
        }
      })
    })
  },
  cityChange: function(e) {
    var self = this;
    self.setData({
      teamCityIndex: e.detail.value,
      areaShowStatus: true,
      teamArea: {},
      teamAreaArray: []
    })

    this.getDataFromDict(self.data.teamCity[self.data.teamCityIndex].dictionaryId, 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.getDataFromDict(self.data.teamCounty[self.data.teamCountyIndex].dictionaryId, 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
    })
  },
  changeOpen: function(e) {
    if(e.detail.value == ''){
      this.setData({
        openExperience: 0
      })
    }else{
      this.setData({
        openExperience: 1
      })
    }
  },
  changeAgree: function (e) {
    if(e.detail.value == ''){
      this.setData({
        isAgree: false
      })
    }else{
      this.setData({
        isAgree: true
      })
    }
  },
  /**
   * 服务类别选择
   * @param {}} e 
   */
  serviceTypeChange: function(e) {
    console.log(e)
    var self = this;
    var selData = e.detail.value;
    if(selData) {
      var dataValueStr = '';
      for(var item of selData) {
        dataValueStr +=item + ",";
      }
      if (dataValueStr.length > 0) {
        dataValueStr = dataValueStr.substr(0,dataValueStr.length - 1);
      }
      self.setData({
        serviceTypeValue: dataValueStr
      })
    }
  },
  /**
   * 服务领域或行业选择
   * @param {}} e 
   */
  serviceIndustryChange: function(e) {
    var self = this;
    var selData = e.detail.value;
    if(selData) {
      var dataValueStr = '';
      for(var item of selData) {
        dataValueStr +=item + ",";
      }
      if (dataValueStr.length > 0) {
        dataValueStr = dataValueStr.substr(0,dataValueStr.length - 1);
      }
      self.setData({
        serviceIndustryValue: dataValueStr
      })
    }
  },
  submitRegister: function () {
    var self = this;
    if(!self.data.isAgree) {
      wx.showToast({
        title: '请阅读并同意《志愿者注册服务协议》',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    var volunteerVO = {
      serviceCity: 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 : 
                  '',
      serviceCounty: 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 : 
                    '',
      serviceArea: 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 : 
                  '',
      serviceType: self.data.serviceTypeValue,
      serviceIndustry: self.data.serviceIndustryValue,
      agree: self.data.isAgree,
      openExperience : self.data.openExperience
    };
    var url;
    if(!self.data.volunteerMsg) {
      url = '/wxminiapp/volunteer/savevolunteer';
    }else {
      url = '/wxminiapp/volunteer/updatevolunteer/' + self.data.volunteerMsg.volunteerId;
    }
    app.restAjax.post(app.restAjax.path(app.volunteerUrl + url, []), 
      volunteerVO, {
        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) {
            if(data || type === 2) {
              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() {
        
      })
    })
  },
  getVolunteerMsg() {
    var self = this;
    return new Promise(resolve => {
      app.restAjax.get(app.restAjax.path(app.volunteerUrl + '/wxminiapp/volunteer/getvolunteerbyuserid', []), 
        {}, {
          headers: {
            'token': self.data.token
          }
        }, function(code, data) {
          if('200' == code) {
            self.setData({
              volunteerMsg: data
            })
          }
        return resolve();
      }, function() {

      }, function() {
        
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this;
    this.getToken().then(result => {
      this.getVolunteerMsg().then(result => {
        this.getDataFromDict('a223b308-014a-4e89-93fa-035a564e7fda', 1).then(result => {
          self.setData({
            serviceType: self.data.tempObj,
            tempObj: {}
          })
        }).then(result => {
          this.getDataFromDict('7b213c37-8575-4db3-bda1-86c4e38589f7', 1).then(result => {
            self.setData({
              serviceIndustry: self.data.tempObj,
              tempObj: {}
            })
          })
        }).then(result => {
          this.getDataFromDict('4a03e904-81e2-48e9-9006-e15ea4a6bc69', 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 () {

  }
})