import { Component, OnInit, ViewChild, inject } from '@angular/core';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { CommonModule } from '@angular/common';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { SHARED_IMPORTS } from '@shared';
import { DataVCardComponent } from '../card/card.component';
import * as echarts from 'echarts';
import { AgGridAngular } from 'ag-grid-angular';
import { DataVTitleComponent } from '../title/title.component';
import { ColDef } from 'ag-grid-community'; // Column Definition Type Interface
import { NzProgressModule } from 'ng-zorro-antd/progress';
import { NzBadgeModule } from 'ng-zorro-antd/badge';
import { Subscription, finalize } from 'rxjs';
import { IMqttMessage, MqttService } from 'ngx-mqtt';
import { ChartComponentComponent } from './chart-component/chart-component.component';
import { NzListModule } from 'ng-zorro-antd/list';
@Component({
  selector: 'app-data-v-s1',
  standalone: true,
  templateUrl: './s1.component.html',
  styleUrls: ['./s1.component.less'],
  imports: [
    CommonModule,
    NzBadgeModule,
    NzProgressModule,
    AgGridAngular,
    DataVCardComponent,
    DataVTitleComponent,
    NzListModule,
    ...SHARED_IMPORTS,
    ChartComponentComponent
  ]
})
export class DataVS1Component implements OnInit {
  private readonly http = inject(_HttpClient);
  private readonly modal = inject(ModalHelper);
  chartConfig = {
    //每行数
    rowNumber: 1,
    //check 表格
    optionsCheckList: [
      { label: '全水', options: {}, checked: true },
      { label: '热值', options: {}, checked: true },
      { label: '全硫', options: {}, checked: false },
      { label: '内水', options: {}, checked: false },
      { label: '灰分', options: {}, checked: false },
      { label: '挥发分', options: {}, checked: false }
    ],
    //底部
    optionBottomList: [{}],
    //左边表格option
    optionsList: [
      { label: '全水', options: {}, checked: true },
      { label: '热值', options: {}, checked: true }
    ],
    //左边table
    tableList: [
      {
        coldef: [
          { headerName: '时间', field: 'rwmc', unSortIcon: true, minWidth: undefined, flex: 1 },
          { headerName: '系统/设备', field: 'rwms', unSortIcon: true, minWidth: undefined, flex: 1 },
          { headerName: '操作描述', field: 'kssj', unSortIcon: true, minWidth: undefined, flex: 1 },
          { headerName: '操作人员', field: 'jhwcsj', unSortIcon: true, minWidth: undefined, flex: 1 }
        ],
        rowData: []
      },
      {
        coldef: [
          { headerName: '序号', field: 'rwmc', unSortIcon: true, minWidth: undefined, flex: 1 },
          { headerName: '时间', field: 'kssj', unSortIcon: true, minWidth: undefined, flex: 1 },
          { headerName: '任务描述', field: 'rwms', unSortIcon: true, minWidth: undefined, flex: 1 },
          { headerName: '等级', field: 'dqzt', unSortIcon: true, minWidth: undefined, flex: 1 }
        ],
        rowData: []
      }
    ]
  };
  handleCheckedItems(checkedItems: { label: string; checked: boolean }[]) {
    console.log('当前选中的项目:', checkedItems);
  }
  chart_options = {};
  chart_options0 = {};
  chart_options1 = {};
  chart_options2 = {};
  chart_options3 = {};
  chart_options4 = {};
  rowData: object[] = [];
  colDefs1: ColDef[] = [
    { headerName: '时间', field: 'rwmc', flex: 1 },
    { headerName: '系统/设备', field: 'rwms', flex: 1 },
    { headerName: '操作描述', field: 'kssj', flex: 1 },
    { headerName: '操作人员', field: 'jhwcsj', flex: 1 }
  ];
  colDefs2: ColDef[] = [
    { headerName: '序号', field: 'rwmc', flex: 1 },
    { headerName: '时间', field: 'kssj', flex: 2 },
    { headerName: '任务描述', field: 'rwms', flex: 1 },
    { headerName: '等级', field: 'dqzt', flex: 1.5 }
  ];
  private subscription: Subscription;
  constructor(private _mqttService: MqttService) {
    this.subscription = this._mqttService.observe('s1').subscribe((message: IMqttMessage) => {
      const messagePayload = JSON.parse(message.payload.toString());
      console.log('Received message as object: ', messagePayload.msg);
      this.chart_options0 = messagePayload.msg;
    });
  }
  ngOnInit(): void {
    /** 获取服务器配置 */
    this.getServerConfig();
    for (var i = 1; i < 30; i++) {
      this.rowData.push({
        rwmc: '任务' + i,
        rwms: '任务描述' + i,
        kssj: '2024-1-' + i + ' 13:38:' + i * 11,
        jhwcsj: '2024-1-' + i + ' 13:38:' + i * 10,
        sfcq: '否',
        dqzt: '正常',
        dqjd: '节点' + i,
        sjwcsj: '2024-1-' + i + ' 13:38:' + i * 27,
        bjmc: '报警5',
        bjms: '报警描述5',
        bjsj: '2024-1-' + i + ' 13:38:' + i * 12,
        gzyy: '-',
        clff: '-',
        tzsj: '2024-1-' + i + ' 13:38:' + i * 19,
        zycd: '一般',
        tzmc: '系统提示',
        tznr: '账户登录',
        fj: '-',
        cz: '操作'
      });
    }
    var errorData = [];
    var categoryData = [];
    var barData = [];
    var dataCount = 100;
    for (var i = 0; i < dataCount; i++) {
      var val = Math.random() * 1000;
      categoryData.push('category' + i);
      errorData.push([i, echarts.number.round(Math.max(0, val - Math.random() * 100)), echarts.number.round(val + Math.random() * 80)]);
      barData.push(echarts.number.round(val, 2));
    }
    this.chart_options = {
      backgroundColor: 'transparent',
      series: [
        {
          type: 'gauge',
          startAngle: 180,
          endAngle: 0,
          center: ['50%', '75%'],
          radius: '90%',
          min: 0,
          max: 1,
          splitNumber: 8,
          axisLine: {
            lineStyle: {
              width: 6,
              color: [
                [0.25, '#74FAFB'],
                [0.5, '#74FAFB'],
                [0.75, '#74FAFB'],
                [1, '#74FAFB']
              ]
            }
          },
          pointer: {
            icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
            length: '12%',
            width: 20,
            offsetCenter: [0, '-60%'],
            itemStyle: {
              color: 'auto'
            }
          },
          axisTick: {
            length: 12,
            lineStyle: {
              color: 'auto',
              width: 2
            }
          },
          splitLine: {
            length: 20,
            lineStyle: {
              color: 'auto',
              width: 5
            }
          },
          axisLabel: {
            color: '#464646',
            fontSize: 20,
            distance: -60,
            rotate: 'tangential',
            formatter: function (value: any) {
              if (value === 0.875) {
                return '';
              } else if (value === 0.625) {
                return '';
              } else if (value === 0.375) {
                return '';
              } else if (value === 0.125) {
                return '';
              }
              return '';
            }
          },
          title: {
            offsetCenter: [0, '-10%'],
            fontSize: 20
          },
          detail: {
            fontSize: 30,
            offsetCenter: [0, '-5%'],
            valueAnimation: true,
            formatter: function (value: any) {
              return Math.round(value * 100) + '';
            },
            color: 'inherit'
          },
          data: [
            {
              value: 0.9,
              name: ''
            }
          ]
        }
      ]
    };
    this.chart_options0 = {
      backgroundColor: 'transparent',
      series: [
        {
          type: 'gauge',
          startAngle: 180,
          endAngle: 0,
          center: ['50%', '75%'],
          radius: '90%',
          min: 0,
          max: 1,
          splitNumber: 8,
          axisLine: {
            lineStyle: {
              width: 6,
              color: [
                [0.25, '#74FAFB'],
                [0.5, '#74FAFB'],
                [0.75, '#74FAFB'],
                [1, '#74FAFB']
              ]
            }
          },
          pointer: {
            icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
            length: '12%',
            width: 20,
            offsetCenter: [0, '-60%'],
            itemStyle: {
              color: 'auto'
            }
          },
          axisTick: {
            length: 12,
            lineStyle: {
              color: 'auto',
              width: 2
            }
          },
          splitLine: {
            length: 20,
            lineStyle: {
              color: 'auto',
              width: 5
            }
          },
          axisLabel: {
            color: '#464646',
            fontSize: 20,
            distance: -60,
            rotate: 'tangential',
            formatter: function (value: any) {
              if (value === 0.875) {
                return '';
              } else if (value === 0.625) {
                return '';
              } else if (value === 0.375) {
                return '';
              } else if (value === 0.125) {
                return '';
              }
              return '';
            }
          },
          title: {
            offsetCenter: [0, '0%'],
            fontSize: 20
          },
          detail: {
            fontSize: 30,
            offsetCenter: [0, '-5%'],
            valueAnimation: true,
            formatter: function (value: any) {
              return Math.round(value * 100) + '';
            },
            color: 'inherit'
          },
          data: [
            {
              value: 0.97,
              name: ''
            }
          ]
        }
      ]
    };
    this.chart_options1 = {
      title: {
        textStyle: {
          color: '#ffffff'
        },
        text: '全水',
        subtext: '(kg/kg)'
      },
      legend: {
        data: ['测量值', '上限值', '下限值']
      },
      calculable: true,
      xAxis: [
        {
          axisLine: {
            lineStyle: {
              color: [
                [0.25, '#74FAFB'],
                [0.5, '#74FAFB'],
                [0.75, '#74FAFB'],
                [1, '#74FAFB']
              ]
            }
          },
          position: 'bottom',
          type: 'category',
          data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '测量值',
          type: 'line',
          data: [100, 155, 139, 199, 220, 160, 120, 182.2, 150, 155, 160, 180],
          markPoint: {
            data: [
              { name: '最大值', value: 220, xAxis: 4, yAxis: 220 },
              { name: '最小值', value: 100, xAxis: 0, yAxis: 100 }
            ]
          },
          markLine: {
            data: [{ type: 'average', name: '平均值' }]
          }
        },
        {
          type: 'custom',
          name: 'error',
          itemStyle: {
            borderWidth: 1.5
          },
          renderItem: function (_params: any, api: any) {
            var xValue = api.value(0);
            var highPoint = api.coord([xValue, api.value(1)]);
            var lowPoint = api.coord([xValue, api.value(2)]);
            var halfWidth = api.size([1, 0])[0] * 0.1;
            var style = api.style({
              stroke: api.visual('color'),
              fill: undefined
            });
            return {
              type: 'group',
              children: [
                {
                  type: 'line',
                  transition: ['shape'],
                  shape: {
                    x1: highPoint[0] - halfWidth,
                    y1: highPoint[1],
                    x2: highPoint[0] + halfWidth,
                    y2: highPoint[1]
                  },
                  style: style
                },
                {
                  type: 'line',
                  transition: ['shape'],
                  shape: {
                    x1: highPoint[0],
                    y1: highPoint[1],
                    x2: lowPoint[0],
                    y2: lowPoint[1]
                  },
                  style: style
                },
                {
                  type: 'line',
                  transition: ['shape'],
                  shape: {
                    x1: lowPoint[0] - halfWidth,
                    y1: lowPoint[1],
                    x2: lowPoint[0] + halfWidth,
                    y2: lowPoint[1]
                  },
                  style: style
                }
              ]
            };
          },
          encode: {
            x: 0,
            y: [1, 2]
          },
          data: errorData,
          z: 100
        }
      ]
    };

    this.chart_options2 = {
      title: {
        text: '热值',
        subtext: '(kg/kg)'
      },
      legend: {
        data: ['超差样数量', '不合格样数量']
      },
      xAxis: [
        {
          type: 'category',
          // prettier-ignore
          data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '超差样数量',
          type: 'line',
          data: [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
          markPoint: {
            data: [
              { type: 'max', name: 'Max' },
              { type: 'min', name: 'Min' }
            ]
          }
        },
        {
          name: '不合格样数量',
          type: 'bar',
          data: [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
          markPoint: {
            data: [
              { name: 'Max', value: 182.2, xAxis: 7, yAxis: 183 },
              { name: 'Min', value: 2.3, xAxis: 11, yAxis: 3 }
            ]
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }]
          }
        }
      ],
      grid: {
        left: '3%',
        right: '3%',
        bottom: '3%',
        containLabel: true
      },

      toolbox: {
        show: false,
        feature: {
          dataView: { show: true, readOnly: false },
          magicType: { show: true, type: ['line', 'bar'] },
          restore: { show: true },
          saveAsImage: { show: true }
        }
      },
      calculable: true
    };
    this.chart_options3 = {
      title: {
        text: '煤样超差率'
      },

      grid: {
        top: '10%',
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['超差样量', '总样量']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: [3, 16],
          label: {
            show: true,
            position: 'top',
            formatter: function (data: { value: string }) {
              return data.value;
            }
          },
          type: 'bar'
        }
      ]
    };
    this.chart_options4 = {
      title: {
        text: '煤样合格率',
        left: 'center'
      },
      grid: {
        top: '10%',
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['超差样量', '总样量']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: [15, 16],
          type: 'bar',
          label: {
            show: true,
            position: 'top',
            formatter: function (data: { value: string }) {
              return data.value;
            }
          }
        }
      ]
    };
    //this.chartConfig.optionsCheckList[0].options = this.chart_options1;
    this.chartConfig.optionsCheckList[1].options = this.chart_options2;
    this.chartConfig.optionsCheckList[2].options = this.chart_options3;
    this.chartConfig.optionsCheckList[3].options = this.chart_options4;
    this.chartConfig.optionBottomList[0] = this.chart_options3;
    this.chartConfig.optionBottomList[1] = this.chart_options4;
  }
  public unsafePublish(topic: string, message: string): void {
    this._mqttService.unsafePublish(topic, message, { qos: 1, retain: true });
  }
  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
  /**
   * 服务器获取配置
   */
  getServerConfig() {
    this.http.get('http://localhost:5006/api/config/s1').subscribe(res => {
      this.chartConfig.optionsCheckList[0].options = res['data'];
      console.log(res);
    });
  }
}
