// pages/xunjian/xunjian.js
import http from '../../base/httputil'
import tools from '../../base/tools'
Page({
  /**
   * 页面的初始数据
   */
  data: {

    busEnterpriseId: null,
    xunjianItems: null,
    hui: "block",
    currentIndex: "block",
    tabcurrentIndex: 0, //默认是活动项
    currentItemId: "0",
    //上传图片
    //mp-uploader
    maximgs: 5, //最大上传数
    files: [], //上传组件绑定的文件urls
    sizeType: ['compressed'], //压缩上传,可以是['original', 'compressed']
    sourceType: ['album', 'camera'], //相册,或拍照

    listdata: [{
        info: "建立安全防火制度，明确防火责任人及其职责",
        checked: true,
        listid: "0"

      },
      {
        info: "建立安全防火制度，明确防火责任人及其职责，建立安全防火制度，明确防火责任人及其职责，建立安全防火制度，明确防火责任人及其职责",
        checked: true,
        listid: "1"
      },
    ],
  },


  takePicture: function (e) {
    // 拍照
    let jibie = e.currentTarget.dataset.jibie
    let listid = e.currentTarget.dataset.listid
    let from = e.currentTarget.dataset.picfrom
    let that = this

    wx.chooseMedia({
      sourceType: ['album', 'camera'],
      success(res) {
        let tempFilePath = res.tempFiles[0].tempFilePath
        console.log(tempFilePath)
        //
        that.data.xunjianItems[jibie][1].forEach(function (item, index) {
          if (item.listid == listid) {
            let uuid = tools.uuid()

            let picutre = {
              "pic_key": uuid,
              "pic_value": tempFilePath,
              "pic_base64":wx.getFileSystemManager().readFileSync(tempFilePath,'base64')
            }
            if (from == "before") {
              that.data.xunjianItems[jibie][1][index].picturesBefore.push(picutre)
            }
            if (from == "after") {
              that.data.xunjianItems[jibie][1][index].picturesAfter.push(picutre)
            }
            // let str = 'xunjianItems["' + jibie + '"][1][' + index + '].checked'
            that.setData({
              xunjianItems: that.data.xunjianItems
            })
          }
        })
      }
    })

    this.setData({
      show: false
    })
  },

  deletePic(e) {
    let that = this
    let jibie = e.currentTarget.dataset.jibie
    let listid = e.currentTarget.dataset.listid
    let pickey = e.currentTarget.dataset.pickey
    let from = e.currentTarget.dataset.picfrom
    console.log(jibie, listid, pickey, from)
    this.data.xunjianItems[jibie][1].forEach(function (item, index) {
      if (item.listid == listid) {
        if (from == "before") {
          that.data.xunjianItems[jibie][1][index].picturesBefore.forEach(function (it, inx) {
            if (it.pic_key == pickey) {
              that.data.xunjianItems[jibie][1][index].picturesBefore.splice(inx, 1)
            }
          })
        } else if (from == "after") {
          that.data.xunjianItems[jibie][1][index].picturesAfter.forEach(function (it, inx) {
            if (it.pic_key == pickey) {
              that.data.xunjianItems[jibie][1][index].picturesAfter.splice(inx, 1)
            }
          })
        }
        that.setData({
          xunjianItems: that.data.xunjianItems
        })
      }
    })
  },

  pictureAuthSetting() {
    wx.authorize({
      scope: 'scope.camera',
      success(res) {
        console.log("申请使用摄像头成功,", res)
      }
    })
  },










  changeme: function (e) {
    let that = this
    let checked = e.detail.value;
    let jibie = e.currentTarget.dataset.jibie
    let listid = e.currentTarget.dataset.index

    this.data.xunjianItems[jibie][1].forEach(function (item, index) {
      if (item.listid == listid) {
        that.data.xunjianItems[jibie][1][index].checked = checked
        let str = 'xunjianItems["' + jibie + '"][1][' + index + '].checked'
        that.setData({
          xunjianItems: that.data.xunjianItems
        })
      }
    })
    console.log(this.data.xunjianItems)

    // this.cz_xunjianItems(listid, checked, jibie);

  },

  //tab
  pagechange: function (e) {
    // 通过touch判断，改变tab的下标值
    if ("touch" === e.detail.source) {
      let currentPageIndex = this.data.tabcurrentIndex;
      currentPageIndex = (currentPageIndex + 1) % 2;
      // 拿到当前索引并动态改变
      this.setData({
        tabcurrentIndex: currentPageIndex,
      })
    }
  },

  bindbusTrackContent(e) {
    let that = this
    let jibie = e.currentTarget.dataset.jibie
    let listid = e.currentTarget.dataset.listid
    this.data.xunjianItems[jibie][1].forEach(function (item, index) {
      if (item.listid == listid) {
        that.data.xunjianItems[jibie][1][index].busTrackContent = e.detail.value
      }
    })
  },

  getTimeLimit(e) {
    let that = this
    let jibie = e.currentTarget.dataset.jibie
    let listid = e.currentTarget.dataset.listid
    this.data.xunjianItems[jibie][1].forEach(function (item, index) {
      if (item.listid == listid) {
        that.data.xunjianItems[jibie][1][index].timeLimit = e.detail.value
      }
    })
  },
  titleClick: function (e) {
    let that = this
    let jibie = e.currentTarget.dataset.jibie
    let listid = e.currentTarget.dataset.listid
    let itemsType = e.currentTarget.dataset.idx
    this.data.xunjianItems[jibie][1].forEach(function (item, index) {
      if (item.listid == listid) {
        that.data.xunjianItems[jibie][1][index].itemsType = itemsType
        let str = 'xunjianItems["' + jibie + '"][1][' + index + '].itemsType'
        console.log("str", str)
        console.log(that.data.xunjianItems[jibie][1][index].itemsType)
        that.setData({
          xunjianItems: that.data.xunjianItems
        })
      }
    })
  },


  //上传图片

  // 删除图片
  clearImg: function (e) {
    var nowList = []; //新数据
    var uploaderList = this.data.uploaderList; //原数据

    for (let i = 0; i < uploaderList.length; i++) {
      if (i == e.currentTarget.dataset.index) {
        continue;
      } else {
        nowList.push(uploaderList[i])
      }
    }
    this.setData({
      uploaderNum: this.data.uploaderNum - 1,
      uploaderList: nowList,
      showUpload: true
    })
  },
  //展示图片
  showImg: function (e) {
    var that = this;
    wx.previewImage({
      urls: that.data.uploaderList,
      current: that.data.uploaderList[e.currentTarget.dataset.index]
    })
  },
  //上传图片
  onLoad: function (options) {
    this.pictureAuthSetting()
    this.data.busEnterpriseId = options.busEnterpriseId
    this.getXunjianItems()
    this.setData({
      //通过bind(this)将函数绑定到this上,以后函数内的this就是指全局页面
      //setdata以后,这两个函数就可以传递给mp-uploader了
      selectFile: this.selectFile.bind(this),
      uplaodFile: this.uplaodFile.bind(this)
    })
  },

  //mpuploader选择图片时的过滤函数，返回true表示图片有效
  selectFile(files) {
    wx.showLoading({
      title: '',
    })
    // 如果有大文件可以压缩一下
    // 返回false可以阻止本次文件上传
  },
  uplaodFile(files) {
    // 图片上传的函数，必须返回Promise
    //Promise的callback里面必须resolve({urls})表示成功，否则表示失败
    return new Promise((resolve, reject) => {
      const tempFilePaths = files.tempFilePaths;
      const that = this;
      let finished = {
        url: []
      } //本次上次成功的URL存入这个变量,被success方法的e.detail承接

      for (var i = 0; i < tempFilePaths.length; i++) {
        let filePath = tempFilePaths[i] //原名
        let cloudPath = 'qyzj' + new Date().getTime() + '-' + i + filePath.match(/\.[^.]+?$/)[0] //云存储文件名

        wx.cloud.uploadFile({
          filePath,
          cloudPath,

          //成功
          success: function (res) {
            if (res.statusCode != 200 && res.statusCode != 204 && res.statusCode != 205) reject('error') // 可能会有好几个200+的返回码，表示成功

            finished.url.push({
              url: res.fileID
            }) //成功一个存一个到本次上传成功列表
            //如果本次上传的文件都完成 或全局已经存满3张,resolve退出
            if (finished.urls.length === tempFilePaths.length || that.data.files.length + finished.urls.length == this.data.maximgs)
              resolve(finished)
          },

          //失败
          fail: function (err) {
            console.log(err)
          }
        })
      }
    })
  },
  uploadError(e) {
    console.log('upload error', e.detail)
    wx.hideLoading()
    this.setData({
      error: "上传失败,可能有些照片过大"
    })
  },
  uploadSuccess(e) {
    console.log('upload success', e.detail)
    this.data.files = this.data.files.concat(e.detail.url)
    this.setData({
      files: this.data.files
    })
    wx.hideLoading()
  },

  //删除图片 detail为{index, item}，index表示删除的图片的下标，item为图片对象。
  delimg(e) {
    this.data.files.splice(this.data.files.findIndex(item => item == e.detail.item), 1)
  },

  getXunjianItems() {
    var obj = new Object()
    obj.busEnterpriseId = this.data.busEnterpriseId
    http.post("/system/AppXunjianController/getXunjianItems", obj, this.getXunjianItemsSuccess)
  },
  getXunjianItemsSuccess(res) {
    console.log(res)
    this.setData({
      xunjianItems: res.xunjianItems
    })
  },

  submitXujian() {
    var obj = new Object();
    let that = this
    wx.getLocation({
      type: 'wgs84', //返回可以用于wx.openLocation的经纬度，
      success: function (res) {
        obj.latitude = res.latitude
        obj.longitude = res.longitude
        obj.xuanjianItems = that.data.xunjianItems
        obj.busEnterpriseId = that.data.busEnterpriseId
        http.wxpost("/system/AppXunjianController/submitXunjian", obj, that.submitXujianSuccess)
      }
    })


  },
  submitXujianSuccess(res) {
    if (res.code == 200) {
      if(res.data.haveXQZG == true){
        //有限期整改的东西，去通知书页面
        wx.navigateTo({
          url: '../xqzggzs2/xqzggzs2?logId='+res.data.logId+"&busEnterpriseId="+this.data.busEnterpriseId,
        })
      }else{
        // 直接返回详情页
        wx.navigateTo({
          url: '../details/details?busEnterpriseId='+this.data.busEnterpriseId,
        })
      }
    } else {
      wx.showToast({
        title: res.msg,
        icon: "none"
      })
    }
  },

  cz_xunjianItems(listid, checked, jibie) {
    this.data.xunjianItems[jibie][1].forEach(item => {
      if (item.listid == listid) {
        item.checked = checked
      }
    })
  },

  bindViewXunJiancz(){
    wx.navigateTo({
      url: '../xunjiancz/xunjiancz?busEnterpriseId='+this.data.busEnterpriseId,
    })
  },




  //-------------------悬浮移动---------------------------------------------------
  // 触摸开始事件 
  touchStart: function (e) {
    touchStartX = e.touches[0].pageX; // 获取触摸时的原点 
    touchStartY = e.touches[0].pageY; // 获取触摸时的原点 
    // 使用js计时器记录时间 
    interval = setInterval(function () {
      time++;
    }, 100);
  },
  // 触摸移动事件 
  touchMove: function (e) {
    touchMoveX = e.touches[0].pageX;
    touchMoveY = e.touches[0].pageY;

  },
  // 触摸结束事件 
  touchEnd: function (e) {
    var moveX = touchMoveX - touchStartX
    var moveY = touchMoveY - touchStartY
    if (Math.sign(moveX) == -1) {
      moveX = moveX * -1
    }
    if (Math.sign(moveY) == -1) {
      moveY = moveY * -1
    }
    if (moveX <= moveY) { // 上下
      // 向上滑动
      if (touchMoveY - touchStartY <= -30 && time < 10) {
        console.log("向上滑动")
      }
      // 向下滑动 
      if (touchMoveY - touchStartY >= 30 && time < 10) {
        console.log('向下滑动 ');
      }
    } else { // 左右
      // 向左滑动
      if (touchMoveX - touchStartX <= -30 && time < 10) {
        console.log("左滑页面")
      }
      // 向右滑动 
      if (touchMoveX - touchStartX >= 30 && time < 10) {
        console.log('向右滑动');
      }
    }
    clearInterval(interval); // 清除setInterval 
    time = 0;
  },



})

var touchStartX = 0; //触摸时的原点 
var touchStartY = 0; //触摸时的原点 
var time = 0; // 时间记录，用于滑动时且时间小于1s则执行左右滑动 
var interval = ""; // 记录/清理时间记录 
var touchMoveX = 0; // x轴方向移动的距离
var touchMoveY = 0; // y轴方向移动的距离