var app = getApp();
const config = require('../../../config/config.js')
const util = require('../../../utils/util.js')
const Http = require('../../../utils/HttpBasics.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    actions: [
      // { name: "抄电", id: 1 },
      // { name: "抄水", id: 2 },
      // { name: "抄燃气", id: 3 }
    ],
    actionID: 1,
    timeIndex: 0,
    typeIndex: 0,
    searchIndex: 0,
    timeArr: ['区间1', '区间2', '区间3', '区间4'],
    typeArr: ['用户表', '公共表'],
    searchArr: ['按表号查询', '按店铺查询'],
    shopNumber: "",
    searchKey: "",
    buildIndex: 0,
    floorIndex: 0,
    shopIndex: 0,
    isShowBuilding: false,
    isShowfloor: false,
    isShowshop: false,
    buildArr: [],
    floorArr: [],
    shopArr: [],
    building: "",
    floor: "",
    preShopReadingList: [],
    date: "2024-08-28", //默认起始时间  
    date2: "2024-08-28", //默认结束时间 
  },

  goAction(e) {
    const id = e.target.dataset.id
    this.setData({
      actionID: id
    })
  },

  bindSelectChange(e) {
    const index = e.target.dataset.index
    const value = e.detail.value
    console.log(value, 'value');
    this.setData({
      searchKey: ""
    })

    if (index == "timeIndex") {
      this.setData({
        timeIndex: value
      })
    } else if (index == "typeIndex") {
      this.setData({
        typeIndex: value,
      })
    } else if (index == "searchIndex") {
      this.setData({
        searchIndex: value,
      })
    } else if (index == "buildIndex") {
      this.setData({
        building: this.data.buildArr[value].id,
        buildIndex: value,
        isShowBuilding: true,
        floorArr: this.data.buildArr[value].floors
      })
    } else if (index == "floorIndex") {
      // wx.showLoading({
      //   title: '请稍等',
      // })
      // this.getShopList(this.data.floorArr[value].id)
      this.setData({
        floor: this.data.floorArr[value].id,
        floorIndex: value,
        isShowfloor: true,
      })
    } else if (index == "shopIndex") {
      this.setData({
        shopIndex: value,
        isShowshop: true,
      })
    }
  },

  changeShopNumber(e) {
    const value = e.detail.value
    this.setData({
      shopNumber: value
    })
  },

  changeSearchKey(e) {
    const value = e.detail.value
    this.setData({
      searchKey: value
    })
  },

  getbuildingfloorlist() {
    Http.get({
      url: config.api.getbuildingfloorlist
    })
      .then(res => {
        console.log(res.data)
        this.setData({
          buildArr: res.data
        })
      })
      .catch(err => {

      });
  },

  getShopList(floor) {
    Http.get({
      url: config.api.getShopList + floor
    })
      .then(res => {
        console.log(res.data.list)
        this.setData({
          shopArr: res.data.list
        })
        wx.hideLoading()
      })
      .catch(err => {

      });
  },

  getShopMeterList() {
    let type = this.data.actionID
    // let shopNumber = this.data.shopNumber
    // let shopId = this.data.shopArr[this.data.shopIndex].id
    // if (!shopId) shopId = ""
    // const physicsType = this.data.typeIndex * 1 + 1
    const searchKey = this.data.searchKey
    const building = this.data.building
    const floor = this.data.floor
    console.log(building, floor);
    Http.get({
      // url: config.api.getShopMeterList +
      //   "physicsType=" + physicsType +
      //   "&type=" + type +
      //   "&shopId=" + shopId +
      //   "&shopNumber=" + shopNumber
      url: config.api.getShopMeterList +
        "searchKey=" + searchKey +
        "&type=" + type +
        "&building=" + building +
        "&floor=" + floor
    })
      .then(res => {
        console.log(res.data)
        this.setData({
          preShopReadingList: res.data.list
        })
        res.data.list.forEach((item, index) => {
          this.getPreShopReadingList(item.id, index)
        })
        if (!res.data.list.length) {
          wx.showToast({
            title: "该店铺暂无数据！",
            icon: 'error',
            duration: 2000,
            mask: false
          });
        }
      })
      .catch(err => {
      });
  },

  getPreShopReadingList(id, index) {
    Http.get({
      url: config.api.preShopReadingList + id
    })
      .then(res => {
        try {
          console.log(res, 'res', index);
          const preShopReadingList = [...this.data.preShopReadingList]
          if (res.data) {
            res.data.formatTime = this.timestampToTime(res.data.preTime, "YYYY-MM-DD")
            preShopReadingList[index].meterData = res.data
            console.log(index, 'index1');
          } else {
            const obj = {
              meterId: id,
              preNumber: "",
              curNumber: "",
              formatTime: "",
              preByName: ""
            }
            preShopReadingList[index].meterData = obj
            console.log(index, 'index2');
          }
          this.setData({
            preShopReadingList
          })
          console.log(preShopReadingList, 'preShopReadingList');
        } catch (error) {
          console.log(error, 'err');
        }
      })
      .catch(err => {
      });
  },

  getMeterList() {
    Http.get({
      url: config.api.meterList
    })
      .then(res => {
        const valus = Object.values(res.data)
        const keys = Object.keys(res.data)
        const arr = []
        valus.forEach((item, index) => {
          const obj = {
            id: keys[index] * 1,
            name: item
          }
          arr.push(obj)
        })
        this.setData({
          actions: arr
        })
        console.log(this.data.actions, 'this.data.actions')
      })
      .catch(err => {

      });
  },

  getTimeList() {
    Http.get({
      url: config.api.timeList + "?type=" + this.data.actionID
    })
      .then(res => {
        console.log(res.data)
        res.data.list.forEach(item => {
          item.period = item.period ? item.period : "*"
        })
        this.setData({
          timeArr: res.data.list
        })
      })
      .catch(err => {

      });
  },

  numberInput(e) {
    console.log(e, 'e');
    const index = e.currentTarget.dataset.index
    const value = e.detail.value
    const preShopReadingList = [...this.data.preShopReadingList]
    preShopReadingList[index].meterData.curNumber = value
    this.setData({
      preShopReadingList
    })
  },

  bindDateChange(e) {
    let that = this;
    that.setData({
      date: e.detail.value,
    })
    console.log(that.data.date)
  },
  bindDateChange2(e) {
    let that = this;
    that.setData({
      date2: e.detail.value,
    })
    console.log(that.data.date2)
  },

  isConfirmTouched() {
    wx.showToast({
      icon: "none",
      title: "该表已确认，无法更改！",
    })
  },

  save() {
    const meterReadingList = this.data.preShopReadingList.map(item => {
      const obj = {
        meterId: item.id,
        curNumber: item.meterData.curNumber,
      }
      if (item.meterData.id) {
        obj.id = item.meterData.id
      }
      return obj
    })
    Http.post({
      url: config.api.commitEnergyReading,
      data: {
        startTime: this.data.date + " 00:00:00",
        endTime: this.data.date2 + " 23:59:59",
        meterReadingList
      }
    }).then(res => {
      wx.showToast({
        title: "保存成功！",
        icon: 'none',
        duration: 2000,
        mask: false,
      });
      this.getShopMeterList()
    }).catch(err => {
      wx.showToast({
        title: err.message ? err.message : "保存失败！",
        icon: 'none',
        duration: 2000,
        mask: false
      });
    })
  },

  /**
* @description 根据时间戳获取时间
* @param {*} timestamp 必传，number类型，时间戳数据（10位及以下，10位至13位）;若不传，则返回：“无时间戳”
* @param {*} format  选传，string类型，提供以下时间格式：YYYY-MM-DD hh:mm:ss、YYYY/MM/DD hh:mm:ss、YYYY.MM.DD hh:mm:ss、YYYY MM DD hh:mm:ss、YYYY年MM月DD日 hh:mm:ss、YYYY-MM-DD、YYYY/MM/DD、YYYY.MM.DD、YYYY MM DD、YYYY年MM月DD日；若不传，则默认为：YYYY-MM-DD
* @returns 根据要求的时间格式
* @version V 1.0, Created by YWQ, 2022.10.20
*/
  timestampToTime(timestamp, format) {
    //时间戳为10位需*1000，时间戳为13位不需乘1000
    if (!timestamp) return
    const length = timestamp.length
    if (length <= 10) {
      var date = new Date(timestamp * 1000)
    } else {
      var date = new Date(timestamp)
    }
    let Y = String(date.getFullYear())
    let M = String(date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1)
    let D = String(date.getDate() + 1 < 10 ? '0' + (date.getDate()) : date.getDate())
    let h = String(date.getHours() + 1 < 10 ? '0' + (date.getHours()) : date.getHours())
    let m = String(date.getMinutes() + 1 < 10 ? '0' + (date.getMinutes()) : date.getMinutes())
    let s = String(date.getSeconds() + 1 < 10 ? '0' + (date.getSeconds()) : date.getSeconds())
    // return Y + M + D + h + m + s
    if (format == "YYYY-MM-DD hh:mm:ss") {
      return Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s
    } else if (format == "YYYY/MM/DD hh:mm:ss") {
      return Y + "/" + M + "/" + D + " " + h + ":" + m + ":" + s
    } else if (format == "YYYY.MM.DD hh:mm:ss") {
      return Y + "." + M + "." + D + " " + h + ":" + m + ":" + s
    } else if (format == "YYYY MM DD hh:mm:ss") {
      return Y + " " + M + " " + D + " " + h + ":" + m + ":" + s
    } else if (format == "YYYY年MM月DD日 hh:mm:ss") {
      return Y + "年" + M + "月" + D + "日" + " " + h + ":" + m + ":" + s
    } else if (format == "YYYY-MM-DD") {
      return Y + "-" + M + "-" + D
    } else if (format == "YYYY/MM/DD") {
      return Y + "/" + M + "/" + D
    } else if (format == "YYYY.MM.DD") {
      return Y + "." + M + "." + D
    } else if (format == "YYYY MM DD") {
      return Y + " " + M + " " + D
    } else if (format == "YYYY年MM月DD日") {
      return Y + "年" + M + "月" + D + "日"
    } else {
      return Y + "-" + M + "-" + D
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    Http.setToken(app.globalData.token)
    this.getbuildingfloorlist()
    this.getTimeList()
    this.getMeterList()
  },

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

  },

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

  },

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

  },

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

  },

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

  }
})