import * as echarts from "echarts"
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components';
import { PieChart } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

import {colorList, colorListBar, orderCharts, title, openMachine, groupByKeys, typesCharts} from './staticData'
import {viewGraphicsPieBar, viewGraphicsTypesBar} from "./graphicElements";
import {updatedGroupByData, choiceTypeBarTypesCharts} from './helpers'
import {axisBarConfig, windowConfig, sizeOptions} from './windowConfigs'
   
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout
])

const lineConfig = (params, id, windowConfig) => {
  const times = params.xAxisData
  const states = params.yAxisData
     
  const series = [
    {
      data: states,
      type: 'line'
    }
  ]

  const axisConfig = axisBarConfig(params.type, times, windowConfig, params.names)

  return {
    title: params.title,
    titleLeft: 'center',
    grid: {
      left: '5%',
      width: '90%',
      top: 30,
      containLabel: true
    },
    axisConfig,
    series,
    windowConfig,
    graphic: [{id: 'yAxisTitle', type: 'text', left: 40, top: 20, z: 999, style: {text: '%', fontSize: 12}}]
  }   
}

const linesConfig = (params, id, windowConfig) => {
  // console.log('params', params)
  const times = params.xAxisData
  const text = params.names.yAxis ? params.names.yAxis : 'Гб'
  const namesLegend = params.charts.map((el) => el.name)
     
  const series = params.charts.map((el) => {
    return {
      name: el.name,
      data: el.value.map((item) => item.state).reverse(),
      type: 'line'
    }
  })

  const axisConfig = axisBarConfig(params.type, times, windowConfig, params.names)

  return {
    title: params.title,
    titleLeft: 'center',
    legend: {
      textStyle: {
        fontSize: windowConfig?.line?.legend?.fontSize
      },
      orient: 'horizontal',
      // top: 360,
      bottom: windowConfig?.line?.legend?.bottom,
      // padding: windowConfig?.bar?.legend?.padding,
      left: 'center',
      itemGap: windowConfig?.line?.legend?.itemGap,
      itemWidth: windowConfig?.line?.legend?.itemWidth,
      itemHeight: windowConfig?.line?.legend?.itemHeight,
      data: namesLegend
    },
    grid: {
      left: '5%',
      width: '90%',
      top: 30,
      containLabel: true
    },
    axisConfig,
    series,
    windowConfig,
    graphic: [{id: 'yAxisTitle', type: 'text', left: 40, top: 20, z: 999, style: {text: text, fontSize: 12}}]
  }   
}

const linesPackConfig = (params, id, windowConfig) => {
  console.log('params', params)
  const times = params.xAxisData
  const text = params.names.yAxis ? params.names.yAxis : ' '
  const namesLegend = params.charts.map((el) => el.name)
     
  const series = params.charts.map((el) => {
    return {
      name: el.name,
      data: el.value.map((item) => item.state).reverse(),
      type: 'line'
    }
  })

  const axisConfig = axisBarConfig(params.type, times, windowConfig, params.names)

  return {
    title: params.title,
    titleLeft: 'center',
    legend: {
      textStyle: {
        fontSize: windowConfig?.line?.legend?.fontSize
      },
      orient: 'horizontal',
      // top: 360,
      bottom: windowConfig?.linesPack?.legend?.bottom,
      // padding: windowConfig?.bar?.legend?.padding,
      left: 'center',
      itemGap: windowConfig?.linesPack?.legend?.itemGap,
      itemWidth: windowConfig?.linesPack?.legend?.itemWidth,
      itemHeight: windowConfig?.linesPack?.legend?.itemHeight,
      data: namesLegend
    },
    grid: {
      left: '3%',
      width: '95%',
      height: '50%',
      top: 30,
      containLabel: true
    },
    axisConfig,
    series,
    windowConfig,
    graphic: [{id: 'yAxisTitle', type: 'text', left: 40, top: 20, z: 999, style: {text: text, fontSize: 12}}]
  }   
}

