import { getUserDetails,getUserLineChart,getUserOnlineStatus } from '../../api/userManagement'
import * as echarts from "echarts";
import { Debounce, throttle } from "../../utils/publicMethods";
export default {
    name: 'UserDetails',
    data() {
      return {
        userDetailsID: null,
        userData: {
            // address:"D7tviVPKtTd2qnkzJEVfZWQqzV6NyQqHxw",
            // historyBalance:[
            //     {
            //         "balance": "testAddBalanceForgrD7tviVPKtTd2qnkzJEVfZWQqzV6NyQqHxws"
            //     },
            //     {
            //         "balance": "testAddBalancD7tviVPKtTd2qnkzJEVfZWQqzV6NyQqHxweForgrs"
            //     },
            //     {
            //         "balance": "testAddBalancD7tviVPKtTd2qnkzJEVfZWQqzV6NyQqHxweForgrs"
            //     },
               
            // ],
            // maxHeight:"100000",
            // createDate:"2025-06-16 00:00:00",
            // amount:"273920.96662387",
            // coin:"nexa",
            // shouldOutDate:"2025-06-16 00:00:00",
            // user:"ceshi1",
        },
        userDetailsLoading: false,
        formInline: {
          user: '',
          region: ''
        },
        userDetailsParams:{
          coin: '',
          minerUser: '',
          startDate:"",
          endDate:"",
        
        },
        labelPosition: 'top',
        noDataTip: false,
        lineChartParams:{         
          minerUser: '',
            endDate:"",
            startDate:"",
            coin:"",
           
        },
        onlineStatusParams:{ 
          minerUser: '',
            coin: '',          
            endDate:"",
            startDate:"",
         },
         onlineStatusData:[

          {
            "date":"2024-11-28T11:00:00",
            "offlineNum": 148,
            "onlineNum": 15
          },
          {
            "date":"2025-06-27 17:00:00",
            "offlineNum": 110,
            "onlineNum": 156
          },
          {
            "date":"2025-06-27 17:30:00",
            "offlineNum": 90,
            "onlineNum": 152
          },
          {
            "date":"2025-06-27 18:00:00",
            "offlineNum": 70,
            "onlineNum": 152
          },
          {
            "date":"2025-06-27 18:00:00",
            "offlineNum": 70,
            "onlineNum": 152
          },
          {
            "date":"2025-06-27 18:00:00",
            "offlineNum": 70,
            "onlineNum": 152
          },
          {
            "date":"2025-06-27 18:00:00",
            "offlineNum": 70,
            "onlineNum": 152
          },
         ],
         lineChatTimes:[],
         option: {
          tooltip: {
              trigger: "axis",
              //解决tooltip显示不全问题1 
              confine: true,

              // formatter: function (params) {
              //     var res
              //     res = params[0].axisValueLabel;


              //     for (let i = 0; i <= params.length - 1; i++) {

              //         if (params[i].seriesName == "Currency Price" || params[i].seriesName == "币价") {
              //             res += `</br>${params[i].marker} ${params[i].seriesName} &nbsp&nbsp&nbsp&nbsp <span style="font-weight: bold">${params[i].value} USD</span>`
              //         } else {
              //             res += `</br>${params[i].marker} ${params[i].seriesName} &nbsp&nbsp&nbsp&nbsp <span style="font-weight: bold">${params[i].value}</span>`
              //         }

              //     }



              //     return res;
              // },

          },
          legend: {
              right: "8%",

          },
          // grid: {//解决Y轴显示不全
          //     left: "10%",//10%
          //     containLabel: true
          // },
          grid: {
              left: "8%",
              right: "8%",
              top: "10%",
              bottom: "15%", // 增加底部空间，为旋转的X轴标签和滑动条留出空间
          },


          xAxis: {
              // type: "time",
              boundaryGap: true, // 让柱子不超出X轴
              axisLabel: {
                  interval: 'auto', // 自动间隔显示标签，避免重叠
                  rotate: 45, // 旋转45度，避免标签重叠
                  formatter: function(value) {
                      // 格式化显示，只显示月-日 时:分
                      if (value.includes(' ')) {
                          const [date, time] = value.split(' ');
                          const [year, month, day] = date.split('-');
                          const [hour, minute] = time.split(':');
                          return `${month}-${day} ${hour}:${minute}`;
                      }
                      return value;
                  }
              },
              // axisTick: {
              //     //去除刻度
              //     show: false,
              // },
              // axisLine: {
              //     //去除轴线
              //     show: false,
              // },
              data: []
          },
          yAxis: [
              {
                  // position: "left",
                  type: "value",
                  name: "GH/s",
                  nameTextStyle: {

                      padding: [0, 0, 0, -40],
                  },
                  // min: `dataMin`,
                  // max: `dataMax`,
                  axisLabel: {
                      formatter: function (value) {
                          // let data
                          // if (value > 10000000) {
                          //     data = `${(value / 10000000)} KW`
                          // } else if (value > 1000000) {
                          //     data = `${(value / 1000000)} M`
                          // } else if (value / 10000) {
                          //     data = `${(value / 10000)} W`
                          // }
                          return value
                      }
                  }
              },
              {

                  position: "right",
                  // type: "log",
                  // splitNumber: "5",
                  show: true,
                  // min: 0,
                  // max: this.maxValue,
                  splitLine: {//不显示右侧Y轴横线
                      show: false
                  },
                  // name: "",
                  nameTextStyle: {

                      padding: [0, 0, 0, 40],
                  }
              },

          ],
          dataZoom: [
              {
                  type: "inside",
                  start: 50, // 默认显示后30%的数据，避免图表过于拥挤
                  end: 100,
                  maxSpan: 100,
                  minSpan: 2, // 最小显示5%的数据
                  animation: false,
              },
              {
                  type: "inside", 
                  start: 50,
                  end: 100,
                  height: 20, // 滑动条高度
                  bottom: 0, // 滑动条位置
                  showDetail: false, // 不显示详细数值
              },
          ],
          series: [
            
              {//在线数量
                  name: "Number of users online",
                  type: "bar",                       
                  data: [],
                  yAxisIndex: 1,
                  itemStyle: {
                    color: '#239342', // 这里设置柱子的主色为绿色
                  
                  },
                  barWidth: '40%', // 使用百分比宽度，保持适当的柱子宽度
                  barGap: '10%', // 同类型柱子间的间隔
                  barCategoryGap: '20%', // 类目间的间隔
                
              },
              {
                name: "Number of offline users",
                type: "bar",
                // smooth: false, //线条是否圆滑
                // symbol: "circle",
                // symbolSize: 5,
                // showSymbol: false,
                itemStyle: {
                    color: "#FE2E74",
                    borderColor: "rgba(221,220,107,0.1)",
                 
                },
                barWidth: '40%', // 使用百分比宽度，保持适当的柱子宽度
                barGap: '10%', // 同类型柱子间的间隔
                barCategoryGap: '20%', // 类目间的间隔
     
                data: [],
                yAxisIndex: 1,
              
            },
              {
                name: "User computing power",
                type: "line",
                smooth: false, //线条是否圆滑
                symbol: "circle",
                symbolSize: 5,
                showSymbol: false,
                itemStyle: {
                    color: "#5721E4",
                    borderColor: "rgba(221,220,107,0.1)",
                    borderWidth: 12,
                },
                lineStyle: {
                    //线条样式
                    color: "#5721E4",
                    width: "2",
                },
                // areaStyle: {
                //     color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                //         {
                //             offset: 0,
                //             color: 'rgb(210,195,234)'
                //         },
                //         {
                //             offset: 1,
                //             color: 'rgb(255, 255, 255)'
                //         }
                //     ])
                // },
                zlevel: 1, z: 1,
                data: [],
                yAxisIndex: 0,
            },



          ],
        },
        lineChartLoading:false,
        lineChartData:[

          {           
            "minerUser": "miner",
            "pv": "8.00080",
            "date": "2024-11-28T11:00:00",
            "unit":"GH/s"
          },
          {           
            "minerUser": "miner",
            "pv": "6.00060",
            "date": "2024-11-28T11:30:00",
            "unit":"GH/s"
          },
          {           
            "minerUser": "miner",
            "pv": "0.05000",
            "date": "2024-11-28T12:00:00",
            "unit":"GH/s"
          },
          {           
            "minerUser": "miner",
            "pv": "2.0000",
            "date": "2024-11-28T12:30:00",
            "unit":"GH/s"
          },
          {           
            "minerUser": "miner",
            "pv": "0.3000",
            "date": "2024-11-28T13:00:00",
            "unit":"GH/s"
          },
          {           
            "minerUser": "miner",
            "pv": "0.9000",
            "date": "2024-11-28T13:30:00",
            "unit":"GH/s"
          },
          {           
            "minerUser": "miner",
            "pv": "15.0000",
            "date": "2024-11-28T14:00:00",
            "unit":"GH/s"
          },

          
          
        ],
        chartShow:true,
        tableData:[
          // {
          //   "shouldOutDate":"2025-06-16T00:00:00",
          //   "allocationAmount":"27366620.96662387",
          //   "transferAmount":"27389920.96662387",
          //   "address":"D7tviVPKtTd2qnkzJEVfZWQqzV6NyQqHxw",
          //   "maxHeight":"100000",
           
          // },
          // {
          //   "shouldOutDate":"2025-06-16T00:00:00",
          //   "allocationAmount":"",
          //   "transferAmount":"920.96662387",
          //   "address":"D7tviVPKtTd2qnkzJEVfZWQqzV6NyQqHxw",
          //   "maxHeight":"100000",
           
          // },
          // {
          //   "shouldOutDate":"2025-06-16T00:00:00",
          //   "allocationAmount":"2720.96662387",
          //   "transferAmount":"920.96662387",
          //   "address":"D7tviVPKtTd2qnkzJEVfZWQqzV6NyQqHxw",
          //   "maxHeight":"100000",
           
          // },
          // {
          //   "shouldOutDate":"2025-06-17T00:00:00",
          //   "allocationAmount":"273920.96662387",
          //   "transferAmount":"273920.96662387",
          //   "address":"D7tviVPKtTd2qnkzJEVfZWQqzV6NyQqHxw",
          //   "maxHeight":"100000",
           
          // },
          // {
          //   "shouldOutDate":"2025-06-18T00:00:00",
          //   "allocationAmount":"273920.96662387",
          //   "transferAmount":"273920.96662387",
          //   "address":"D7tviVPKtTd2qnkzJEVfZWQqzV6NyQqHxw",
          //   "maxHeight":"100000",
           
          // },
          // {
          //   "shouldOutDate":"2025-06-19T00:00:00",
          //   "allocationAmount":"273920.96662387",
          //   "transferAmount":"273920.96662387",
          //   "address":"D7tviVPKtTd2qnkzJEVfZWQqzV6NyQqHxw",
          //   "maxHeight":"100000",
           
          // },
          // {
          //   "shouldOutDate":"2025-06-19T00:00:00",
          //   "allocationAmount":"2720.96662387",
          //   "transferAmount":"220.96662387",
          //   "address":"D7tviVPKtTd2qnkzJEVfZWQqzV6NyQqHxw",
          //   "maxHeight":"100000",
           
          // },
          // {
          //   "shouldOutDate":"2025-06-20T00:00:00",
          //   "allocationAmount":"273920.96662387",
          //   "transferAmount":"273920.96662387",
          //   "address":"D7tviVPKtTd2qnkzJEVfZWQqzV6NyQqHxw",
          //   "maxHeight":"100000",
           
          // },
          // {
          //   "shouldOutDate":"2025-06-21T00:00:00",
          //   "allocationAmount":"273920.96662387",
          //   "transferAmount":"273920.96662387",
          //   "address":"D7tviVPKtTd2qnkzJEVfZWQqzV6NyQqHxw",
          //   "maxHeight":"100000",
           
          // },


        ],
        historyBalance:[],
        mergeConfig: {}, // 存储合并配置

      }
    },
    watch: {
      tableData: {
        handler() {
          this.calculateMergeConfig()
        },
        deep: true
      }
    },
    mounted() {
          let token
          try{
            token =JSON.parse(localStorage.getItem('token')) 
          }catch(e){
          console.log(e);
          }
          if (!token) {
              this.$router.push({ path: `/${lang}/login` });
              
          }
        const params= this.$route.query || JSON.parse(localStorage.getItem("userDetailsParams"));
        this.lineChartParams.minerUser=params.minerUser
        this.lineChartParams.coin=params.coin
        this.onlineStatusParams.minerUser=params.minerUser
        this.onlineStatusParams.coin=params.coin
        this.userDetailsParams.coin=params.coin
        this.userDetailsParams.minerUser=params.minerUser
      
        if (this.userDetailsParams.coin && this.userDetailsParams.minerUser) {
          localStorage.setItem("userDetailsParams", JSON.stringify(params));
        
          this.fetchUserDetails(this.userDetailsParams);
          // 等待两个图表相关接口都完成后再调用inCharts
          this.fetchChartData();
        } 
  

        // this.calculateMergeConfig()


    },
    methods: {
      /**
     * 提取日期部分（去掉时间）
     * @param {string} dateTimeString - 完整的日期时间字符串
     * @returns {string} 日期部分
     */
    extractDate(dateTimeString) {
      if (!dateTimeString) return ''
      return dateTimeString.split('T')[0]
    },
    
          //初始化图表
          inCharts() {
            if (this.myChart == null) {
                this.myChart = echarts.init(document.getElementById("lineChart"));
            }
     

            this.option.series[0].name = this.$t(`backendSystem.onlineUserNum`)
            this.option.series[1].name = this.$t(`backendSystem.offlineUserNum`)
            this.option.series[2].name = this.$t(`backendSystem.userPower`)

            this.myChart.setOption(this.option);
            // 回调函数，在渲染完成后执行
            this.myChart.on('finished', () => {
              // 图表渲染完成
              console.log('图表渲染完成');
            });
          
            window.addEventListener('resize', throttle(() => {
                if (this.myChart) this.myChart.resize();
            }, 200));
        },
      async fetchUserDetails(params) {
        this.setLoading('userDetailsLoading', true);
        // 获取用户详情逻辑
        const res = await getUserDetails(params)
        console.log(res)

        if(res && res.code == 200){
            if (!res.data) {
                this.noDataTip = true
                // this.userData.coin = this.userDetailsParams.coin
                // this.userData.user = this.userDetailsParams.minerUser
            }else{
                this.userData = res.data
                // this.userData.shouldOutDate=`${this.userData.shouldOutDate.split("T")[0]} ${this.userData.shouldOutDate.split("T")[1]}` 
                // this.userData.createDate=`${this.userData.createDate.split("T")[0]} ${this.userData.createDate.split("T")[1]}` 
                this.historyBalance=res.data.historyBalance
                this.tableData = res.data.walletInInfo.sort((a, b) => new Date(b.createDate) - new Date(a.createDate));
                this.noDataTip = false
            }
            // 🔥 在更新数据后重新计算合并配置
            this.$nextTick(() => {
              this.calculateMergeConfig()
            })

        }
        this.setLoading('userDetailsLoading', false);
      },
      async fetchUserLineChart(params) {
        const res = await getUserLineChart(params)
        console.log(res)
        let xData = []
        let pvData = []
        if(res && res.code == 200){
         
          if (!Array.isArray(res.data) || res.data.length === 0 || !res.data[0].unit) {
            this.chartShow = false
            return;
          }
          this.chartShow = true
          this.lineChartData = res.data
          this.lineChartData.forEach(item => {
            item.date = item.date.split("T")[0] + " " + item.date.split("T")[1].split(".")[0]
            xData.push(item.date)
            pvData.push(Number(item.pv).toFixed(6))
          })

          this.option.xAxis.data = xData
          this.option.series[2].data = pvData
          this.option.yAxis[0].name = this.lineChartData[0].unit
          // this.inCharts()
        }
      },
      async fetchUserOnlineStatus(params) {
        const res = await getUserOnlineStatus(params)
        console.log(res)
        // let xData = []
        let offlineNum = []
        let onlineNum = []
        if(res && res.code == 200){
          if (!Array.isArray(res.data) || res.data.length === 0 ) {
            this.chartShow = false
            return;
          }
          this.chartShow = true
          this.onlineStatusData = res.data
          
          this.onlineStatusData.forEach(item => {          
            offlineNum.push(item.offlineNum)
            onlineNum.push(item.onlineNum)
          })
          this.option.series[0].data = onlineNum
          this.option.series[1].data = offlineNum
       
       
        }
      },
      /**
       * 获取图表数据 - 等待两个接口都完成后再渲染图表
       */
      async fetchChartData() {
        try {
          this.setLoading('lineChartLoading', true);
          
          // 并行调用两个接口，等待都完成
          await Promise.all([
            this.fetchUserLineChart(this.lineChartParams),
            this.fetchUserOnlineStatus(this.onlineStatusParams)
          ]);
          
          // 两个接口都完成后，检查是否有数据再渲染图表
          if (this.chartShow) {
            this.inCharts();
          }
          
        } catch (error) {
          console.error('获取图表数据失败:', error);
        } finally {
          this.setLoading('lineChartLoading', false);
        }
      },
      goBack(){
        const lang = this.$i18n.locale;
        this.$router.push({ 
            path: `/${lang}/userManagement`, 
        })
      },

      handleLineChatTimesChange(val){
        console.log(val,'val');
        if(val){
          this.lineChartParams.startDate=val[0]
          this.lineChartParams.endDate=val[1]
          this.onlineStatusParams.startDate=val[0]
          this.onlineStatusParams.endDate=val[1]
          this.userDetailsParams.startDate=val[0]
          this.userDetailsParams.endDate=val[1]

        }else{
          this.lineChartParams.startDate=""
          this.lineChartParams.endDate=""
          this.onlineStatusParams.startDate=""
          this.onlineStatusParams.endDate=""
          this.userDetailsParams.startDate=""
          this.userDetailsParams.endDate=""
        }
        this.fetchUserDetails(this.userDetailsParams);
        // 等待两个图表相关接口都完成后再调用inCharts
        this.fetchChartData();
      },

        /**
     * 计算合并配置
     * 根据 shouldOutDate 的日期部分进行分组和合并
     */
    calculateMergeConfig() {
      const dateGroups = {}
      const mergeConfig = {}
      
      // 按日期分组
      this.tableData.forEach((row, index) => {
        const dateKey = this.extractDate(row.shouldOutDate)
        if (!dateGroups[dateKey]) {
          dateGroups[dateKey] = []
        }
        dateGroups[dateKey].push(index)
      })
      
      // 计算每个日期组的合并信息
      Object.values(dateGroups).forEach(group => {
        if (group.length > 1) {
          // 第一行显示合并的单元格
          mergeConfig[group[0]] = {
            shouldOutDate: group.length, // 合并的行数
          }
          
          // 其他行的日期列不显示
          for (let i = 1; i < group.length; i++) {
            mergeConfig[group[i]] = {
              shouldOutDate: 0, // 0表示不显示
            }
          }
        }
      })
      
      this.mergeConfig = mergeConfig
      console.log('合并配置:', this.mergeConfig)
    },

     /**
     * Element UI 表格合并单元格方法
     * @param {Object} param0 - 包含行索引、列索引等信息
     * @returns {Array} [rowspan, colspan] 合并配置
     */
     handleSpanMethod({ rowIndex, columnIndex }) {
      // 列索引对应关系：
      // 0: shouldOutDate (日期列)
      // 1: allocationAmount  
      // 2: transferAmount
      // 3: address
      // 4: maxHeight
      
      // 只对日期列（索引为0）进行合并
      if (columnIndex === 0) {
        const config = this.mergeConfig[rowIndex]
        if (config && typeof config.shouldOutDate !== 'undefined') {
          return [config.shouldOutDate, 1] // [rowspan, colspan]
        }
      }
      
      return [1, 1] // 默认不合并
    },
      /**
     * 处理时间显示（如果你还需要这个方法）
     * @param {string} dateTime - 日期时间字符串
     * @returns {string} 格式化后的日期
     */
      handelTime(dateTime) {
        if (!dateTime) return ''
        return this.extractDate(dateTime)
      }

    
    }
  }