var dateTimePicker = require('./dateTimePicker.js');
let vpage = [];
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    votename: ' ',
    votedetail: ' ',

    // options: [{
      // opsid: 1,
      // opsname: ' ',
      // opsdetail: ' ',
      imgList: [],
      src: '',
      // opsvideo:src,
      // opsimage:imgList[item]
    // }],
    options: [0],
    // opsid: ' ',
    opsname: [],
    opsdetail: [],

    showUploadTip: false,
    haveGetImgSrc: false,
    opdhidden: true,
    envId: '',
    // Vimg:[],
    imgSrc: '',
    navState: 0,

    dateTimeArray1: null,
    dateTime1: null,

    dateTimeArray2: null,
    dateTime2: null,

    startYear: 2022,
    endYear: 2030,

    isunname: false,
    canhot: true,
    canshare: true,
    ispublic: true,
    setvotes: null,
    canvotes: false
  },

  onLoad(options) {

    //swiperitem内容显示
    let that = this
    //uni-app是uni.getSystemInfo,微信小程序wx.getSystemInfo
    wx.getSystemInfo({
      success: function (res) {
        //uni-app
        //that.clientHeight=res.windowHeight-177
        //微信小程序
        that.setData({
          clientHeight: res.windowHeight - 177
        });
      }
    })


    this.setData({
      envId: options.envId
    });

    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    // 精确到分的处理，将数组的秒去掉
    var lastArray = obj1.dateTimeArray.pop();
    var lastTime = obj1.dateTime.pop();

    this.setData({
      dateTimeArray1: obj1.dateTimeArray,
      dateTime1: obj1.dateTime
    });

    var obj2 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    // 精确到分的处理，将数组的秒去掉
    var lastArray = obj2.dateTimeArray.pop();
    var lastTime = obj2.dateTime.pop();

    this.setData({
      dateTimeArray2: obj2.dateTimeArray,
      dateTime2: obj2.dateTime
    });

  },

  //自适应文本框
  getvotedetail: function (votedetail) {
    this.setData({
      votedetail: votedetail.detail.value
    })
  },
  getvotename: function (votename) {
    this.setData({
      votename: votename.detail.value
    })
    console.log(votename)
  },
  getsetvotes: function (setvotes) {
    this.setData({
      setvotes: setvotes.detail.value
    })
  },
  // getopsname: function (opsname) {
  //   this.setData({
  //     opsname: opsname.detail.value
  //   })
  // },
  // getopsdetail: function (opsdetail) {
  //   this.setData({
  //     opsdetail: opsdetail.detail.value
  //   })
  // },


  uploadImg() {
    // let that = this 
    wx.showLoading({
      title: '加载中',
    });
    // 让用户选择一张图片
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: chooseResult => {
        // 将图片上传至云存储空间
        wx.cloud.uploadFile({
          // 指定上传到的云路径
          cloudPath: 'vp/' + new Date().getTime() + '.png',
          // 指定要上传的文件的小程序临时文件路径
          filePath: chooseResult.tempFilePaths[0],
          // filePath: that.data.imgSrc[0],
          config: {
            env: this.data.envId
          }
        }).then(res => {
          console.log('上传成功', res);
          this.setData({
            haveGetImgSrc: true,
            imgSrc: res.fileID
          });
          wx.hideLoading();
          vpage = res.fileID
        }).catch((e) => {
          console.log(e);
          wx.hideLoading();
        });
      },
    });
  },

  clearImgSrc() {
    wx.cloud.deleteFile({
      fileList: ['chooseResult.tempFilePaths[0]'],
      success: res => {
        // handle success
        console.log(res.fileList)
      },
      fail: console.error
    })
    this.setData({
      haveGetImgSrc: false,
      imgSrc: ''
    });
    // let that = this;
    // let id = event.currentTarget.dataset.id;
    // console.log('id', id)
    // wx.showModal({
    //   title: '删除！',
    //   content: '确定删除嘛？',
    //   success(res) {
    //     if (res.confirm) {
    //       console.log("点击确认")
    //       wx.cloud.database()
    //         .collection('imgSrc')
    //         .doc(id)//对那一条数据
    //         .remove({
    //           success(res) {
    //             console.log("delSuccess", res)
    //             // that.getimgSrc;
    //           }
    //         })
    //     } else {
    //       console.log("点击了取消按钮")
    //     }
    //   }
    // })
  },

  //监听滑块
  bindchange(e) {
    // console.log(e.detail.current)
    let index = e.detail.current;
    this.setData({
      navState: index
    })
  },
  changeColor: function (e) {
    this.setData({
      index: e.currentTarget.dataset['index'],
    })
  },
  //点击导航
  navSwitch: function (e) {
    // console.log(e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index;
    this.setData({
      navState: index
    })
  },
  //时间选择
  changeDate(e) {
    this.setData({ date: e.detail.value });
  },
  changeTime(e) {
    this.setData({ time: e.detail.value });
  },
  changeDateTime(e) {
    this.setData({ dateTime: e.detail.value });
  },
  changeDateTime1(e) {
    this.setData({ dateTime1: e.detail.value });
  },
  changeDateTimeColumn(e) {
    var arr = this.data.dateTime, dateArr = this.data.dateTimeArray;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({
      dateTimeArray: dateArr,
      dateTime: arr
    });
  },
  changeDateTimeColumn1(e) {
    var arr = this.data.dateTime1, dateArr = this.data.dateTimeArray1;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr
    });
  },

  changeDateTime2(e) {
    this.setData({ dateTime2: e.detail.value });
  },
  changeDateTimeColumn2(e) {
    var arr = this.data.dateTime2, dateArr = this.data.dateTimeArray2;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({
      dateTimeArray2: dateArr,
      dateTime2: arr
    });
  },


  //选项描述显示
  adddetail: function () {
    this.setData({
      opdhidden: !this.data.opdhidden
    })
  },
  /*图片  视频 选择框*/
  addfujian: function () {
    var _this = this;
    wx.showActionSheet({
      itemList: ['图片', '视频'],
      success: function (res) {
        if (res.tapIndex == 0) {
          _this.chooseImg()
        }
        if (res.tapIndex == 1) {
          _this.chooseVideo()
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  // 选择照片
  chooseImg: function () {
    var _this = this;
    wx.showActionSheet({
      itemList: ["拍照", "从相册中选择"],
      itemColor: "#000000",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            _this.imgWShow("camera")        //拍照
          } else if (res.tapIndex == 1) {
            _this.imgWShow("album")      //相册
          }
        }
      }
    })
  },
  // 点击调用手机相册/拍照
  imgWShow: function (type) {
    var _this = this;
    let len = 0;
    if (_this.data.imgList != null) {
      len = _this.data.imgList.length
    }   //获取当前已有的图片
    wx.chooseImage({
      count: 6 - len,     //最多还能上传的图片数,这里最多可以上传5张
      sizeType: ['original', 'compressed'],        //可以指定是原图还是压缩图,默认二者都有
      sourceType: [type],             //可以指定来源是相册还是相机, 默认二者都有
      success: function (res) {
        wx.showToast({
          title: '正在上传...',
          icon: "loading",
          mask: true,
          duration: 1000
        })

        // for(let i=0;i<_this.data.imgList.length;i++){
        //   wx.cloud.uploadFile({
        //     cloudPath:'opsimg/'+new Date().getTime() + i + '.png',
        //     filePath:_this.data.imgList[i]
        //   }).then(res => {
        //     wx.hideLoading()
        //     wx.showToast({
        //       title: '上传成功',
        //     })
        //     console.log(res)
        //   }).catch(error => {
        //     console.log(error)
        //   })
        // }

        // 返回选定照片的本地文件路径列表,tempFilePaths可以作为img标签的scr属性显示图片
        var imgList = res.tempFilePaths
        let tempFilePathsImg = _this.data.imgList
        // 获取当前已上传的图片的数组
        var tempFilePathsImgs = tempFilePathsImg.concat(imgList)
        _this.setData({
          imgList: tempFilePathsImgs
        })
      },
      fail: function () {
        wx.showToast({
          title: '图片上传失败',
          icon: 'none'
        })
        return;
      }
    })
  },
  // 预览图片
  previewImg: function (e) {
    let index = e.target.dataset.index;
    let _this = this;
    wx.previewImage({
      current: _this.data.imgList[index],
      urls: _this.data.imgList
    })
  },
  /**
   * 点击删除图片
   */
  deleteImg: function (e) {
    var _this = this;
    var imgList = _this.data.imgList;
    var index = e.currentTarget.dataset.index;      //获取当前点击图片下标
    wx.showModal({
      title: '提示',
      content: '确认要删除该图片吗?',
      confirmColor: '#000000',
      cancelColor: '#5ea6e9',
      success: function (res) {
        if (res.confirm) {
          console.log("确定")
          imgList.splice(index, 1);
        } else if (res.cancel) {
          console.log("取消");
          return false
        }
        _this.setData({
          imgList
        })
      }
    })
  },

  // 选择视频
  chooseVideo: function () {
    var _this = this;
    wx.chooseVideo({
      sourceType: ['album'],
      maxDuration: 60,
      success: function (res) {
        _this.setData({
          src: res.tempFilePath,
        })
      }
    })
  },
  /*上传视频 目前后台限制最大100M, 以后如果视频太大可以选择视频的时候进行压缩*/
  uploadvideo: function () {
    var src = this.data.src;
    wx.uploadFile({
      url: '',
      methid: 'POST',           // 可用可不用
      filePath: src,
      name: 'files',              // 服务器定义key字段名称
      header: app.globalData.header,
      success: function () {
        console.log('视频上传成功')
      },
      fail: function () {
        console.log('接口调用失败')
      }
    })
  },
  /*点击删除视频*/
  deleteVideo: function (e) {
    var _this = this;
    var src = _this.data.src;
    var index = e.currentTarget.dataset.index;      //获取当前点击图片下标
    wx.showModal({
      title: '提示',
      content: '确认要删除该视频吗?',
      confirmColor: '#000000',
      cancelColor: '#5ea6e9',
      success: function (res) {
        if (res.confirm) {
          console.log("确定")
          var unsrc = '';
          _this.setData({
            src: unsrc
          })
        } else if (res.cancel) {
          console.log("取消");
          return false
        }
      }
    })
  },


  addoptions: function () {
    // let newArray = {
    //   opsid: ' ',
    //   opsname: ' ',
    //   opsdetail: ' '
    //   // opsvideo:src,
    //   // opsimage:imgList[item]
    // }
    // this.setData({
    //   opsid:this.data.options.opsid + 1,
    //   options: this.data.options.concat(newArray)
    // })
    // var that = this;
    var old = this.data.options;
    old.push(1);//这里不管push什么，只要数组长度增加1就行
    this.setData({
      // opsid: that.data.opsid + 1,
      options: old
    })
  },
  deleteoptions: function (e) {
    // let that = this
    // let index = e.target.dataset.index //数组下标
    // let arrayLength = that.data.options.length //数组长度
    // let newArray = []
    // if (arrayLength > 1) {
    //   //数组长度>1 才能删除
    //   for (let i = 0; i < arrayLength; i++) {
    //     if (i !== index) {
    //       newArray.push(that.data.options[i])
    //     }
    //   }
    //   that.setData({
    //     options: newArray
    //   })
    // }
    // var that = this;
    var nowidx = e.currentTarget.dataset.index;//当前索引
    var oldName = this.data.opsname;//所有的input值
    var oldDetail = this.data.opsdetail;
    // var oldopsimg = this.data.imgList;
    // var oldopsvideo = this.data.src;
    var oldarr = this.data.options;//循环内容
    oldarr.splice(nowidx, 1);    //删除当前索引的内容，这样就能删除view了
    oldName.splice(nowidx, 1);//view删除了对应的input值也要删掉
    oldDetail.splice(nowidx, 1);
    // oldopsimg.splice(nowidx, 1);
    // oldopsvideo.splice(nowidx, 1);
    if (oldarr.length < 1) {
      oldarr = [0]  //如果循环内容长度为0即删完了，必须要留一个默认的。这里oldarr只要是数组并且长度为1，里面的值随便是什么
    }
    this.setData({
      options: oldarr,
      // opsid:that.data.opsid - 1,
      opsname: oldName,
      opsdetail: oldDetail,
    //   imgList: oldopsimg,
    //   src: oldopsvideo
    })
  },
  getopsname: function (e) {
    // let index = e.target.dataset.index //数组下标
    // let tag = e.target.dataset.tag  //字段名称
    // let array = this.data.options;
    // array[index][tag] = e.detail.value  //赋值
    // this.setData({
    //   options: array
    // })
    var nowIdx = e.currentTarget.dataset.index;//获取当前索引
    var val = e.detail.value;//获取输入的值
    var oldName = this.data.opsname;
    // var oldDetail = this.data.opsdetail;
    oldName[nowIdx] = val;//修改对应索引值的内容
    // oldDetail[nowIdx] = val;
    this.setData({
      opsname: oldName
      // opsdetail: oldDetail
    })
  },
  getopsdetail: function (e) {
    var nowIdx = e.currentTarget.dataset.index;//获取当前索引
    var val = e.detail.value;//获取输入的值
    // var oldName = this.data.opsname;
    var oldDetail = this.data.opsdetail;
    // oldName[nowIdx] = val;//修改对应索引值的内容
    oldDetail[nowIdx] = val;
    this.setData({
      // opsname: oldName,
      opsdetail: oldDetail
    })
  },
  // getopsimg: function (e) {
  //   var nowIdx = e.currentTarget.dataset.index;//获取当前索引
  //   for(let i=0;i<imgList.length;i++){
  //     var val = e.detail.i;//获取输入的值
  //   }

  //   // var oldName = this.data.opsname;
  //   var oldImg = this.data.imgList;
  //   // oldName[nowIdx] = val;//修改对应索引值的内容
  //   oldImg[nowIdx] = val;
  //   this.setData({
  //     // opsname: oldName,
  //     imgList: oldImg
  //   })
  // },

  //发布
  postvote: function () {
    let that = this
    for (let i = 0; i < that.data.imgList.length; i++) {
      wx.cloud.uploadFile({
        cloudPath: 'opsimg/' + new Date().getTime() + i + '.png',
        filePath: that.data.imgList[i]
      }).then(res => {
        wx.hideLoading()
        wx.showToast({
          title: '上传成功',
        })
        console.log(res)
      }).catch(error => {
        console.log(error)
      })
    }




    wx.showLoading({
      title: '投票创建中',
    })
    var opsname = this.data.opsname;
    var opsdetail = this.data.opsdetail;

    var votename = this.data.votename;
    var votedetail = this.data.votedetail;
    var dateTimeArray1 = this.data.dateTimeArray1;
    var dateTime1 = this.data.dateTime1;

    var dateTimeArray2 = this.data.dateTimeArray2;
    var dateTime2 = this.data.dateTime2;

    var isunname = this.data.isunname;
    var canhot = this.data.canhot;
    var canshare = this.data.canshare;
    var ispublic = this.data.ispublic;
    var setvotes = this.data.setvotes;
    var canvotes = this.data.canvotes;
    db.collection("Vote").add({
      data: {
        opsname:opsname,
        opsdetail:opsdetail,

        votename: votename,
        votedetail: votedetail,
        imgSrc: vpage,
        dateTimeArray1: dateTimeArray1,
        dateTime1: dateTime1,
        dateTimeArray2: dateTimeArray2,
        dateTime2: dateTime2,
        isunname: isunname,
        canhot: canhot,
        canshare: canshare,
        ispublic: ispublic,
        setvotes: setvotes,
        canvotes: canvotes
      }
    }).then(res => {
      console.log('投票创建成功', res)
      wx.showToast({
        title: '投票创建成功',
        duration: 2000
      })
      wx.hideLoading({
        success: (res) => { },
      })
    })

  },

})