const pieConfig = (params, id, windowConfig) => {
  const data = params.machines.map((el) => {
    el.color = colorList(el.name)
    el.order = orderCharts(el.name)
    return el
  }).sort((a, b) => a.order - b.order)

  const series = [{
    name: '',
    type: 'pie',
    label: {
      position: 'inner',
      formatter: (d) => {
        // console.log('d', d)  
        return d.value
      },
      color: '#FFF',
      fontWeight: 'bold'
    },
    minAngle: 15,      
    center: ['50%', '50%'],
    radius: ['40%', '70%'],
    color: data.map((el) => el.color), //26.12.2023
    itemStyle: {
      borderRadius: 5,
      borderColor: '#FFF',
      borderWidth: 2
    },
    data: data,
    emphasis: {
      itemStyle: {
        // color: {
        //      type: 'radial',
        //      x: 0.4,
        //      y: 0.3,
        //      r: 1,
        //      // colorStops: [
        //      //   {
        //      //     offset: 0,
        //      // //     color: `rgb(251, 118, 123, 0.5)`,
        //      //     opacity: 0.5
        //      //   },
        //      //   {
        //      //     offset: 1,
        //      // //     color: `rgb(204, 46, 72, 0.5)`
        //      //     opacity: 0.5
        //      //   }
        //      // ]
        //    },
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)',
        opacity: 0.7
      }
    },
  }]

  return {
    title: title(id, params.countMachines),
    type: 'pie',
    legend: {
      formatter: (title) => {
        const [elem] = params.machines.filter((el) => el.name == title) //26.12.2023
        return title + ' ' + elem.value
      },
      textStyle: {
        fontSize: windowConfig?.pie?.legend?.fontSize
      },     
      icon: 'circle',
      orient: 'horizontal',
      bottom: 0,
      left: 'center',
      itemGap: windowConfig?.pie?.legend?.itemGap,
      itemWidth: windowConfig?.pie?.legend?.itemWidth,
      itemHeight: windowConfig?.pie?.legend?.itemHeight,
    },
    graphic: [{elements: viewGraphicsPieBar(id, params.period, params.countMachines, title(id, params.countMachines), windowConfig, params.isOpenMenu, params.type)}],
    series,
    windowConfig
  }
}

const barConfig = (params, id, windowConfig) => {
  // console.log('params', params)
  const countMachinesWithoutMl = params?.machines?.[params?.machines?.length - 1]?.key === 'routes_without_ml' ? params?.machines?.[params?.machines?.length - 1]?.values : 0
     
  const data = params?.machines?.map((el) => {
    el.itemStyle = {color: colorListBar(params.type, el.name)}
    return el
  }).sort((a, b) => a?.value - b?.value).reverse()

  const xAxisData = data.map((el) => {
    return `${el.name}`
  })

  const series = data?.map((chart, idx) => {
    return {
      name: `${chart?.name} ${chart?.value}`,
      type: 'bar',
      tooltip: {
        formatter: value => `${value.marker} ${value.data.name !== null ? value.data.name : 'Нет данных'} ${value.data.value}`
      },
      label: {
        show: true,
        position: 'inside',
        overflow: 'break',
        color: '#FFF',
        fontWeight: 'bold',
        textborderColor: '#ff0000'
        // formatter: '{c}'
      },
      labelLine: {
        show: true,
        lineStyle: {
          // color: 'source',
          color: 'black',
        }
      },
      labelLayout: 
               (p) => {
                 if(p.labelRect.width >= p.rect.width) {
                   return {hideOverlap: true}
                 }
               },
      scaleLimit: {
        min: 1,
        max: 5
      },
      itemStyle: {
        borderColor: chart?.itemStyle?.color,
        color: chart?.itemStyle?.color,
        //  borderRadius: 5,
        //  borderWidth: 1
      },
      barMinWidth: 25,
      barMinHeight: 20,
      barMaxWidth: '90%',
      barGap: '10%',
      barCategoryGap: '30%',
      groupPadding: 2,
      data: data.map((el, index) => idx === index ? el : ''),    
      // data: data, // Для мульти данных, то есть больше чем один тип данных в столбце 
      stack: 'total',
      sampling: 'average',
      emphasis: {
        itemStyle: {
          shadowBlur: 5,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
          opacity: 1
        }
      },
    }
  })

  const axisConfig = axisBarConfig(params.type, xAxisData, windowConfig)
          
  return {
    // label: {
    //      show: true,
    //      position: 'inside'
    //      },
    title: title(id, params.countMachines, params.countMachines_with_ml, params.countMachines_without_ml ? params.countMachines_without_ml : countMachinesWithoutMl),
    backgroundColor: '#FFF',
    legend: {
      textStyle: {
        fontSize: windowConfig?.bar?.legend?.fontSize
      },
      orient: 'horizontal',
      // top: 360,
      bottom: windowConfig?.bar?.legend?.bottom,
      // padding: windowConfig?.bar?.legend?.padding,
      left: 'center',
      itemGap: windowConfig?.bar?.legend?.itemGap,
      itemWidth: windowConfig?.bar?.legend?.itemWidth,
      itemHeight: windowConfig?.bar?.legend?.itemHeight,
    },
    grid: {
      left: '5%',
      width: '90%',
      top: 50,
      containLabel: true
    },
    axisConfig,
    graphic: [{elements: viewGraphicsPieBar(id, params.period, params.countMachines, title(id, params.countMachinesWithMl, countMachinesWithoutMl), windowConfig, params.isOpenMenu, params.type)}],
    series,
    windowConfig
  }
}

