import { getReportDetail } from "../../../service/report";
import { alertInfo, alertSuccess, getPixelRatio, loadingFunc } from "../../../utils/index";
import request from '../../../utils/request'
import * as echarts from '../../components/echarts/echarts';
import { getRoundNumber } from "../../../utils/index"
const { OK } = request



// pages/billDetail/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: "",
    time: "",
    detail: {},
    meters: [],
    // header1: [
    //   { key: 'address', title: '电表地址' },
    //   { title: '起码',renderBody: (item) => { return item?.startNumber } },
    //   { title: '止码',renderBody: (item) => { return item?.endNumber } },
    //   { title: '倍率',renderBody: (item) => { return item?.displayRatio } },
    // ],
    // header2: [
    //   { title: '用电量', renderBody: (item) => item?.overall?.amount },
    //   { title: '线损电量',renderBody: (item) => item?.loss?.amount },
    //   { title: '公摊电量',renderBody: (item) => item?.publicAmount },
    //   { title: '合计电量',renderBody: (item) => { 
        
    //   } },
    // ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { id, time, tenement } = options;
    const that = this;
    loadingFunc(async () => {
      await that.init(id, time, tenement);
    })
  },
  async init(id, time, tenement) {
    const { code, message, detail, amount } = await getReportDetail(id, tenement)
    if (code !== OK) {
      alertInfo(message)
      return;
    }
    this.setData({
      id, 
      time, 
      detail, 
      amount: amount,
      meters: detail?.meters?.map(item => {
        if (item?.loss?.amount) {
          item.loss.amount = getRoundNumber(Number(item.loss.amount))
        }
        // const finalAmount = Number(item?.overall?.amount || 0) + Number(item?.loss?.amount || 0) + Number(item?.publicAmount || 0)
        item.finalAmount = getRoundNumber(Number(item.finalAmount))
        return item;
      })
    })
    if (detail?.park?.meter04kvType === 0) {
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: 10,
          left: 'center'
        },
        label: {
          alignTo: 'edge',
          formatter: '{name|{b}}\n{value|{c} }',
          minMargin: 5,
          edgeDistance: 10,
          lineHeight: 15,
          rich: {
            time: {
              fontSize: 10,
              color: '#999'
            }
          }
        },
        series: [
          {
            type: 'pie',
            radius: '50%',
            data: [
              { value: detail.comprehensive.lossAmount, name: '线损电量', itemStyle: { color: 'rgb(104,187,196)' } },
              { value: detail.comprehensive.consumption, name: '电度电量', itemStyle: { color: 'rgb(80,135,236)' } },
    
            ],
          }
        ]
      };
      this.init_pieCharts(option);
    } else {
      // const option = {
      //   tooltip: {
      //     trigger: 'item'
      //   },
      //   legend: {
      //     top: 10,
      //     left: 'center'
      //   },
      //   label: {
      //     alignTo: 'edge',
      //     formatter: '{name|{b}}\n{value|{c} }',
      //     minMargin: 5,
      //     edgeDistance: 10,
      //     lineHeight: 15,
      //     rich: {
      //       time: {
      //         fontSize: 10,
      //         color: '#999'
      //       }
      //     }
      //   },
      //   series: [
      //     {
      //       type: 'pie',
      //       radius: '50%',
      //       data: [
      //         { 
      //           value: detail.comprehensive.lossAmount, 
      //           name: '线损电量', 
      //         },
      //         { 
      //           value: detail.comprehensive.consumption, 
      //           name: '电度电量', 
      //         },
    
      //       ],
      //     }
      //   ]
      // };
      // this.init_pieCharts(option);
    }
    
    const that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          statusBarHeight : res.statusBarHeight,
          navBarHeight : res.statusBarHeight , // 顶部导航栏高度为 44px
          jiaonangheight: wx.getMenuButtonBoundingClientRect().height, // 胶囊高度
          jiaonangwidth:wx.getMenuButtonBoundingClientRect().width,
        })
      },
    })
  },
  init_pieCharts: function(options) {
    this.selectComponent('#echarts').init((canvas, width, height) => {
      // 初始化图表
      const pieChart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: getPixelRatio(),
      });
      
      pieChart.setOption(options);
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return pieChart;
    });
  },
  jumpToDetail(e) {
    const { meter } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/billMeterDetail/index?data=' + JSON.stringify(meter),
    })
  },
  download() {
    const { id: tenement } = wx.getStorageSync('tenement')
    const { id } = this.data;
    wx.showModal({
      title: '提示',
      content: '为了您更好的体验，请复制链接，通过浏览器打开下载',
      showCancel: true,
      cancelText: '关闭',
      confirmText: '复制链接',

      complete: (res) => {
        if (res.confirm) {
          const result = wx.getAccountInfoSync();
          const { envVersion } = result.miniProgram;
          switch (envVersion) {
            // 开发版
            case 'develop':
              wx.setClipboardData({
                data: `http://1.92.72.5:8080/user-report/?report=${id}&tenement=${tenement}`,
                success: () => {
                  alertSuccess("复制成功")
                }
              })
              break;
            // 体验版
            case 'trial':
              wx.setClipboardData({
                data: `http://1.92.72.5:8080/user-report/?report=${id}&tenement=${tenement}`,
                success: () => {
                  alertSuccess("复制成功")
                }
              })
              break;
            // 正式版
            case 'release':
              wx.setClipboardData({
                data: `https://zgd.hbhcbn.com/user-report/?report=${id}&tenement=${tenement}`,
                success: () => {
                  alertSuccess("复制成功")
                }
              })
              break;
          }
         
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})