let db = wx.cloud.database()
let id = ''
const {
  month
} = require('../../utils/util.js');
const util = require('../../utils/util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    vote: [],
    canvote: false,
    canvote2: false,
    options: [],
    set_choose: [{
      choose: false,
      canvote: false
    }, {
      choose: false,
      canvote: false
    }, {
      choose: false,
      canvote: false
    }, {
      choose: false,
      canvote: false
    }],
    setvotes: null,
  },
  tovoteinfo: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    wx.navigateTo({
      url: '/pages/voteInfo/index?id=' + id + "&index=" + e.currentTarget.dataset.index,
    })

  },
  // 判断投票是否已经结束和是否已经开始
  judge_vote(e, a, x, y) {

    var that = this
    let month = util.month(new Date()) * 1
    let day = util.day(new Date()) * 1
    // 之前月份的11结束  00可投票 01未开始
    // 判断活动是否已经结束

    if (e < month) {

      that.setData({
        canvote: true,
      })
    }
    // 之后月份的
    else if (e > month) {

      that.setData({
        canvote: false,
      })
    }
    // 本月份的
    else if (e == month) {

      if (a <= day) {

        that.setData({
          canvote: true,
        })
      } else {
        that.setData({
          canvote: false,
        })
      }
    }
    // 判断活动是否已经开始

    if (x > month) {
      that.setData({
        canvote2: false,
      })
    } else if (x == month) {
      if (y > day) {
        that.setData({
          canvote2: false,
        })
      } else if (y <= day) {
        that.setData({
          canvote2: true,
        })
      }
    } else {
      that.setData({
        canvote2: true,
      })
    }

  },
  // 判断今日可投票次数并渲染出可投票选项
  judet_setvotes(e, a, setvotes, canvotes) {

    for (var i = 0; i < this.data.set_choose.length; i++) {
      this.setData({
        ["set_choose[" + i + "].canvote"]: true
      })
    }
    var that = this
    let hour = util.hour(new Date()) * 1
    let minute = util.minute(new Date()) * 1
    let time_day = Date.parse(new Date()) / 1000 - hour * 60 * 60 - minute * 60 //当日开始的时间戳今日00：00开始的时间戳
    if (!canvotes) { //单一选项不可重复投票
      for (var i = 0; i < a.length; i++) {
        if (a[i].votelist.length != 0) {
          for (var k = 0; k < a[i].votelist.length; k++) {
            console.log(a[i].votelist[k].time - time_day, hour, minute, Date.parse(new Date()) / 1000)
            if (a[i].votelist[k].openid == wx.getStorageSync('openid')) { //判断是否为今日投票
              if ((a[i].votelist[k].time - time_day) < 24 * 60 * 60 && (a[i].votelist[k].time - time_day) > 0) { //证明今日已经投票
                that.setData({
                  ["set_choose[" + i + "].canvote"]: false
                })
                if (setvotes > 0) {
                  setvotes = setvotes - 1
                }

              }
            }
          }
        }
      }
    } else { //可对单一选项重复投票
      for (var i = 0; i < a.length; i++) {
        if (a[i].votelist.length != 0) {
          for (var k = 0; k < a[i].votelist.length; k++) {

            if (a[i].votelist[k].openid == wx.getStorageSync('openid')) {
              for (var t = 0; t < a[i].votelist[k].list.length; t++) {
                //判断是否为今日投票
                if ((a[i].votelist[k].list[t].time - time_day) < 24 * 60 * 60 && (a[i].votelist[k].list[t].time - time_day) > 0) {
                  that.setData({
                    ["set_choose[" + i + "].canvote"]: false
                  })
                  if (setvotes > 0) {
                    setvotes = setvotes - 1
                  }

                }

              }
            }


          }
        }
      }
    }



    if (setvotes > 0 && canvotes) { //可重复投票 重新跟新 对可以投票
      for (var i = 0; i < this.data.set_choose.length; i++) {
        this.setData({
          ["set_choose[" + i + "].canvote"]: true
        })
      }
    }
    that.setData({
      setvotes: setvotes
    })



  },
  //判断是否可对单一选项重复投票 和判断用户今日是否已经对选项进行了投票
  judge_choose(e) {
    //可重复投票先将所有选项设为true
    if (e) {
      for (var i = 0; i < this.data.set_choose.length; i++) {
        this.setData({
          ["set_choose[" + i + "].canvote"]: true
        })
      }
    } else { //

    }


  },
  // 获取投票数据信息
  getvoteid(e) {
    let that = this
    db.collection("Vote").doc(e).get()
      .then(res => {
        res.data.attention = false
        res.data.canvote = true
        // 跟新选项（选项的一个初始化）
        let set = this.data.set_choose
        for (var i = 0; i < res.data.options.length; i++) {
          let add = {
            choose: false,
            canvote: false
          }
          set.push(add)
        }
        that.setData({
          set_choose: set
        })
        // 判断用户是否已经关注了
        if (res.data.attentionlist.length != 0) {
          for (var i = 0; i < res.data.attentionlist.length; i++) {
            if (res.data.attentionlist[i].openid == wx.getStorageSync('openid')) {
              res.data.attention = true
              break
            }
          }
        }
        // 判断投票是否已经结束
        let vote_month = (res.data.dateTime2[5] + res.data.dateTime2[6]) * 1
        let vote_day = (res.data.dateTime2[8] + res.data.dateTime2[9]) * 1
        let vote_month2 = (res.data.dateTime1[5] + res.data.dateTime1[6]) * 1
        let vote_day2 = (res.data.dateTime1[8] + res.data.dateTime1[9]) * 1
        that.judge_vote(vote_month, vote_day, vote_month2, vote_day2)
        //判断是否可对单一选项重复投票 和判断用户今日是否已经对选项进行了投票
        that.judge_choose(res.data.canvotes, res.data.options)
        // 判断今日剩余可投票次数
        that.judet_setvotes(res.data.setvotes, res.data.options, res.data.setvotes, res.data.canvotes)
        that.setData({
          vote: res.data,
          options: res.data.options,
        })
      })

  },
  // 关注或取消关注
  attenion(e) {
    var that = this
    let attention = e.currentTarget.dataset.attention
    that.setData({
      "vote.attention": !that.data.vote.attention
    })
    if (!attention) { //点击关注
      let _ = db.command
      let attentionlist = {
        openid: wx.getStorageSync('openid')
      }
      db.collection("Vote").doc(id).update({
          data: {
            attentionlist: _.push([attentionlist])
          }
        })
        .then(res => {
          wx.showToast({
            title: '已关注',
          })
        })
    } else { //点击取消关注
      let attentionlist = that.data.vote.attentionlist
      for (var i = 0; i < attentionlist.length; i++) {
        if (attentionlist[i].openid == wx.getStorageSync('openid')) {
          attentionlist.splice(i, 1)
          db.collection("Vote").doc(id).update({
              data: {
                attentionlist: attentionlist
              }
            })
            .then(res => {
              wx.showToast({
                title: '已取消关注',
              })
            })
          break
        }
      }
    }
  },
  // 监听用户选择活动
  check_vote(e) {


    let index = e.currentTarget.dataset.index
    var that = this
    that.setData({
      ["set_choose[" + index + "].choose"]: !that.data.set_choose[index].choose
    })
  },
  // 用户点击投票
  govote() {
    let canvotemore = this.data.vote.canvotes//是否可以重复投票
    //设置投票者的openid  投票的次数  上一次投票的时间
    let choose = false
    var vote = 0
    var that = this
    var chooselist = that.data.set_choose//初始选项列表
    var options = that.data.options//数据选项列表
    // 查询用户选择了哪些选项
    for (var i = 0; i < that.data.set_choose.length; i++) {

      if (that.data.set_choose[i].choose) {
        choose = true
        vote = vote + 1//监听用户一共选择了几个选项
      }
    }

//判断用户是否选择了选项
    if (!choose) {
      wx.showToast({
        title: '请选择一个选项',
      })
    } else {
      //选择选项大于今日可投票次数
      if (that.data.setvotes < vote) {
        wx.showModal({
          title: "投票失败",
          content: "投票次数超过今日可投票次数"
        })
      } else {
        let up = true
        for (var i = 0; i < chooselist.length; i++) {
          if ((chooselist[i].choose) && (chooselist[i].canvote)) {
          
            var index = null
            //设置投票信息
            if (options[i].votelist.length == 0) { //投票人数为0
              wx.showLoading({
                title: '投票中',
              })
              if (!canvotemore) {
                let addvote = {
                  openid: wx.getStorageSync('openid'),
                  number: 1,
                  time: Date.parse(new Date()) / 1000
                }
                options[i].votelist.push(addvote)
                options[i].number = options[i].number + 1
              } else {
                let addvote = {
                  openid: wx.getStorageSync('openid'),
                  number: 1,
                  list: [{
                    time: Date.parse(new Date()) / 1000
                  }]
                }
                options[i].votelist.push(addvote)
                options[i].number = options[i].number + 1
              }


            } else if (options[i].votelist.length != 0) { //投票人数不为0
              let first = true
              let newvote = null
              for (var a = 0; a < options[i].votelist.length; a++) { //判断用户是否为第一次投票
                first = true
                if (options[i].votelist[a].openid == wx.getStorageSync('openid')) {
                  first = false
                  newvote = options[i].votelist[a]
                  index = a
                }
              }

              if (first) { //第一次投票
                console.log(i, "第一次")
                wx.showLoading({
                  title: '投票中',
                })
                if (!canvotemore) {
                  let addvote = {
                    openid: wx.getStorageSync('openid'),
                    number: 1,
                    time: Date.parse(new Date()) / 1000
                  }
                  options[i].votelist.push(addvote)
                  options[i].number = options[i].number + 1
                } else {
                  let addvote = {
                    openid: wx.getStorageSync('openid'),
                    number: 1,
                    list: [{
                      time: Date.parse(new Date()) / 1000
                    }]
                  }
                  options[i].votelist.push(addvote)
                  options[i].number = options[i].number + 1
                }
              } else { //不是第一次
                console.log(i, "不是第一次")
                wx.showLoading({
                  title: '投票中',
                })
                if (!canvotemore) {
                  options[i].number = options[i].number + 1
                  newvote.number = newvote.number + 1
                  newvote.time = Date.parse(new Date()) / 1000
                } else {
                  options[i].number = options[i].number + 1
                  newvote.number = newvote.number + 1
                  let list = newvote.list
                  list.push({
                    time: Date.parse(new Date()) / 1000
                  })
                  newvote.list = list


                }
                options[i].votelist[index] = newvote
                console.log(options[i].votelist[index])
              }

            }
          }
          //此选项今日不可投票
          else if ((chooselist[i].choose) && (!chooselist[i].canvote)) {
            up = false
            var k = i + 1
            wx.showModal({
              title: "投票失败",
              content: "选项" + k + "今日已经投票不可重复投票"
            })
            break
          }
        }
        // 跟新数据库可投票信息 先跟新后读取
        if (up) {

          db.collection("Vote").doc(id).update({
              data: {
                options: options
              }
            })
            .then(res => {
              wx.hideLoading()
              that.getvoteid(id)
              wx.showToast({
                title: '投票成功',
              })
            })
        }
      }
    }
  },

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

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    console.log('转发事件的来源', res.from)
    console.log(that.data)
    return { //自定义转发内容
      title: '来看看这个投票活动吧！', //自定义转发标题
      path: '/pages/voteContent/index' //当前页面的路径 ，必须是以 / 开头的完整路径
      //imageUrl: that.data.pic不设置此字段时，默认截取当前页面作为展示的图片
    }
  }
})