const barTypesConfig = (params, id, windowConfig, enableDataZoom) => {
  console.log('params', params)
  const isMlType = params.type === typesCharts.typesMl
  const isMountType = params.type === 'mount'

  const dataWithoutZero = choiceTypeBarTypesCharts(params).updatedData.dataGroupBy.map((el) => {
    const result = el.map((item) => {
      if(item.value === 0) {
        item.value = ''
        return item
      }
      if(item.name === null) {
        item.name = 'Нет данных'
        return item
      }
      return item
    }).sort((a, b) => {
      if(a.groupByKey && b.groupByKey) {
        (a.groupByData[a.groupByKey] - b.groupByData[b.groupByKey])
      }})

    return !isMountType ? result.reverse() : result
  })
     
  // console.log('dataWithoutZero', dataWithoutZero)
  const series = dataWithoutZero.map((charts) => {
    const [title] = choiceTypeBarTypesCharts(params).updatedData.dataCustomTitle.flat().filter((el) => el?.name == charts[0]?.name)
    return {
      name: `${title?.name} ${title?.count} id:${id}`,
      type: 'bar',
      tooltip: {
        formatter: value => `${value.marker} ${value?.data?.name !== null ? value?.data?.name : 'Нет данных'} ${value?.data?.value}`
      },
      label: {
        show: true,
        position: 'inside',
        overflow: 'break',
        color: '#FFF',
        fontWeight: 'bold',
        textborderColor: '#ff0000'
        // formatter: '{c}'
      },
      labelLine: {
        show: true,
        lineStyle: {
          // color: 'source',
          color: 'black',
        }
      },
      labelLayout: (p) => p.labelRect.width <= p.rect.width ? {hideOverlap: true} : {hideOverlap: false},
      // return {x: initCharts.getWidth() - 50, moveOverlap: 'shiftY'}
      // return {dx: 50, dy: -100}
      scaleLimit: {
        min: 1,
        max: 5
      },
      itemStyle: {
        borderColor: isMlType ? colorListBar(params.type, charts[0]?.name) : colorList(charts[0]?.name),
        color: isMlType ? colorListBar(params.type, charts[0]?.name) : colorList(charts[0]?.name),
        //  borderRadius: 5,
        //  borderWidth: 1
      },
      // barWidth: 30,
      // barMinWidth: 25,
      barMaxWidth: 35,
      barMinHeight: 30,
      barGap: '20%',
      barCategoryGap: '10%',
      groupPadding: 2,
      // data: data.map((el, index) => idx === index ? el : ''), // Для одного типа данных в столбце    
      data: charts,
      stack: 'total',
      sampling: 'average',
      large: true,
      largeThreshold: 100,
      progressiveThreshold: 1000,
      emphasis: {
        itemStyle: {
          shadowBlur: 5,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
          opacity: 1
        }
      },
    }
  })

  const axisConfig = axisBarConfig(params.type, choiceTypeBarTypesCharts(params).axisData, windowConfig)

  return {
    // label: {
    //      show: true,
    //      position: 'inside'
    //      },
    title: isMountType? title(id, params.countMounts) : title(id, params.countMachines, params.countMachinesWithMl, params.countMachinesWithoutMl),
    legend: {
      // icon: 'path://M224 320c8.823 0 16 7.177 16 16s-7.177 16-16 16-16-7.177-16-16 7.177-16 16-16m0-32c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zM320 0H128C64 0 0 42.981 0 96v256c0 47.169 50.656 86.391 106.9 94.473l-55.285 55.285c-3.78 3.78-1.103 10.243 4.243 10.243h25.798c3.183 0 6.235-1.264 8.485-3.515L150.627 448h146.745l60.486 60.485a12.002 12.002 0 0 0 8.485 3.515h25.798c5.345 0 8.022-6.463 4.243-10.243L341.1 446.472C397.344 438.391 448 399.169 448 352V96c0-53.019-63-96-128-96zM32 128h384v96H32v-96zm96-96h192c58.237 0 96 37.881 96 64H32c0-32.299 47.552-64 96-64zm192 384H128c-48.448 0-96-31.701-96-64v-96h384v96c0 32.299-47.552 64-96 64z',
      // backgroundColor: '#ff0000',
      orient: 'horizontal',
      textStyle: {
        fontSize: windowConfig?.bar?.legend?.fontSize
      },
      zLevel: 1,
      // top: 35,
      left: 'center',
      bottom: windowConfig?.bar?.legend?.bottom,
      itemGap: windowConfig?.bar?.legend?.itemGap,
      itemWidth: windowConfig?.bar?.legend?.itemWidth,
      itemHeight: windowConfig?.bar?.legend?.itemHeight,
      formatter: (e) => {
        return e.slice(0, e.indexOf('id') - 1)
      }
      // data: legendData
    },
    grid: {
      left: '1%',
      top: windowConfig?.bar?.grid?.top,
      width: windowConfig?.bar?.grid?.width,
      containLabel: true,
      height: isMountType ? '68%' : 'auto'
    },
    dataZoom: [
      {
        type: 'slider',
        show: true,
        width: 14,
        top: windowConfig?.bar?.dataZoom?.top,
        right: '3%',
        yAxisIndex: 0,
        realtime: true,
        start: windowConfig?.bar?.dataZoom?.start,
        end: 100,
        rangeMode: ['value', 'percent'],
        zoomLock: true,
        brushSelect: false,
        minSpan: windowConfig?.bar?.dataZoom?.minSpan,
        handleSize: 18,
        showDetail: false,
        handleIcon: "path://M12 0c-9.432 0-12 2.568-12 12s2.551 12 12 12 12-2.551 12-12-2.568-12-12-12z",
        handleStyle: {
          color: '#CCCCCC',
          borderColor: '#CCCCCC'
        }
      },
      {
        type: 'inside',
        yAxisIndex: 0,
        start: 70,
        end: 100,
        zoomOnMouseWheel: false,
        moveOnMouseWheel: true,
        handleSize: 18
      },
    ],
    graphic: isMountType ? [{elements: viewGraphicsPieBar(id, '', params.countMounts, title(id), windowConfig, params.isOpenMenu, params.type)}] : 
      [{elements: viewGraphicsTypesBar(id, title(id, isMlType ?  params.countMachinesWithMl :  params.countMachines, params.countMachinesWithoutMl), params.groupByKey, params.prevGroupByData, params.filterKey, params.prevGroupByFilters, params.type, params.groupByValue ? params.groupByValue : params.typeId ? params.typeId : null, params.period, params.yAxisData.length, windowConfig, params.isOpenMenu)}],
    series,
    axisConfig,
    windowConfig,
    enableDataZoom
  }
}

