// pages/activity/activity.js
// var WxParse = require('../../../wxParse/wxParse.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    startDate: new Date('1900-01-01'),
    uploadUrl: 'upload.uploadPic',
    activity_id: '',
    types: {
      "88": 'diyusername',
      "99": 'diypassword',
      "0": 'diyinput',
      "1": 'diytextarea',
      "3": 'diycheckbox',
      "4": 'diyradio',
      "2": 'diyselect',
      "7": 'diydate',
      "9": 'diycity',
      "5": 'diyimage',
    },
    thumb: "",
    conference: {},
    form_id: '',
    diyform: {},
    diydata: [],
    intro: false,
    //地区
    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    currentDate: new Date().getTime(),
    isValidation: true,
    nosubmit: true,
    is_enrol:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let scene = decodeURIComponent(options.scene);

    // 扫码进入
    if (scene) {
      let info_arr = [];
      info_arr = scene.split(',');
      for (let i = 0; i < info_arr.length; i++) {
        let chil_arr = [];
        chil_arr = info_arr[i].split('=');
        if (chil_arr[0] == 'id') {
          this.setData({
            activity_id: chil_arr[1]
          });
        }
      }
    }

    // 点击进入
    if (options.id) {
      this.setData({
        activity_id: options.id
      });
    }
    if (!this.data.activity_id) {
      wx.showToast({
        title: '活动不存在！',
        icon: 'none',
        duration: 1500,
        success: function () {
          setTimeout(function () {
            //要延时执行的代码
            wx.redirectTo({
              url: '/packageA/member/conferenceList/conferenceList'
            });
          }, 1500); //延迟时间
        },
      });
    }
    //加载地址数据初始化
    this._initAddressInfo();
    this.getActivity();
  },
  onRead_1(e) {
    try {
      let diydata = this.data.diydata;
      let index = e.currentTarget.dataset.idex;
      if (diydata[index].type == "diyimage") {
        if (diydata[index].imgUrls.length >= diydata[index].data.tp_max) {
          wx.showToast({
            title: `最多只能上传${diydata[index].data.tp_max}张`,
            icon: 'none',
            duration: 1000
          });
          return;
        }
      }
      // for (var i = 0; i < diydata.length; i++){
      //   if(diydata[i].type == "diyimage"){
      //     if(diydata[i].imgUrls.length >= diydata[i].data.tp_max){
      //       wx.showToast({
      //         title: `最多只能上传${diydata[i].data.tp_max}张`,
      //         icon:'none',
      //         duration:1000
      //       })
      //       return
      //     }
      //   }
      // }
      // console.log(this.data.diydata)
    } catch (err) {
      console.log(err);
    }
    let name = e.currentTarget.dataset.name;
    this.setData({
      setname: name
    });
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        wx.compressImage({
          src: tempFilePaths[0], // 图片路径
          quality: 60, // 压缩质量
          success(e) {
            // console.log(e)
            let photourl = e.tempFilePath;

            wx.uploadFile({
              url: urlStr,
              filePath: photourl,
              name: 'file',
              formData: {
                attach: that.data.setname
              },
              success(resdata) {
                var res = JSON.parse(resdata.data);
                console.log(res);
                if (res.result == 1) {
                  let diydata = that.data.diydata;
                  console.log(res);
                  for (var i = 0; i < diydata.length; i++) {
                    if (diydata[i].name == res.data.attach) {
                      diydata[i].imgUrls.push(res.data.img_url);
                    }
                  }
                  that.setData({
                    diydata: diydata
                  });
                  console.log(that.data.diydata);
                } else {
                  wx.showToast({
                    icon: 'none',
                    title: res.msg,
                    duration: 1500
                  });
                }
              }
            });
          },
          fail(e) {
            console.log(e);
          },
          complete(e) {

          }
        });
      }
    });
  },
  removeImg: function (e) {
    let delIndex = e.currentTarget.dataset.indexc;
    let index_1 = e.currentTarget.dataset.index;
    let diydata = this.data.diydata;
    diydata[index_1].imgUrls.splice(delIndex, 1);
    this.setData({
      diydata: diydata
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return{
      title:this.data.conference.title ? this.data.conference.title : '活动',
      path:"/packageB/conference/activity/activity?id="+this.data.activity_id
    };
  },
  getActivity() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.conference.api.conference-activity.get-activity-detail");
    urlStr += '&id=' + this.data.activity_id;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (res.data.is_end == 1) {
            wx.showToast({
              title: '来晚了,活动已结束！',
              icon: 'none',
              duration: 1500,
              success: function () {
                setTimeout(function () {
                  //要延时执行的代码
                  wx.redirectTo({
                    url: '/packageA/member/conferenceList/conferenceList'
                  });
                }, 1500); //延迟时间
              },
            });
            return;
          }
          
          that.setData({
            thumb: res.data.thumb,
            conference: res.data,
            form_id: res.data.form_id,
          });
          wx.setNavigationBarTitle({
            title: that.data.conference.title ? that.data.conference.title : '活动'
          });
          // let article = that.data.conference.content;
          /**
           * WxParse.wxParse(bindName , type, data, target,imagePadding)
           * 1.bindName绑定的数据名(必填)
           * 2.type可以为html或者md(必填)
           * 3.data为传入的具体数据(必填)
           * 4.target为Page对象,一般为this(必填)
           * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
           */
          // try {
          // 	WxParse.wxParse('article', 'html', article, that);
          // } catch (e) {
          // 	//TODO handle the exception
          // }
          that.getForm();
          if(res.data.is_enrol == 1){
            that.setData({
              is_enrol:res.data.is_enrol
            });
            wx.showToast({
              title: '您已报名该活动！',
              icon:'none'
            });
            return;
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  goDetail(){
    wx.navigateTo({
      url: '/packageB/conference/myActivityInfo/myActivityInfo?id='+this.data.activity_id,
    });
  },
  getForm() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.diyform.api.diy-form.get-diy-form-by-id");
    urlStr += '&form_id=' + this.data.form_id;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        var f = {};
        if (res.result == 1) {
          that.setData({
            diyform: res.data
          });
          let fields = that.data.diyform.fields;
          let diydata = that.data.diydata;
          for (var field in fields) {
            if (that.data.types[fields[field].data_type] == 'diycheckbox') {
              f = {
                name: field,
                data: fields[field],
                value: [],
                type: that.data.types[fields[field].data_type],
              };
            } else if (that.data.types[fields[field].data_type] == 'diydate') {
              f = {
                name: field,
                data: fields[field],
                value: '',
                type: that.data.types[fields[field].data_type],
              };

            } else if (that.data.types[fields[field].data_type] == 'diyselect') {
              let tp_textArr = [];
              for (let i = 0; i < fields[field].tp_text.length; i++) {
                tp_textArr.push({
                  name: fields[field].tp_text[i]
                });
              }

              f = {
                name: field,
                data: fields[field],
                value: '',
                type: that.data.types[fields[field].data_type],
                diysishow: false,
                sitem: tp_textArr
              };
            } else if (that.data.types[fields[field].data_type] == 'diycity') {
              f = {
                name: field,
                data: fields[field],
                value: '',
                type: that.data.types[fields[field].data_type],
                showAdd: false
              };

            } else if (that.data.types[fields[field].data_type] == 'diyimage') {
              f = {
                name: field,
                data: fields[field],
                imgUrls: fields[field].value ? fields[field].value : [],
                isPhoto: false,
                type: that.data.types[fields[field].data_type],
              };

            } else {
              f = {
                name: field,
                data: fields[field],
                value: '',
                type: that.data.types[fields[field].data_type],
              };
            }
            diydata.push(f);
            that.setData({
              diydata: diydata
            });
            console.log(that.data.diydata);
          }

        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  showIntro() {
    this.setData({
      intro: true
    });
  },
  showIntroClose() {
    this.setData({
      intro: false
    });
  },
  //自定义表单值绑定
  tpnameinp(e) {
    let val = e.detail.value;
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].value"]: val
    });
  },
  diytextareainp(e) {
    let val = e.detail.value;
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].value"]: val
    });
  },
  checkboxinp(e) {
    let val = e.detail;
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].value"]: val
    });
  },
  diyselectBtn(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].diysishow"]: true
    });
  },
  sitemClose(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].diysishow"]: false
    });
  },
  sitemSelectBtn(e) {
    let idx = e.currentTarget.dataset.idex;
    let val = e.detail.name;
    this.setData({
      ["diydata[" + idx + "].value"]: val,
      ["diydata[" + idx + "].diysishow"]: false
    });
  },
  raidinp(e) {
    let val = e.detail;
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].value"]: val
    });
  },
  // 关闭选择收货地址
  _closeDateLw: function (e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].showAdd"]: false
    });
  },
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地址信息准备就绪");
        that._getProvinceData();
      },
      fail: function (res) {
        console.log("省fail");
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: 'provinceData',
              data: province
            });
            wx.setStorage({
              key: 'cityData',
              data: city
            });
            wx.setStorage({
              key: 'districtData',
              data: district
            });
            that._initAddressInfo();
          },
          fail: function (res) {},
          state: true
        });
      }
    });
  },
  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("省读取成功", res.data);
        that.setData({
          provinceData: res.data
        });
        that.setData({
          "selectAddressData[0].name": res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0]
        });
        that._getCityData();
      }
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    console.log("城市", "_data", _data);
    var that = this;
    var _keyName = 'cityData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("城市读取成功", res);

        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("城市数据筛选", _json);
        that.setData({
          cityData: _json
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1]
        });
        that._getDistrictData();
      }
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    console.log("地区", "_data", _data);
    console.log(_data);
    var that = this;
    var _keyName = 'districtData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地区读取成功");
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("地区数据筛选", _json);
        that.setData({
          districtData: _json
        });
        console.log("districtData", _json);
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2]
        });
        console.log("over", that.data.selectAddressData);
      }
    });
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2]
    });
    this._initAddressInfo();
  },
  //城市结果
  resultAdd: function (e) {
    let idx = e.currentTarget.dataset.idex;
    let seleData = this.data.selectAddressData;
    let retCity = seleData[0].name + ' ' + seleData[1].name + ' ' + seleData[2].name;
    this.setData({
      ["diydata[" + idx + "].value"]: retCity,
      ["diydata[" + idx + "].showAdd"]: false
    });
  },
  //自定义日期选择
  openPicker(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].timeShow"]: true
    });
  },
  PickerClose(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].timeShow"]: false
    });
  },
  PickerChange(event) {
    let idx = event.currentTarget.dataset.idex;
    let time = event.detail;
    this.setData({
      ["diydata[" + idx + "].currentDate"]: time
    });
  },
  birthdayconfirm(e) {
    let idx = e.currentTarget.dataset.idex;
    let time = e.detail;
    let changtime = this.timestampToTime(time);
    this.setData({
      ["diydata[" + idx + "].value"]: changtime,
      ["diydata[" + idx + "].timeShow"]: false
    });
  },
  timestampToTime(timestamp) {
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate();
    return Y + M + D;
  },
  submit() {
    let refs = this.selectComponent('.diyfrom');
    refs.submit();
  },
  dfsave(e) {
    this.setData({
      formData: e.detail
    });
    this.submitConference();
  },
  submitConference() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.conference.api.conference-activity.save-enrol");
    urlStr += '&conference_id=' + this.data.activity_id;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          var enrol_id = res.data.enrol_id;
          that.submitForm(enrol_id);
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          wx.redirectTo({
            url: '/packageA/member/conferenceList/conferenceList'
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  submitForm(enrol_id) {
    let that = this;
    let formData = [];
    let formObject = {};
    this.data.diydata.forEach(item => {
      if (item.type == 'diyimage') {
        formObject[item.name] = item.imgUrls;
      } else {
        formObject[item.name] = item.value;
      }

    });
    console.log(formObject, this.data.diydata);
    formData.push(formObject);
    let json = {
      form_data: this.data.formData,
      form_id: this.data.form_id,
    };
    let urlStr = app.getNetAddresss("plugin.diyform.api.diy-form.save-diy-form-data");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          var form_data_id = res.data.form_data_id;
          that.submitEnro(enrol_id, form_data_id);
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }

      },
      fail: function (res) {}
    });
  },
  submitEnro(enrol_id, form_data_id) {
    let urlStr = app.getNetAddresss("plugin.conference.api.conference-activity.save-enrol-end");
    let json = {
      enrol_id: enrol_id,
      form_data_id: form_data_id,
    };
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: '报名成功',
            icon: 'none',
            duration: 1500,
            success: function () {
              setTimeout(function () {
                //要延时执行的代码
                wx.redirectTo({
                  url: '/packageA/member/conferenceList/conferenceList'
                });
              }, 1500); //延迟时间
            },
          });
        }
      },
      fail: function (res) {}
    });
  },
  //自定义日期选择
  showAddBtn(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].showAdd"]: true
    });
  },
});