import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { NzMessageService, NzTabChangeEvent } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { STColumn } from '@delon/abc';
import { environment } from '@env/environment';
import { Router } from '@angular/router';

@Component({
  selector: 'app-profile-advanced',
  templateUrl: './advanced.component.html',
  styleUrls: ['./advanced.component.less'],
  // changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProProfileAdvancedComponent implements OnInit {
  list: any[] = [];
  base: any = {};
  isLoading = false;
  weektemp: {};
  weekhumid: {};
  weektilt: {};
  monthtemp: {};
  monthhumid: {};
  monthtilt: {};
  trans = {
    temp: '温度数据',
    humid: '湿度数据',
    tilt: '倾斜数据',
    month: '近一月',
    week: '近一周',
  };
  option = {
    title: {
      text: '',
      left: 'center',
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: [],
    },
    grid: {
      left: '4%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      data: [],
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: false,
      },
      splitArea: {
        show: true,
        areaStyle: {
          color: ['#F5F7FA', '#fff']
        }
      },
    },
    series: [{
      data: [],
      symbol: 'none',
      type: 'line',
      lineStyle: {
        color: '#0098d9',
      },
    }],
  };
  leftItems = [{
    icon: 1,
    label: '名称',
    per: '',
    value: 'towerName',
  }, {
    icon: 2,
    label: '搭建时间',
    per: '',
    value: 'createTime',
  }, {
    icon: 3,
    label: '温度',
    per: '℃',
    value: 'temp',
  }, {
    icon: 4,
    label: '湿度',
    per: '%rH',
    value: 'humid',
  }, {
    icon: 11,
    label: '网关电量',
    per: '%',
    value: 'bat',
  }];

  constructor(public msg: NzMessageService, private http: _HttpClient, private message: NzMessageService, private router: Router) {
  }

  ngOnInit() {
    this.getBase();
    this.getWeekCharts();
    this.getMonthCharts();
  }

  getBase() {
    const req = {
      sn: '19040999',
      type: 'WTD93RX',
    };
    this.http.post(environment.baseUrl + '/data/getRealTimeData', req).subscribe((res: any) => {
      this.handle(res, () => {
        if (res && res.towerNo) {
          this.base = res;
          this.base.tiltWarn = (res.tilt && Number(res.tilt) < 20 && Number(res.tilt) > -20) || res.tilt === 'N/A' ? true : false;
        } else {
          this.message.error(res.message);
        }
      });
    });
  }

  getWeekCharts() {
    this.isLoading = true;
    const param = ['tilt', 'temp', 'humid'];
    param.map((item, index) => {
      this.getChart(item, 'week', index);
    });
  }

  getMonthCharts() {
    this.isLoading = true;
    const param = ['tilt', 'temp', 'humid'];
    param.map((item, index) => {
      this.getChart(item, 'month', index);
    });
  }

  getChart(item, type, index) {
    const end = type === 'week' ? new Date().getTime() - 7 * 24 * 3600 * 1000 : new Date().getTime() - 30 * 24 * 3600 * 1000;
    const req = {
      endTime: new Date().getTime(),
      parameter: item,
      sn: '19040999',
      startTime: end,
      type: 'WTD93RX',
    };
    this.http.post(environment.baseUrl + '/data/getHistoryDataByTime', req).subscribe((res: any) => {
      this.handle(res, () => {
        if (res.historyData && res.historyData.constructor === Array && res.historyData.length > 0) {
          const len = res.historyData.length - 1;
          const data = [];
          const xAxis = [];
          const option = JSON.parse(JSON.stringify(this.option));
          res.historyData.map((one, i) => {
            data.push(one.value);
            xAxis.push(one.time);
            if (i === len) {
              option.series[0].data = data;
              option.xAxis.data = xAxis;
              option.title.text = this.trans[type] + this.trans[item];
              option.yAxis.name = '数值(' + res.unit + ')';
              option.series[0].name = this.trans[type] + this.trans[item];
              option.tooltip.formatter = '{a}<br/>时间: {b}<br/>数据值: {c}' + res.unit;
              this[type + item] = option;
            }
          });
        }
        if (index === 2) {
          this.isLoading = false;
        }
      });
    });
  }

  handle(res, next) {
    if (res.code === 2) {
      this.router.navigate(['/passport/login']);
    } else {
      next();
    }
  }
}