const config = (params) => {
  //  console.log('params', params)
  return {
    title: {
      text: params.title,
      subtextStyle: {
        fontSize: 11,
        align: 'left'
      },
      top: params.windowConfig?.title?.top,
      left: params.titleLeft ? params.titleLeft : params.windowConfig?.title?.left,
      textStyle: {
        width: params.windowConfig?.title?.width,
        fontSize: params.windowConfig?.title?.fontSize,
        overflow: 'break',
      },
               
    },
    backgroundColor: params.windowConfig?.backgroundColor,
    tooltip: {trigger: 'item'},
    legend: params.legend,
    xAxis: params.axisConfig?.xAxis ? params.axisConfig?.xAxis : '',
    yAxis: params.axisConfig?.yAxis ? params.axisConfig?.yAxis : '',
    dataZoom: params.enableDataZoom && params.dataZoom ? params.dataZoom : '',
    toolbox: {
      show: true,
      feature: {
        mark: {show: true},
        // dataView: {show: true, readOnly: false, title: ''},
        // magicType: {show: true, type: ['line', 'bar'], title: {line: 'Переключить на линейный график', bar: 'Переключить на график гистограмму'}  },
        // restore: {show: true, title: 'Обновить'},
        // saveAsImage: {show: true, title: ''}
      },
      iconStyle: {
        borderColor: '#333',
        // borderWidth: 0,
        // borderType: 'solid'
      },
      emphasis: {iconStyle: {
        borderColor: 'rgba(1, 97, 253, 0.3)',

      }},
      top: 16,
      right: 20,
    },
    graphic: params.graphic ? params.graphic : '',
    grid: params.grid ? params.grid : '',
    series: params.series
  }
     
}

