// pages/post/post.js
const app = getApp()
const host = app.globalData.host;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sexArray: ["男","女"],    //性别
    recordArray: ["初中", "高中或同等学历", "中专或同等学历", "专科或同等学历", "本科或同等学历","研究生以上"], //学历
    categoryArray: [{ label: '电工', id: 0 }, { label: '水工', id: 1 }], //作业类别
    subjectArray: [{name:'请选择'}],    //准操项目
    trainArray: [{ name: '新办', intro: '第一次取证；或者以前取证了没有按规定的时间复审、换证' }, 
    { name: '复审', intro: '已取证；复审日期一天都不超最好提前3个月' }, 
    { name: '换证', intro: '有效期满提前三个月' }],    //培训类型
    receiveArray: ['自取','邮寄（将产生邮寄费用）'],    //领取类型
    sex:0,
    record:0,
    category:-1,
    subject:-1,
    train:-1,
    receive:0,
    area: ['四川省', '成都市', '锦江区'],
    time:'2020-01-01',
    price:'0.00',
    classList:[],
    class_:-1,
    class_id:0,
    data:{},
    type:0,
    device_cats:[],
    dev:[],
    show_dev:false,
    subject_item0:"",
    selectClass:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      type: options.type,
      subject_item0:options.s_name,
      selectClass:options.s_name.indexOf("特种")!=-1?false:true
    })
    var sub_list=[],user={}
    //获取用户信息
    wx.request({
      url: host + '/api/wx/authinfo',
      header: {
        openid: app.globalData.openid
      },
      success: res => {
        user = res.data.data
        if (options.type != 2 && user){
            this.setData({
              name:user.name,
              company: user.company,
              phone:user.phone,
              idno: user.idno,
              sex:user.sex=='男'?0:1,
              record: this.data.recordArray.indexOf(user.education),
            })
        }
      }
    })
    wx.request({
      url: host + '/api/wx/sujectitem',
      success: res => {
        sub_list = res.data.data       
        // options：s_name  分类名称    s_id 分类id  class_id  班级id
        //新增报名
        if (options.type == 1){
          //班级列表
          wx.request({
            url: host + '/api/wx/class/list?signup=1&subject_item0=' + options.s_name,
            method: 'GET',
            success: res => {
              // 过滤分类
              let list = sub_list.filter(item => item.id == options.s_id)
              this.setData({
                categoryArray: list[0].children,
                z_type: list[0].name,     //提交时拼接subject_item
                classList: res.data.data
              })
            }
          })
        }
        //修改报名
        if(options.type == 2){
          wx.showLoading({
            title: '',
          })
            wx.request({
              url: host+'/api/wx/signup',
              method:'GET',
              data:{id:options.id},
              success:res=>{
                wx.hideLoading()
                let data = res.data.data, subject_item = data.subject_item.split('|');
                let list = sub_list.filter(item => item.name == subject_item[0]);
                let categoryArray = list[0].children, subject = 0,
                    subjectArray = [], category = 0, train=0;
                //定位分类下拉选项
                for(let i=0;i<categoryArray.length;i++){
                  if (categoryArray[i].name == subject_item[1]){
                    category=i
                    subjectArray = categoryArray[i].children
                    for(let j=0;j<subjectArray.length;j++){
                      if (subjectArray[j].name == subject_item[2]){
                            subject=j
                        }
                    }
                    }
                }
                for(let i=0;i<this.data.trainArray.length;i++){
                  if (this.data.trainArray[i].name == data.train_type){
                    train=i
                    }
                }
                //获取班级列表
                wx.request({
                  url: host + '/api/wx/class/list' ,
                  method: 'GET',
                  data:{
                    subject_item0: subject_item[0],
                    subject_item1: subject_item[1],
                    subject_item2: subject_item[2]
                  },
                  success: res => {
                    let class_ = 0, classes=[];
                    if (res.data.data.length>0){
                      classes = res.data.data[0].classes;
                      for(let i=0;i<classes.length;i++){
                        if (classes[i].cid == data.class_id){
                          class_=i
                          }
                      }
                    }
                    this.setData({
                      classList: classes,
                      class_: class_
                    })
                  }
                })
                this.setData({
                  z_type: subject_item[0],
                  sex:data.sex=='男' ? 0 :1,
                  record: this.data.recordArray.indexOf(data.education),
                  receive: data.receive_card == '自取' ? 0 : 1,
                  categoryArray: categoryArray,
                  subjectArray: subjectArray,
                  category: category,
                  subject: subject,
                  train: train,
                  area:data.area.split(' '),
                  device_cats: categoryArray[category].device_cats,
                  dev: data.device_cats ? data.device_cats.join(' , '):''
                })
                
                this.setData({
                  data: res.data.data
                })
              }
            })
        }
        //班级报名
        if(options.type == 3){
          this.setData({
            parice_list: options.price.split('_'),
            class_id: options.class_id
          })
        } 
      }
    })
      
  },
  getClass(){
    let category = this.data.category>=0 ? this.data.categoryArray[this.data.category].name:'',
      subject = this.data.subject >= 0 ? this.data.subjectArray[this.data.subject].name : ''
    wx.request({
      url: host + '/api/wx/class/list?signup=1',
      method: 'GET',
      data:{
        subject_item0: this.data.z_type,
        subject_item1: category,
        subject_item2: subject
      },
      success: res => {
        // 过滤分类
        this.setData({
          classList: res.data.data
        })
      }
    })
  },
  sure:function(){
    if(this.data.dev==''){
      wx.showToast({
        title: '请选择设备种类！',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    this.setData({
      show_dev: false,
    })
  },
  checkboxChange:function(e){
      console.log('checkbox发生change事件，携带value值为：', e.detail.value)
      const values = e.detail.value
      this.setData({
        dev: e.detail.value.join(' , ')
      })
    
  },
  open:function(){
    this.setData({
      show_dev: true,
    })
  },
  pickerChange:function(e){
    if(e.target.dataset.name == 'sex'){
      this.setData({
        sex: e.detail.value
      })
    };
    if (e.target.dataset.name == 'record') {
      this.setData({
        record: e.detail.value
      })
    };
    if (e.target.dataset.name == 'category') {
      let list = this.data.categoryArray[e.detail.value].children
      this.setData({
        category: e.detail.value,
        subjectArray: list,
        subject:-1,
        train:-1,
        device_cats: this.data.categoryArray[e.detail.value].device_cats,
      })

      if (this.data.categoryArray[e.detail.value].device_cats.length>0){
        this.setData({
          show_dev: true
        })
      }else{
        this.setData({
          dev: ''
        })
      }
      this.getClass()
    };
    if (e.target.dataset.name == 'subject') {
      this.setData({
        subject: e.detail.value,
        train: -1
      })
      this.getClass()
    };
    if (e.target.dataset.name == 'time') {
      this.setData({
        time: e.detail.value
      })
    };
    if (e.target.dataset.name == 'train') {
      var price=this.data.price
      if(this.data.type == 3){
        price = this.data.parice_list[e.detail.value]
      }else if(this.data.category>=0 && this.data.subject>=0){
        if (e.detail.value == 0){
          price = this.data.subjectArray[this.data.subject].price_new
        }
        if (e.detail.value == 1) {
          price = this.data.subjectArray[this.data.subject].price_re
        }
        if (e.detail.value == 2) {
          price = this.data.subjectArray[this.data.subject].price_change
        }
      }
      this.setData({
        train: e.detail.value,
        price: price
      })
    };
    if (e.target.dataset.name == 'area') {
      this.setData({
        area: e.detail.value
      })      
    };
    if (e.target.dataset.name == 'receive') {
      this.setData({
        receive: e.detail.value
      })
    };
    if (e.target.dataset.name == 'class_') {
      this.setData({
        class_: e.detail.value
      })
    };
    
  },
  next:function(e){
    var formData = e.detail.value,data=this.data
    if (this.data.dev != ''){
      formData.device_cats = this.data.dev.split(' , ')
    }
    if (formData.name == '') {
      wx.showToast({
        title: '姓名不能为空！',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    if (formData.idno.length < 18) {
      wx.showToast({
        title: '请填写正确的身份证号',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    if (!(/^1[3456789]\d{9}$/.test(formData.phone))) {
      wx.showToast({
        title: '请填写正确的手机号',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    if(data.type != 3){
      if (this.data.category == -1) {
        wx.showToast({
          title: '请选择作业类别',
          icon: 'none',
          duration: 2000
        })
        return false
      }
      if (this.data.subject == -1) {
        wx.showToast({
          title: '请选择准操项目或资格类型',
          icon: 'none',
          duration: 2000
        })
        return false
      }
      // console.log(this.data.class_)
      // console.log(this.data.z_type)
      if (this.data.classList.length > 0 && this.data.class_<0 && this.selectClass) {
        wx.showToast({
          title: '请选择班级',
          icon: 'none',
          duration: 2000
        })
        return false
      }
      formData.subject_item = data.z_type + "|" + data.categoryArray[data.category].name + "|" + data.subjectArray[data.subject].name
      formData.subject_id = data.subjectArray[data.subject].id 
      if (this.data.classList.length > 0 && this.selectClass){
        formData.class_id = data.classList[data.class_].id
      }else{
        formData.class_id = 0
      }
    }else{
      formData.class_id = data.class_id
    }
    if (this.data.train == -1) {
      wx.showToast({
        title: '请选择培训类型',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    formData.sex=data.sexArray[data.sex]
    formData.education = data.recordArray[data.record]
    formData.receive_card = data.receiveArray[data.receive]  
    formData.train_type = data.trainArray[data.train].name
    formData.price=this.data.price
    formData.area=this.data.area.join(' ')
    var method = 'POST', post_data = formData
    if (this.data.type == 2) { 
      method = 'PUT' 
      var new_data=this.data.data
      for(let key in formData){
        new_data[key]=formData[key]
      }
      post_data = new_data
    }


    wx.showLoading({
      title: '正在提交',
    })
    
    wx.request({
      url: host + '/api/wx/signup',
      method: method,
      header: {
        openid: app.globalData.openid
      },
      data: post_data,
      success: res => {
        wx.hideLoading()
        if(res.data.code == 0){
          let id = (data.type == 2) ? new_data.id : res.data.data.id
          wx.navigateTo({
            url: '../upload/upload?id='+id,
          })
        }else{
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: res => {
        wx.hideLoading()
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        })
      }
    })
    
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})