// pages/electricQuery/index.js
import { exportElectricityList, getAccountingList, getElectricityList, getMeterReadingList } from "../../../service/accounting";
import { getTenementMeterList } from "../../../service/meter";
import { getParkInfoByTime } from "../../../service/park";
import dayjs from "../../../utils/dayjs";
import request from '../../../utils/request';
import * as echarts from '../../components/echarts/echarts';
import { alertInfo, getPixelRatio, loadingFunc } from "../../../utils/index";
const { OK } = request;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    queryType: 0,
    timeType: 0,
    show: false,
    columns: [],
    meterList: [],
    meterCode: "",
    meterId: "",
    year: dayjs().format('YYYY'),
    yearMonth: dayjs().format("YYYY-MM"),
    yearMonthDay: dayjs().format("YYYY-MM-DD"),

    yearStamp: new Date().getTime(),
    yearMonthStamp: new Date().getTime(),
    yearMonthDayStamp: new Date().getTime(),


    header: [
      // { key: 'address', title: '电表地址', renderBody: (item) => item.meter?.address },
      { title: '时间',renderBody: (item) => { return item.time } },
      { key: 'number', title: '耗量' },
    ],
    valleyHeader: [
      // { key: 'address', title: '电表地址', renderBody: (item) => item.meter?.address },
      { title: '时间',renderBody: (item) => { return item.time } },
      { key: 'critical', title: '尖' },
      { key: 'peak', title: '峰' },
      { key: 'flat', title: '平' },
      { key: 'valley', title: '谷' },
      { key: 'deepValley', title: '深谷' },
    ],
    list: [],
    visible: false,
    accountingList: [],
    electricNumber: 0,
    meterNumber: 0,
    page: 1,
    readingPage: 1,
  },
  changeQueryType(e) {
    const { type } = e.currentTarget.dataset
    this.setData({ queryType: type },() => {
      switch(type) {
        case 0:
          loadingFunc(async () => {
            await this.init()
          })
          break;
        case 1:
          // loadingFunc(async () => {
          //   await this.getReadingList();
          // })
          // break;
        case 2:
          loadingFunc(async () => {
            await this.getAccountingBalanceList();
          })
    
          break;
      }

    })
  },
  clickTime() {
    const { timeType } = this.data;
    this.setData({
      timePickerType: timeType === 0 ? "day" : (timeType === 1 ? 'month' : 'year'),
      visible: true
    })
  },
 
  changeTimeType(e) {
    const { type } = e.currentTarget.dataset;
    const that = this;
    this.setData({ timeType: type }, () => {
      loadingFunc(async () => {
        await that.init()
      })
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    loadingFunc(async () => {
      await this.getMeters()
      await this.getParkInfo()
      await this.init()
    })
  },
  async init() {
    const { queryType, timeType, meterId, year, yearMonth, yearMonthDay, page, parkInfo } = this.data;
    let time;
    switch(timeType) {
      case 1:
        time = yearMonth;
        break;
      case 2: 
        time = year;
        break;
      default:
        time = yearMonthDay;
        break;
    }
    const { code, message, data, electricNumber, meterNumber, total } = await getElectricityList({ type: timeType, meter: meterId, time: time, page })
    if (code !== OK) {
      alertInfo(message)
      return;
    }
    this.setData({ 
      list: data, 
      electricNumber: Number(electricNumber)?.toFixed(2), 
      meterNumber: Number(meterNumber), 
      totalPage: Math.ceil(total / 20) 
    })
    if (!data?.length) {
      return;
    }
    this.selectComponent('#echarts').init((canvas, width, height) => {
      // 初始化图表
      const pieChart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: getPixelRatio(),
      });
      const ids = [...new Set(data?.map(item => item?.meter?.id))]
      const point = data?.[0]?.time?.slice(-1)
      const times = [...new Set(data?.map(item => item.time))].
      map(item => Number(item.replace(point, ""))).
      sort((a, b) => a - b).
      map(ele => `${ele}${point}`.padStart(3, "0"));

      const options  = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data:  data?.map(item => item?.meter?.address),
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: times
        },
        yAxis: {
          type: 'value'
        },
        series: ids?.map(item => {
          const element = data?.find(i => i?.meter?.id === item)
          const list = data?.filter(ele => ele?.meter?.id === item)
          const newList = [...times].map(item => {
            const exist = list.find(ele => ele.time === item)
            if (exist) {
              return Number(exist.critical || 0)+ Number(exist.peak || 0)+Number(exist.flat || 0)+Number(exist.valley || 0)+Number(exist.deepValley || 0);
            }
            return null
          })
          return {
            name: element?.meter?.address,
            type: 'line',
            data: newList
          }}) 
         
      };
      pieChart.setOption(options);
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return pieChart;
    });
  },
  
  async export() {
    loadingFunc(async () => {
      const { queryType, timeType, meterId, year, yearMonth, yearMonthDay } = this.data;
      let time;
      switch(timeType) {
        case 1:
          time = yearMonth;
          break;
        case 2: 
          time = year;
          break;
        default:
          time = yearMonthDay;
          break;
      }
      const data = await exportElectricityList({ type: timeType, meter: meterId, time: time })
      // if (code !== OK) {
      //   alertInfo(message)
      //   return;
      // }
          wx.openDocument({
            filePath: data.tempFilePath,
            fileType: ['xlsx'],
            showMenu: true,
            success() {
            },
            fail(err) {
            }
          })
       
    })
  },
  async onChangePage(e) {
    const page = e.detail.currentIndex;
    const that = this;
    this.setData({
      page
    }, () => {
      that.init();
    })
  },
  async getAccountingBalanceList() {
    const { meterId } = this.data;
    const { code, message, data } = await getAccountingList(meterId)
    if (code !== OK) {
      alertInfo(message)
      return;
    }
    this.setData({ accountingList: data, totalPage: 1 })
  },
  async getMeters() {
    const { id } = wx.getStorageSync('tenement')
    const { code, message, data } = await getTenementMeterList(id);
    if (code !== OK) {
      alertInfo(message)
      return;
    }
    const first = data?.[0]
    this.setData({
      meterList: data || [],
      meterId: first?.id,
      meterAddress: first?.address,
      meterCode: first?.code, 
    }, () => {
      const { queryType, } = this.data;
      switch(queryType) {
        case 1:
          loadingFunc(async () => {
            await this.getReadingList();
          })
          break;
        case 2: 
          loadingFunc(async () => {
            await this.getAccountingBalanceList();
          })
          break;
        default:
          loadingFunc(async () => {
            await this.init();
          })
          break;
      }
    })
  },
  clickMeter() {
    this.setData({
      type: "meter",
      columns: [
        // { id: "", name: "全部", code: "" },
        ...this.data.meterList.map(item => ({ 
          id: item.id, 
          name: `${item.code}-${item.address}`, 
          code: item.code,
          address: item.address 
        }))],
      show: true,
      title: "表计"
    })
  },
  onCancel() {
    this.setData({
      type: "meter",
      columns: [],
      show: false,
      title: "",
    })
  },
  onOk(e) {
    const { id, code, address } = e.detail.value;
    this.setData({
      // year: currentYear,
      meterId: id,
      meterCode: code, 
      meterAddress: address,
      type: "",
      show: false,
      title: ""
    }, () => {
      const { queryType, } = this.data;
      switch(queryType) {
        case 1:
          loadingFunc(async () => {
            await this.getReadingList();
          })
          break;
        case 2: 
          loadingFunc(async () => {
            await this.getAccountingBalanceList();
          })
          break;
        default:
          loadingFunc(async () => {
            await this.init();
          })
        
          break;
      }
    })
  },
  onTimeClose() {
    this.setData({ visible: false })
  },
  onTimeCancel() {
    this.setData({ visible: false })
  },
  
  onTimeConfirm(e) {
    const { type, time } = e.detail;
    switch(type) {
      case "year":
        this.setData({ year: time,  visible: false, }, () => {
          loadingFunc(async () => {
            await this.getParkInfo()
            await this.init();
          })
        });
        break;
      case "month":
        const [year, month] = time.split("-")
        this.setData({ yearMonth: time, yearMonthStamp: new Date(Number(year), Number(month) - 1, 1).getTime(), visible: false }, () => {
          loadingFunc(async () => {
            await this.getParkInfo()
            await this.init();
          })
        });
        break;
      case "day":
        this.setData({ 
          yearMonthDay: time, 
          yearMonthDayStamp: new Date(time).getTime(), 
          visible: false,
          page: 1,
        }, () => {
          loadingFunc(async () => {
            await this.getParkInfo()
            await this.init();
          })
        })
        break;
    }
  },
  readingChangeTime(e) {

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

  },

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

  },
  async getParkInfo() {
    const park = wx.getStorageSync('park');
    const { timeType, yearMonthDay, yearMonth, year } = this.data;
    let time = ''
    switch(timeType) {
      case 0:
        time = yearMonthDay;
        break;
      case 1:
        time = yearMonth;
        break;
      case 2:
        time = year;
    }
    const { park:parkInfo, code, message } = await getParkInfoByTime(park?.id,  `${time}`, `${timeType}`,)
    if (code !== OK) {
      alertInfo(message)
      return;
    }
    const that = this;
    return new Promise((resolve) => {
     
      that.setData({
        parkInfo: parkInfo
      }, () => {
        resolve()
      })
    })

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

  },

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

  },

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

  },

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

  },

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

  }
})