class ECharts {
  constructor(id, sizes = {}) {
    this.id = id
    this.el = document.getElementById(id)
    const clientWidth = window.innerWidth
    const clientHeight = window.innerHeight
    this.isMobile = clientWidth < 768
    this.currentWidth = clientWidth - 100
    this.currentheight = clientHeight + 70
    this.widthChart = sizes.width ? sizes.width : 450
    this.heightChart = sizes.height ? sizes.height : 350
    this.mountHeightChart = 350
    this.charts = []
    this.legendFilterData = []

    this.initCharts = echarts.init(this.el, null, {renderer: 'canvas'})
    this.initCharts.showLoading()

    // window.addEventListener('resize', function() {
    //      this.initCharts.resize()
    // })
    console.log('sizes', sizes)
    this.getRes = this.el.getAttribute("get-res") == "true"
      
  }

  getChart(id) {
    if (this.getRes) {
      return {isGetChart: true, id}
    }
  }        

  makeLineCharts(charts) {
    charts.chartId = this.id
    this.charts = []
    this.charts.push(charts)
    this.initCharts.resize(sizeOptions(this.isMobile ? this.currentWidth : this.widthChart, charts.height ? charts.height : this.heightChart))
    this.initCharts.setOption(config(lineConfig(charts, this.id, windowConfig(this.isMobile, this.currentWidth))), {
      replaceMerge: ["series", "yAxis", "xAxis", "grid"],
    })
    this.initCharts.hideLoading()
  }

  makeLinesCharts(charts) {
    console.log('charts', charts)
    charts.chartId = this.id,
    this.charts = []
    this.charts.push(charts)
    if(this.initCharts) {
      this.initCharts.resize(sizeOptions(this.isMobile ? this.currentWidth : this.widthChart, charts.height ? charts.height : this.heightChart))
      this.initCharts.setOption(config(linesConfig(this.charts[0], this.id, windowConfig(this.isMobile, this.currentWidth))), {
        replaceMerge: ["series", "yAxis", "xAxis", "grid"],
      })
    }
    this.initCharts.hideLoading()
  }
     
  makeLinesPackCharts(charts) {
    console.log('charts', charts)
    charts.chartId = this.id,
    this.charts = []
    this.charts.push(charts)
    if(this.initCharts) {
      // this.initCharts.resize(sizeOptions(this.isMobile ? this.currentWidth : this.widthChart, charts.height ? charts.height : this.heightChart))
      this.initCharts.setOption(config(linesPackConfig(this.charts[0], this.id, windowConfig(this.isMobile, this.currentWidth))), {
        replaceMerge: ["series", "yAxis", "xAxis", "grid"],
      })
    }
    this.initCharts.hideLoading()
  }
     
  updateLineCharts(charts) {
    if(this.charts[0].xAxisData[this.charts[0].xAxisData.length - 1] !== charts.xAxisData[charts.xAxisData.length - 1]) {
      this.charts[0].xAxisData.shift()
      this.charts[0].xAxisData.push(charts.xAxisData[charts.xAxisData.length - 1])
      this.charts[0].yAxisData.shift()
      this.charts[0].yAxisData.push(charts.yAxisData[charts.yAxisData.length - 1])
      if(this.initCharts) {
        this.initCharts.setOption({xAxis: [{data: this.charts[0].xAxisData}], series: [{data: this.charts[0].yAxisData}]}, false)
      }
    }
  }
     
  updateLinesCharts(charts) {
    // console.log('charts', charts)
    if(this.charts[0].xAxisData[this.charts[0].xAxisData.length - 1] !== charts.xAxisData[charts.xAxisData.length - 1]) {
      this.charts[0].charts.forEach((el, idx) => {
        el.value.pop()
        el.value.unshift(charts.charts[idx].value[0])
      })
      this.charts[0].xAxisData.shift()
      this.charts[0].xAxisData.push(charts.xAxisData[charts.xAxisData.length - 1])
      if(this.initCharts) {
        this.initCharts.setOption({xAxis: [{data: this.charts[0].xAxisData}],series: [{data: this.charts[0].charts}]}, false)
      }
    }
  }
     
  makePieCharts(charts) {
    charts.chartId = this.id
    this.charts = []
    this.charts.push(charts)
    const initCharts = echarts.init(this.el, null, sizeOptions(this.widthChart, this.heightChart), {renderer: 'canvas'})
    initCharts.hideLoading()
    initCharts.resize(sizeOptions(this.isMobile ? this.currentWidth : this.widthChart, this.heightChart))
    initCharts.setOption(config(pieConfig(charts, this.id, windowConfig(this.isMobile, this.currentWidth))), true)
  }
    
  makeBarCharts(charts) {
    charts.chartId = this.el.id
    this.charts = []
    this.charts.push(charts)
    const initCharts = echarts.init(document.getElementById(`${this.el.id}`), null, {renderer: 'canvas'})
    initCharts.hideLoading() 
    initCharts.resize(sizeOptions(this.isMobile ? this.currentWidth : this.widthChart, this.heightChart))
    initCharts.setOption(config(barConfig(charts, this.el.id, windowConfig(this.isMobile, this.currentWidth))), true)
  }

  makeBarMountCharts(charts) {
    // console.log('charts', charts)
    charts.chartId = this.el.id
    this.charts = []
    this.charts.push(charts)
    this.mountHeightChart = charts.height
    const initCharts = echarts.init(document.getElementById(`${this.el.id}`), null, {renderer: 'canvas'})
    initCharts.hideLoading()
    initCharts.resize(sizeOptions(this.isMobile ? this.currentWidth : this.widthChart, charts.height))
    initCharts.setOption(config(barTypesConfig(charts, this.el.id, windowConfig(this.isMobile, this.currentWidth))), true)
  }
    
  makeBarTypesCharts(charts) {    
    charts.chartId = this.el.id
    this.charts = []
    this.charts.push(charts)
    console.log('charts - makeBarTypesCharts', charts.legendFilterData)
    const initCharts = echarts.init(document.getElementById(`${this.el.id}`), null, {renderer: 'canvas'})
    // this.heightChart = 270 + (charts?.yAxisData?.length * 27)
    const countCharts = charts?.yAxisData?.length
    const enableDataZoom = (countCharts * 35) + 200 > this.heightChart
    initCharts.hideLoading()
    initCharts.resize(sizeOptions(this.isMobile ? this.currentWidth : this.widthChart,  this.heightChart))
    initCharts.setOption(config(barTypesConfig(charts, this.el.id, windowConfig(this.isMobile, this.currentWidth, countCharts), enableDataZoom)), true)

    let currentLegendCount = 0
    if(charts.legendFilterData?.length > 0) {
      charts.legendFilterData?.map((legend) => {
        if(legend.id === this.el.id) {
          if(this.el.id !== 'routes_types_bar_ml') {
            charts.xAxisData.map((chart) => {
              chart.charts.reduce((acc, el) => {
                if(el.name === legend.filterData.name) {
                  currentLegendCount += Number(el.value)
                } else {
                  return acc
                }
              }, 0)
            })
          } else {
            charts.xAxisData.map((chart) => {
              chart.reduce((acc, el) => {
                if(el.charts.name === legend.filterData.name) {
                  currentLegendCount += Number(el.charts.value)
                } else {
                  return acc
                }
              }, 0)
            })
          }
          
          initCharts.dispatchAction({
            type: !legend.filterData.value ? 'legendUnSelect' : 'legendSelect',
            name: `${legend.filterData.name} ${currentLegendCount} id:${legend.id}`
          })
        }
        currentLegendCount = 0
      })
    }
  }

  setMenuChart (data) {
    if (data.groupByInfo.chartId) {
      this.charts = [data.groupByInfo.data]
      const [chart] = this.charts
      chart.chartId = data.groupByInfo.chartId
      chart.type = data.groupByInfo.type
      chart.isOpenMenu = data.openMenuChart
      const initCharts = echarts.init(document.getElementById(`${data.groupByInfo.chartId}`), null, {renderer: 'canvas'})
      const countCharts = chart?.yAxisData?.length
      const enableDataZoom = (chart?.yAxisData?.length * 35) + 200 > this.heightChart
      initCharts.hideLoading()
      initCharts.resize(sizeOptions(this.isMobile ? this.currentWidth : this.widthChart, data.groupByInfo.chartId.includes('mount') ? chart.height : this.heightChart))
      if(data.groupByInfo.chartId.includes('pie')) {
        initCharts.setOption(config(pieConfig(chart, data.groupByInfo.chartId, windowConfig(this.isMobile, this.currentWidth))), true)
      } else if (data.groupByInfo.chartId.includes('types_bar')) {
        initCharts.setOption(config(barTypesConfig(chart, data.groupByInfo.chartId, windowConfig(this.isMobile, this.currentWidth, countCharts), enableDataZoom)), true)
      } else if (data.groupByInfo.chartId.includes('mount')) {
        initCharts.setOption(config(barTypesConfig(chart, data.groupByInfo.chartId, windowConfig(this.isMobile, this.currentWidth))), true)
      } else {
        initCharts.setOption(config(barConfig(chart, data.groupByInfo.chartId, windowConfig(this.isMobile, this.currentWidth))), true)
      }
    }
  }

  downloadChart (data, updatedData) {
    if (data.groupByInfo.chartId) {
      this.charts = [data.groupByInfo.data]
      const [chart] = this.charts
      const countCharts = chart?.yAxisData?.length
      const initCharts = echarts.init(document.getElementById(`${data.groupByInfo.chartId}`), null, {renderer: 'canvas'})
      const enableDataZoom = (countCharts * 35) + 200 > data.updatedHeight
      initCharts.hideLoading()
               
      if(data.groupByInfo.chartId.includes('pie')) {
        initCharts.setOption(config(pieConfig(chart, data.groupByInfo.chartId, windowConfig(this.isMobile, this.currentWidth))), true)
        this.downloadImage(data.groupByInfo.title, this.prepareImage(initCharts))
      } else if (data.groupByInfo.chartId.includes('types_bar')) {
        console.log('this.charts', this.charts)
        initCharts.resize(sizeOptions(this.isMobile ? this.currentWidth : this.widthChart, data.groupByInfo.updatedHeight))
        initCharts.setOption(config(barTypesConfig(chart, data.groupByInfo.chartId, windowConfig(this.isMobile, data.groupByInfo.updatedHeight, countCharts), enableDataZoom)), true)

        initCharts.on('finished', () => {
          if(data.groupByInfo.isDownloadChart) {
            console.log('data', data)
            this.downloadImage(data.groupByInfo.title, this.prepareImage(initCharts))
            data.groupByInfo.isDownloadChart = false
            updatedData({action: 'downloadChart', groupByInfo: {...data.groupByInfo, updatedHeight: this.heightChart, data: this.charts}})
          }
        })

      } else if (data.groupByInfo.chartId.includes('mount')) {
        initCharts.setOption(config(barTypesConfig(chart, data.groupByInfo.chartId, windowConfig(this.isMobile, this.currentWidth))), true)
        this.downloadImage(data.groupByInfo.title, this.prepareImage(initCharts))
      } else {
        initCharts.setOption(config(barConfig(chart, data.groupByInfo.chartId, windowConfig(this.isMobile, this.currentWidth))), true)
        console.log('data.groupByInfo.title', data.groupByInfo.title)
        this.downloadImage(data.groupByInfo.title, this.prepareImage(initCharts))
      }
    }
  }
     
  prepareImage(initCharts) {
    const img = new Image()
    img.src = initCharts.getDataURL({type: 'canvas'})
    const myHeaders = new Headers()
    const myRequest = new Request(img.src, {
      method: "GET",
      headers: myHeaders,
      mode: "cors",
      cache: "default",
    })
    return myRequest
  }

  async downloadImage(name, myRequest) {
    try {
      const response = await fetch(myRequest)
      if (!response.ok) {
        throw new Error("Network response was not OK")
      }
      const myBlob = await response.blob()
      const imageURL = URL.createObjectURL(myBlob)
      const link = document.createElement('a')
      link.href = imageURL
      if (link.href) {
        const openedImage = window.open(link.href, '_blank')
        console.log('openedImage', openedImage)
        const linkImg = openedImage.document.createElement('a')
        linkImg.href = link.href
        linkImg.download = name
        openedImage.document.body.appendChild(linkImg)
        linkImg.click()
        openedImage.document.body.removeChild(linkImg)
      }
    }
    catch (error) {
      console.error("Error:", error)
    }
  }

  updateLegendFiltersData(params) {
    const [chart] = this.charts
    console.log('params - updateLegendFilterData', params)
    console.log('chart - updateLegendFilterData', chart)
    if (params.id === chart.chartId) {
      if(!params.filterData.value) {
        this.legendFilterData.push(params)
        return this.legendFilterData
      } else {
        const updatedFiltersData = this.legendFilterData.filter((legend) => legend.filterData.name !== params.filterData.name)
        this.legendFilterData = updatedFiltersData
        return updatedFiltersData
      }
    }
  }

  onClickedBarCharts(updatedData) {
    this.initCharts.on('click', (e) => {
      // console.log('e', e)
      const filterKey = e.data?.filterKey ? e.data?.filterKey : e.data?.filterKey
      if(filterKey && e.componentType === 'series' && e.data?.type !== 'mount') {
        // console.log('this.charts - nextLayoutChart', this.charts)
        updatedData({id: this.id, action: 'nextLayoutChart', data: this.charts, prevGroupByData: e.data.groupByData, prevGroupByFilters: e.data.prevGroupByData, filterKey: filterKey, groupByKey: e.data.groupByKey, groupByValue: e.data.groupByValue ? e.data.groupByValue : null, type: e.data.type})
      }
      if(e.event?.target?.id && e.info?.typeEl === 'buttonPrevious' && e.componentType === 'graphic') {
        // console.log('beforeLayoutChart')
        // console.log('e.info', e.info)
        updatedData({id: this.el.id, action: 'beforeLayoutChart', filterKey: e.event.target.id, groupByInfo: e.info})
      }
      if(e.event?.target?.id && e.info?.typeEl === 'menu' && e.componentType === 'graphic') {
        e.info.mountHeightChart = this.mountHeightChart
        // console.log('this.charts - menu', this.charts)
        updatedData({action: 'openMenuChart', groupByInfo: {...e.info, data: this.charts}})
      }
      if(e.event?.target?.id && (e.info?.typeEl === 'download' || e.info?.typeEl === 'downloadTitle') && e.componentType === 'graphic') {
        const fullHeight = e.info.countCharts * 35 + 200
        e.info.isDownloadChart = true
        updatedData({action: 'downloadChart', groupByInfo: {...e.info, updatedHeight: fullHeight, data: this.charts}})
      }
      if(e.event?.target?.id && e.info?.typeEl === 'link' && e.componentType === 'graphic') {
        const id = e.event?.target?.parent?.id
        const idx = id.slice(0, id.indexOf(':'))
        const layoutGroupKey = id.slice((id.indexOf('_') + 1), id.indexOf('-')).trim()
        const layoutGroupValue = id.slice(id.indexOf('-') + (id.includes('/') ? 3 : 2)).trim()
        const isCurrentLayout = Object.values(e.info?.prevGroupByData)[0] === layoutGroupValue
        if (isCurrentLayout && Object.keys(e.info.prevGroupByFilters).length > 1) { // Для выхода с первого вложенного слоя группировки
          return false
        } else {
          // console.log('e.info', e.info)
          const updatedPrevGroupByFilters = updatedGroupByData(idx, e.info.prevGroupByFilters, layoutGroupKey, layoutGroupValue)
          e.info.prevGroupByFilters = updatedPrevGroupByFilters
          e.info.prevGroupByData = {[layoutGroupKey]: layoutGroupValue}
          updatedData({id: this.el.id, action: 'beforeLayoutChart', filterKey: e.info.filterKey ? e.info.filterKey : null, groupByInfo: e.info})
        }
      }
      if(e.data?.groupByKey === groupByKeys.fiveLayout) {
        openMachine(e.data)
      }
    })

    this.initCharts.on('legendselectchanged', (params) => {
      if(params.name.indexOf('id:') > 0) {
        // Берём все данные производные из имени, так как это активный элемент легенды
        // const id = params.name.slice((params.name.indexOf('id:') + 3))
        const nameIdxEnd = (params.name.indexOf('id:') - 1)
        const namePrepare = params.name.slice(0, nameIdxEnd)
        const name = namePrepare.slice(0, namePrepare.lastIndexOf(' '))
        const updatedLegendFiltersData = this.updateLegendFiltersData({id: this.el.id, filterData: {name: name, value: params.selected[params.name]}})
        updatedData({action: 'legendFiltersParams', data: updatedLegendFiltersData})
      }
               
    })
  }
}

export {ECharts}
export default ECharts;