fengxiang
2018-03-23 40951bf70651c38d09a3b1f5eaddde8faa9e8c06
src/app/routes/analysis/query/query.component.ts
@@ -1,384 +1,218 @@
import { ExampleService } from '@business/services/util/example.service';
import { MonitorPointService } from '@business/services/http/monitor-point.service';
import { AreacodeService } from '@business/services/http/areacode.service';
import { LineChartCriteria, TimePeriod, Organization, MonitorPoint, DataCondition, Device, PairData } from '@business/entity/data';
import { PageBean, ResultBean } from '@business/entity/grid';
import { Sensor } from '@business/entity/data';
import { SensorsService } from '@business/services/http/sensors.service';
import { Component, OnInit } from '@angular/core';
import { Component, OnInit, ViewChild } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { Sensor, Device, DataCondition, MonitorPoint, Organization, LineChartCriteria, PairData } from '@business/entity/data';
import { TimeUnits, AreaRange, ResultCode } from '@business/enum/types.enum';
import { SensorsService } from '@business/services/http/sensors.service';
import { PageBean, ResultBean, Grid } from '@business/entity/grid';
import { NzTreeComponent } from 'ng-tree-antd';
import * as moment from 'moment';
import { CascaderOption } from 'ng-zorro-antd/src/cascader/nz-cascader.component';
import { environment } from '@env/environment';
import { ExampleService } from '@business/services/util/example.service';
import { DeviceService } from '@business/services/http/device.service';
import { DateService } from '@business/services/util/date.service';
import { environment } from '@env/environment';
import { CascaderOption } from 'ng-zorro-antd/src/cascader/nz-cascader.component';
import { AreacodeService } from '@business/services/http/areacode.service';
import { MonitorPointService } from '@business/services/http/monitor-point.service';
import { NzMessageService } from 'ng-zorro-antd';
import * as $ from 'jquery';
import { DateService } from '@business/services/util/date.service';
import { zip } from 'rxjs/observable/zip';
@Component({
    selector: 'app-query',
    templateUrl: './query.component.html',
    styleUrls: ['./query.component.less']
  selector: 'app-query',
  templateUrl: './query.component.html',
  styleUrls: ['./query.component.less']
})
export class QueryComponent implements OnInit {
    public sensorList: Sensor[];
    public timeUnits: { label: string, value: TimeUnits }[] = [];
    public lineChartCriteria: LineChartCriteria = { sensorKey: 'e1', timePeriod: { startTime: null, endTime: null }, dataConditions: [] };
    _areas: { label: any, value: any };
    _monitorPoint: MonitorPoint;
    _device: Device;
    _dataTimeUnits: { label: string, value: TimeUnits } = { label: '日', value: TimeUnits.DAY };
    _actualTime: number;
    actualTimes: number[];
    public _timePeriodUnitValue: TimeUnits = TimeUnits.DAY; // 横坐标时间单位
    dataTimeUnitsList: { label: string, value: TimeUnits }[] = [];
    public monitorPoints: MonitorPoint[];
    public devices: Device[];
    // aqi六项排序
    private aqiSort = {
        e1: 1,
        e2: 2,
        e10: 3,
        e11: 4,
        e15: 5,
        e16: 6
    };
    public tableWidth = 2800;
    private tableWidthOption = {
        'MONTH': 1400,
        'DAY': 2800,
        'HOUR': 2100,
        'MINUTE': 5000
    };
    public expandForm: boolean; // 搜索区 展开控制
    // public sensors: any[] = [];
    public sensorOptions: any[] = [];
    /**
     * 数据类型,下拉列表数据
     * 注意,年度类型,对应查询数据单位为月,以此类推
     * @memberof QueryComponent
     */
    public timeUnitOptions = [
        {label: '某年', value: TimeUnits.MONTH},
        {label: '某月', value: TimeUnits.DAY},
        {label: '某日', value: TimeUnits.HOUR},
        {label: '某时', value: TimeUnits.MINUTE},
    ];
    public timeUnit: {label: string, value: TimeUnits} = this.timeUnitOptions[2];
    // 默认时间为昨天,今天无数据
    public actualTime: Date = moment().subtract(1, 'days').toDate();
    public actualYearOptions: number [];
    public isCollapse = false;
    public isChartCollapse = false;
    // 显示使用
    public _areas: { label: string, value: string }[] = new Array();
    public  grid: Grid<{sensor: Sensor, data: string [], weight?: number}> = new Grid();
    // public grid.data: {sensor: Sensor, data: string [], weight?: number} [] = [];
    //  样式控制,设备名称列冻结偏移
    public sensorNameScrollLeft = '0px';
     @ViewChild(NzTreeComponent)  private tree: NzTreeComponent;
     private _timeType: {showTime: boolean|{[key: string]: Function|boolean}, mode:  'month' | 'day', dateFormat: string  } = {showTime: false, mode: 'day', dateFormat: 'YYYY年MM月DD日'};
     // 用key-value方式,暂存监测项目
     private _sensors: {[key: string]: string} = {};
     private _sensorNames: string;
     get sensorNames(): string {
         return this._sensorNames;
     }
     public toggleCollapse() {
         this.isCollapse = !this.isCollapse;
     }
     public toggleChartCollapse() {
          // 打开的时候
         if (this.isChartCollapse && !!this.echartsIntance) {
            this.reloadChart();
            this.switchSensor(this.chartSelectedIndex);
            // this.chartLoading = false;
         }
         this.isChartCollapse = !this.isChartCollapse;
     }
     public deviceOptions: Device[] = [];
     public dataCondition: DataCondition = {areaRangeId: 320583, areaRange: AreaRange.AREA };
    dataConditionTemp: DataCondition = { timeUnits: TimeUnits.DAY, actualTime: null };
    get lineChartSensorName(): String {
        return !!this.sensorList ? this.sensorList.find(sensor => sensor.sensorKey === this.lineChartCriteria.sensorKey).name : null;
    }
    public set timePeriodUnitValue(value: TimeUnits) {
        this._timePeriodUnitValue = value;
        this.lineChartCriteria.timePeriod.timeUnits = value;
        switch (value) {
            // YYYY-MM-DD HH:mm:ss
            case TimeUnits.MONTH:
                this.timeType.dateFormat = 'YYYY-MM';
                this.timeType.mode = 'month';
                this.timeType.timePickerOption = null;
                break;
            case TimeUnits.DAY:
                this.timeType.dateFormat = 'YYYY-MM-DD';
                this.timeType.mode = 'day';
                this.timeType.timePickerOption = null;
                break;
            case TimeUnits.HOUR:
                this.timeType.dateFormat = 'YYYY-MM-DD HH 时';
                this.timeType.mode = 'day';
                this.timeType.timePickerOption = true;
                break;
            case TimeUnits.MINUTE:
                this.timeType.dateFormat = 'YYYY-MM-DD HH:mm';
                this.timeType.mode = 'day';
                this.timeType.timePickerOption = true;
                break;
        }
        const index = this.timeUnits.findIndex(item => {
            return item.value === value;
        });
        // 为了保持顺序 按以下操作
        this.dataTimeUnitsList = this.timeUnits;
        const length = this.timeUnits.length;
        const end = index < length - 1 ? index + 2 : length - 1;
        this._dataTimeUnits =  this.timeUnits.find( item => item.value === value);
        setTimeout(() => {
            this.dataTimeUnitsList = null;
        }, 1);
        setTimeout(() => {
            this.dataTimeUnitsList = this.timeUnits.slice( index, end );
        }, 1);
    }
    public timeType: { dateFormat?: string, mode?: 'month' | 'day', timePickerOption?: boolean }
        = { dateFormat: 'YYYY-MM-DD', mode: 'day', timePickerOption: null };
    get timePeriodUnitName(): String {
        return this.timeUnits.find(item => item.value === this._timePeriodUnitValue).label;
    }
    constructor(
        private sensorsService: SensorsService,
        private areacodeService: AreacodeService,
        private http: _HttpClient,
        private monitorPointService: MonitorPointService,
        private deviceService: DeviceService,
        private dateService: DateService,
        private msg: NzMessageService
    ) {
    }
    private initPage() {
        this.sensorsService.getPagingList(null, null).subscribe(
            (res: PageBean) => {
                this.sensorList = res.data;
            }
        );
        this.timeUnits.push(
            { label: '年', value: TimeUnits.YEAR },
            { label: '月', value: TimeUnits.MONTH },
            { label: '日', value: TimeUnits.DAY },
            { label: '时', value: TimeUnits.HOUR },
            { label: '分', value: TimeUnits.MINUTE }
        );
        this.dataTimeUnitsList = this.timeUnits.slice(2, 4);
        this._dataTimeUnits = this.dataTimeUnitsList[0];
        const now = new Date();
        this.lineChartCriteria.timePeriod.timeUnits = TimeUnits.DAY;
        this.lineChartCriteria.timePeriod.startTime = now;
        this.lineChartCriteria.timePeriod.endTime = new Date(now.getTime());
        // 省市区 初始值
        this.http.get(environment.SERVER_BASH_URL + 'organization/get-my-org').subscribe(
            (res: ResultBean<Organization>) => {
                if (res.code === ResultCode.SUCCESS) {
                    const org = res.data;
                    if (!!org.areaNames) {
                        const areaNames = org.areaNames;
                        this._areas = { label: null, value: null };
                        this._areas.label = Object.values(areaNames).filter(
                            val => !!val
                        ).join('/');
                        if (areaNames.areaName != null) {
                            this._areas.value = org.areaCode;
                            this.dataConditionTemp.areaRange = AreaRange.AREA;
                            this.dataConditionTemp.areaRangeId = org.areaCode;
                        } else if (areaNames.cityName != null) {
                            this._areas.value = org.cityCode;
                            this.dataConditionTemp.areaRange = AreaRange.CITY;
                            this.dataConditionTemp.areaRangeId = org.cityCode;
                        } else {
                            this._areas.value = org.provinceCode;
                            this.dataConditionTemp.areaRange = AreaRange.PROVINCE;
                            this.dataConditionTemp.areaRangeId = org.provinceCode;
                        }
                    } else {
                        this._areas = { label: '江苏省/苏州市/昆山市', value: 320583 };
                        this.dataConditionTemp.areaRange = AreaRange.AREA;
                        this.dataConditionTemp.areaRangeId = 320583;
                    }
                }
            }
        );
        // 监控点初始化
        this.monitorPointsChange(null);
    }
    devicesChange(mpId) {
        if (!!mpId) {
            const example = new ExampleService();
            example.or().andEqualTo({ name: 'monitorPointId', value: mpId });
            this.deviceService.getPageByExample(null, example).subscribe(
                (res: PageBean) => {
                    if (!!res && !!res.data) {
                        this.devices = res.data;
                    }
                }
            );
        } else {
            this.devices = null;
        }
    }
    monitorPointsChange(text) {
     public monitorPointOptions: MonitorPoint[] = [];
     get actualYear(): number {
         return this.actualTime.getFullYear();
     }
     set actualYear(year) {
         this.actualTime.setFullYear(Number(year));
     }
     monitorPointsChange(text?: string) {
        const pageBean: PageBean = { pageIndex: 0, pageSize: 20 };
        const example = new ExampleService();
        let areaName = '';
        switch (this.dataConditionTemp.areaRange) {
            case AreaRange.PROVINCE:
        switch (this._areas.length) {
            case 1:
                areaName = 'provinceCode'; break;
            case AreaRange.CITY:
            case 2:
                areaName = 'cityCode'; break;
            case AreaRange.AREA:
            case 3:
                areaName = 'areaCode'; break;
        }
        if (!!text) {
            example.or().andLike({ name: 'name', value: '%' + text + '%' })
                .andEqualTo({ name: areaName, value: this.dataConditionTemp.areaRangeId });
                .andEqualTo({ name: areaName, value:  Number(this._areas.slice(-1).pop().value) });
        } else {
            example.or()
                .andEqualTo({ name: areaName, value: this.dataConditionTemp.areaRangeId });
                .andEqualTo({ name: areaName, value:  Number(this._areas.slice(-1).pop().value) });
        }
        this.monitorPointService.getPageByExample(pageBean, example).subscribe(
            (res: PageBean) => {
                if (!!res && !!res.data) {
                    this.monitorPoints = res.data;
                    this.monitorPointOptions = res.data;
                }
            }
        );
    }
     devicesChange(text?: string) {
        if (!!this.monitorPoint) {
            const example = new ExampleService();
            if (!!text) {
                example.or().andEqualTo({ name: 'monitorPointId', value: this.monitorPoint.id })
                .andLike({name: 'text', value: text});
            }else {
                example.or().andEqualTo({ name: 'monitorPointId', value: this.monitorPoint.id });
            }
            this.deviceService.getPageByExample(null, example).subscribe(
                (res: PageBean) => {
                    if (!!res && !!res.data) {
                        this.deviceOptions = res.data;
                    }
                }
            );
        } else {
            this.deviceOptions = [];
        }
    }
    /**
     * 报表属性
     */
    public chartLoading: boolean;
    public chartOption;
    public echartsIntance;
    public chartSelectedIndex = 0;
    public onChartInit(e): void {
        this.echartsIntance = e;
    }
    constructor(
    private http: _HttpClient,
    private sensorsService: SensorsService,
    private deviceService: DeviceService,
    private areacodeService: AreacodeService,
    private monitorPointService: MonitorPointService,
    private msg: NzMessageService,
    private dateService: DateService,
    ) { }
    ngOnInit() {
        this.initPage();
    }
    get _isSameDay() {
        return this.lineChartCriteria.timePeriod.startTime && this.lineChartCriteria.timePeriod.endTime && moment(this.lineChartCriteria.timePeriod.startTime).isSame(this.lineChartCriteria.timePeriod.endTime, 'day');
    }
    get _startShowTime() {
        return this.timeType.timePickerOption ?
            {
                nzHideDisabledOptions: true,
                nzDisabledHours: () => {
                    const endTime = this.lineChartCriteria.timePeriod.endTime;
                    const hours = this.newArray(50);
                    return this._isSameDay && !!endTime ? hours.slice(endTime.getHours() + 1, 24) : [];
                },
                nzDisabledMinutes: (h) => {
                    if (this._timePeriodUnitValue === TimeUnits.MINUTE) {
                        const endTime = this.lineChartCriteria.timePeriod.endTime;
                        if (this._isSameDay && h === endTime.getHours()) {
                            const minutes = this.newArray(122);
                            return minutes.slice(endTime.getMinutes() + 1, 60);
                        } else {
                            return [];
    private initPage() {
        this.sensorsService.getPagingList(null, null).subscribe(
            (res: PageBean) => {
                this.sensorOptions.push({id: -1, name: '全部', isExpanded: true, children: res.data});
            }
        );
        this.actualYearOptions = this.newArray(this.actualYear - 9, 10).map(item => Number(item)).reverse();
                // 省市区 初始值
                this.http.get(environment.SERVER_BASH_URL + 'organization/get-my-org').subscribe(
                    (res: ResultBean<Organization>) => {
                        if (res.code === ResultCode.SUCCESS) {
                            const org = res.data;
                            const areas = new Array(3);
                            if (!!org.areaNames) {
                                const areaNames = org.areaNames;
                                Object.keys(areaNames).forEach(
                                    key => {
                                        const value = areaNames[key];
                                        if ( value != null) {
                                            switch (key) {
                                                case 'provinceName' :
                                                areas[0] = {label : value, value: org.provinceCode }; break;
                                                case 'cityName' :
                                                areas[1] = {label : value, value: org.cityCode }; break;
                                                case 'areaName' :
                                                areas[2] = {label : value, value: org.areaCode }; break;
                                            }
                                        }
                                    }
                                );
                            } else {
                                for (let i = 0; i < areas.length; i++) {
                                    switch (i) {
                                        case  0:
                                        areas[0] = {label : '江苏省', value: 320000 }; break;
                                        case  1:
                                        areas[1] = {label : '苏州市', value: 320500 }; break;
                                        case  2:
                                        areas[2] = {label : '昆山市', value: 320583 }; break;
                                    }
                                }
                            }
                            this.setAreasData(areas);
                        }
                    } else {
                        return this.newArray(60).slice(1);
                    }
                },
                nzDisabledSeconds: () => {
                    return this.newArray(60).slice(1);
                }
            } : false;
                );
    }
    get _endShowTime() {
        return this.timeType.timePickerOption ?
            {
                nzHideDisabledOptions: true,
                nzDisabledHours: () => {
                    const startTime = this.lineChartCriteria.timePeriod.startTime;
                    return this._isSameDay && !!startTime ? this.newArray(startTime.getHours()) : [];
                },
                nzDisabledMinutes: (h) => {
                    if (this._timePeriodUnitValue === TimeUnits.MINUTE) {
                        const startTime = this.lineChartCriteria.timePeriod.startTime;
                        if (this._isSameDay && h === startTime.getHours()) {
                            return this.newArray(startTime.getMinutes());
                        } else {
                            return [];
                        }
                    } else {
                        return this.newArray(60).slice(1);
                    }
                },
                nzDisabledSeconds: () => {
                    return this.newArray(60).slice(1);
                }
            } : false;
    }
    newArray = (len) => {
        const result = [];
        for (let i = 0; i < len; i++) {
            result.push(i);
        }
        return result;
    }
    newArray2 = (start, len) => {
        const result = [];
        for (let i = start; i <= len; i++) {
            result.push(i);
        }
        return result;
    }
    _disabledStartDate = (startValue: Date) => {
        if (!startValue || !this.lineChartCriteria.timePeriod.endTime) {
            return false;
        }
        let format = this.timeType.dateFormat;
        // 单位为时,开始日期中 日默认时间设置为 00.00.00
        if (format.indexOf('H', 11)) {
            format = format.replace(/HH.*/, '');
        }
        const _startValue = moment(moment(startValue).format(format), format);
        return _startValue.valueOf() > this.lineChartCriteria.timePeriod.endTime.getTime();
    }
    _disabledEndDate = (endValue: Date) => {
        if (!endValue || !this.lineChartCriteria.timePeriod.startTime) {
            return false;
        }
        const _endValue: Date = new Date(endValue.getTime());
        _endValue.setHours(23);
        _endValue.setMinutes(59);
        _endValue.setSeconds(59);
        return _endValue.getTime() < this.lineChartCriteria.timePeriod.startTime.getTime();
    }
    _timeChange = (value, type?: 'start'|'end') => {
        const startTime = this.lineChartCriteria.timePeriod.startTime;
        const endTime = this.lineChartCriteria.timePeriod.endTime;
        if (type === 'start') {
            this.lineChartCriteria.timePeriod.startTime = value;
            !!endTime ? '' : this.lineChartCriteria.timePeriod.endTime = value;
        } else {
            this.lineChartCriteria.timePeriod.endTime = value;
            !!startTime ? '' : this.lineChartCriteria.timePeriod.startTime === value;
        }
    }
    private getPeriodDate(value: Date , type?: 'start'|'end' ): Date {
        let month = 0;
        let day = 1;
        let hour = 0;
        let minute = 0;
        let second = 0;
        let millisecond = 0;
        if ('end' === type) {
            month = 11;
            day = 31;
            hour = 23;
            minute = 59;
            second = 59;
            millisecond = 999;
        }
        const mo = moment(value);
        switch ( this.lineChartCriteria.timePeriod.timeUnits ) {
            case TimeUnits.YEAR:
            mo.month(month).date(day).hour(hour).minute(minute).second(second).millisecond(millisecond); break;
            case TimeUnits.MONTH:
            mo.date(day).hour(hour).minute(minute).second(second).millisecond(millisecond); break;
            case TimeUnits.DAY:
            mo.hour(hour).minute(minute).second(second).millisecond(millisecond); break;
            case TimeUnits.HOUR:
            mo.minute(minute).second(second).millisecond(millisecond); break;
            case TimeUnits.MINUTE:
            mo.second(second).millisecond(millisecond); break;
        }
        return mo.toDate();
    }
    get startYear(): number {
        !!this.lineChartCriteria.timePeriod.startTime ?
            '' : this.lineChartCriteria.timePeriod.startTime = new Date();
        return this.lineChartCriteria.timePeriod.startTime.getFullYear();
    }
    set startYear(value) {
        !!this.lineChartCriteria.timePeriod.startTime ?
            '' : this.lineChartCriteria.timePeriod.startTime = new Date();
        if (this.startYear === this.endYear && value < this.startYear) {
            // 异步调用防止循环
            setTimeout(() => {
                this.endYear += 1;
            }, 1);
        }
        this.lineChartCriteria.timePeriod.startTime.setFullYear(value);
    }
    get minStartYear(): number {
        const now = new Date();
        return now.getFullYear() - 50;
    }
    get maxStartYear(): number {
        return this.endYear;
    }
    get endYear(): number {
        !!this.lineChartCriteria.timePeriod.endTime ?
            '' : this.lineChartCriteria.timePeriod.endTime = new Date();
        return this.lineChartCriteria.timePeriod.endTime.getFullYear();
    }
    set endYear(value) {
        !!this.lineChartCriteria.timePeriod.endTime ?
            '' : this.lineChartCriteria.timePeriod.endTime = new Date();
        if (this.startYear === this.endYear && value > this.startYear) {
            // 异步调用防止循环
            setTimeout(() => {
                this.startYear -= 1;
            }, 1);
        }
        this.lineChartCriteria.timePeriod.endTime.setFullYear(value);
    }
    get minEndYear(): number {
        return this.startYear;
    }
    get maxEndYear(): number {
        const now = new Date();
        return now.getFullYear() + 50;
    }
    areaLazyLoad(event: { option: CascaderOption, index: number, resolve: (children: CascaderOption[]) => void, reject: () => void }) {
    public areaLazyLoad(event: { option: CascaderOption, index: number, resolve: (children: CascaderOption[]) => void, reject: () => void }) {
        const index = event['index'];
        const option = event.option;
        switch (index) {
@@ -402,140 +236,276 @@
                ); break;
        }
    }
    setAreaCodes(codes: string[]) {
        if (!!codes && !!codes.length) {
            const n = codes.length;
            if (this.dataConditionTemp.areaRangeId !== Number(codes[n - 1])) {
                this.dataConditionTemp.areaRangeId = Number(codes[n - 1]);
                switch (n) {
                    case 1:
                        this.dataConditionTemp.areaRange = AreaRange.PROVINCE;
                        break;
                    case 2:
                        this.dataConditionTemp.areaRange = AreaRange.CITY;
                        break;
                    case 3:
                        this.dataConditionTemp.areaRange = AreaRange.AREA;
                        break;
                }
                this.monitorPointsChange(null);
                this._monitorPoint = null;
                this.devicesChange(null);
                this._device = null;
            }
            this._areas.value = codes;
    // 第一步,省市区 赋值变 并 改变监控点选项
    public  setAreasData(areas: {label: string, value: string}[] ) {
        let isChanged = false;
        isChanged = areas.some( (item , index: number) => {
            // this._areas[index] 为null 改变 监控点选项
            return this._areas.length < areas.length
            || !this._areas[index]
            || this._areas[index].value !== item.value;
        });
        if ( isChanged ) {
            this._areas = areas;
            this.monitorPoint = null;
            this.monitorPointsChange();
        }
    }
    // 下拉框设置监控点事件
    setMonitorPoint(value: MonitorPoint) {
        if (!!value) {
            this.dataConditionTemp.areaRangeId = value.id;
            this.dataConditionTemp.areaRange = AreaRange.MONITORPOINT;
        } else {
            this.setAreaCodes(this._areas.value);
        }
        if (value !== this._monitorPoint) {
            this._device = null;
            this.devicesChange(!!value ? value.id : null);
        }
        this._monitorPoint = value;
    }
    // 设置设备的值
    setDevice(value: Device) {
        if (!!value) {
            this._device = value;
            this.dataConditionTemp.areaRangeId = value.id;
            this.dataConditionTemp.areaRange = AreaRange.DEVICE;
        } else {
            this.setMonitorPoint(this._monitorPoint);
        }
    }
    setDataTimeUnits(item) {
        this._dataTimeUnits = item;
        this.dataConditionTemp.timeUnits = item.value;
        if (!this.actualTimeDisabled) {
        this._actualTime = 1;
        switch (item.value) {
           case TimeUnits.MONTH:
           this.actualTimes = this.newArray2(1, 12); break;
           case TimeUnits.DAY:
           this.actualTimes = this.newArray2(1, 31); break;
           case TimeUnits.HOUR:
           this.actualTimes = this.newArray2(0, 23); break;
           case TimeUnits.MINUTE:
           this.actualTimes = this.newArray2(1, 59); break;
        }
        }
    }
    // 实际时间是否可用 actualTimeDisabled
    get actualTimeDisabled() {
      if (!!this.dataTimeUnitsList && this._dataTimeUnits === this.dataTimeUnitsList[0]) {
            this.setActualTime(null);
            // 实际时间下拉选项数组
            this.actualTimes = null;
         }
         return  !!this.dataTimeUnitsList && this._dataTimeUnits === this.dataTimeUnitsList[0];
    }
    setActualTime(val) {
         this.dataConditionTemp.actualTime = val;
         this._actualTime = val;
    }
    search(event) {
       // 刷新时间格式
       const startTime = this.lineChartCriteria.timePeriod.startTime;
       const endTime = this.lineChartCriteria.timePeriod.endTime;
       this.lineChartCriteria.timePeriod.startTime = this.getPeriodDate(startTime);
       this.lineChartCriteria.timePeriod.endTime = this.getPeriodDate(endTime, 'end');
       this.lineChartCriteria.dataConditions.pop();
       this.lineChartCriteria.dataConditions.push(this.dataConditionTemp);
       this.reloadChart();
    }
      private reloadChart(): void {
        const countTimeRange = this.dateService.countTimeRange(this.lineChartCriteria.timePeriod);
        let timeList: string[];
        const maxTimeRange = 5000;
        if (countTimeRange < maxTimeRange ) {
            timeList = this.dateService.makeTimeList(this.lineChartCriteria.timePeriod);
     // 第二步 设置 监控点, 值变 改变设备选项,值为null 置空设备选项和设备值
     public _monitorPoint: MonitorPoint;
     get monitorPoint(): MonitorPoint {
         return this._monitorPoint;
     }
     set monitorPoint(value) {
        if (!!value) {
              // 值变 改变设备选项
             if (this._monitorPoint !== value) {
                this._monitorPoint = value; // 此处不能提前也不能放后,设备改变要调用
                this.devicesChange();
             }
             // 值为null 置空设备选项和设备值
        } else {
            this.msg.error('时间跨度不能超过' + maxTimeRange + ',当前时间跨度为' + countTimeRange);
             this._monitorPoint = null;
             this.device = null;
             this.deviceOptions = null;
        }
     }
    // 第三步 设置 监控点
    public _device: Device;
    set device(val: Device) {
        this._device = val;
    }
    get device(): Device {
        return this._device;
    }
    /**
     * 获取 传感器名称
     *
     * @readonly
     * @type {string}
     * @memberof QueryComponent
     */
    public onSensorSelect(event): void {
        const data = event.node.data;
        if (data.id === -1 && data.halfChecked === false) {
            if (!!data.checked) {
                this.sensorOptions[0].children.forEach(
                    sensor => {
                        this._sensors [sensor.id] = sensor.sensorKey;
                    }
                );
            } else {
                this._sensors = {};
            }
        }else {
             if (!!data.checked) {
                this._sensors [data.id] = data.sensorKey;
             }else {
                delete this._sensors[data.id];
             }
        }
        this._sensorNames = '';
        this.sensorOptions[0].children.forEach(
            sensor => {
               const hasSensor = Object.keys(this._sensors).some(
                     id => Number(id) === Number(sensor.id)
                );
                if (hasSensor) {
                    this._sensorNames += sensor.name + ',';
                }
            }
        );
    }
    public setTimeUnit(val: {label: string, value: TimeUnits} ) {
        switch (val.value) {
            // YYYY-MM-DD HH:mm:ss
            case TimeUnits.MONTH:
            this._timeType.dateFormat = 'YYYY年';
                // this._timeType.dateFormat = 'YYYY-MM';
                // this._timeType.mode = 'month';
                // this._timeType.endShowTime = null;
                break;
            case TimeUnits.DAY:
                this._timeType.dateFormat = 'YYYY年MM月';
                this._timeType.mode = 'month';
                this._timeType.showTime = false;
                break;
            case TimeUnits.HOUR:
                this._timeType.dateFormat = 'YYYY年MM月DD日';
                this._timeType.mode = 'day';
                this._timeType.showTime = false;
                break;
            case TimeUnits.MINUTE:
                this._timeType.dateFormat = 'YYYY年MM月DD日 HH时';
                this._timeType.mode = 'day';
                this._timeType.showTime = {
                    nzHideDisabledOptions: true,
                    nzDisabledHours: () => {
                        return [];
                    },
                    nzDisabledMinutes: (h) => {
                        return this.newArray(60).slice(1).map(
                            item => Number(item)
                        );
                    },
                    nzDisabledSeconds: () => {
                        return this.newArray(60).slice(1).map(
                            item => Number(item)
                        );
                    }
                };
                break;
        }
    }
   private newArray = (startOrLen: number, len?: number, prefix?: string, suffix?: string) => {
        const result = [];
        const s = !!len ? startOrLen : 0;
        len = !!len ? len : startOrLen;
        suffix = !!suffix ? suffix : '';
        prefix = !!prefix ? prefix :  '';
        for (let i = s; result.length < len; i++) {
            result.push(prefix + i + suffix);
        }
        return result;
    }
    public loadGrid(): void {
        // 数据检查
        const sensors = Object.values(this._sensors);
        if ( sensors.length === 0 ) {
            this.msg.error(' 监测项目 不能为空');
            return ;
        }
       this.grid.loading = true;
       this.sensorNameScrollLeft = '0px';
       this.grid.data = [];
       const start: Date = this.getPeriodDate(this.actualTime , 'start');
       const end: Date = this.getPeriodDate(this.actualTime , 'end');
       this.dataCondition['actualTime'] = null;
       this.dataCondition['timeUnits'] = this.timeUnit.value;
       // 设置表格宽度,要在此处
       this.tableWidth = this.tableWidthOption[this.timeUnit.value];
       // 设置区域值
       const mptValue: number = !!this._monitorPoint ? this._monitorPoint.id : null;
       const devValue: number = !!this._device ? this._device.id : null;
       const areasData = [ devValue, mptValue, Number(this._areas.slice(-1).pop().value)];
       for (let index = 0 ; index < areasData.length ; index++) {
            const item = areasData[index];
            if ( item !== null ) {
                this.dataCondition.areaRangeId = item;
                switch (index) {
                    case 0: this.dataCondition.areaRange = AreaRange.DEVICE; break;
                    case 1: this.dataCondition.areaRange = AreaRange.MONITORPOINT; break;
                    case 2:
                    switch (this._areas.length ) {
                      case 1: this.dataCondition.areaRange = AreaRange.PROVINCE; break;
                      case 2: this.dataCondition.areaRange = AreaRange.CITY; break;
                      case 3: this.dataCondition.areaRange = AreaRange.AREA; break;
                    }
                    break;
                }
                break;
            }
       }
       const dataConditions = [this.dataCondition];
       const lineChartCriteria: LineChartCriteria = {
        sensorKeys: sensors,
        timePeriod: {startTime: start , endTime: end, timeUnits: this.timeUnit.value },
        dataConditions: dataConditions
      };
      const timePeriod = lineChartCriteria.timePeriod;
      switch (timePeriod.timeUnits) {
          case TimeUnits.MONTH:
          this.grid.columns = this.newArray(1, 12, null, '月').map(
               item => {
                   return {text: item};
               }
          ); break;
          case TimeUnits.DAY:
          const mo = moment(lineChartCriteria.timePeriod.startTime);
          const days = mo.endOf('month').date();
          this.grid.columns = this.newArray(1, days, null, '日').map(
               item => {
                   return {text: item};
               }
          ); break;
          case TimeUnits.HOUR:
          this.grid.columns = this.newArray(0, 24, null, '时').map(
            item => {
                return {text: item};
            }
          ); break;
          case TimeUnits.MINUTE:
          this.grid.columns = this.newArray(0, 60, null, '分').map(
            item => {
                return {text: item};
            }
          ); break;
      }
      this.reloadChart();
      this.http.post(environment.SERVER_BASH_URL + '/report/line-chart', lineChartCriteria).subscribe(
        (res: ResultBean<{[key: string]: Array<Array<PairData>>}>) => {
           if (res.code === 1) {
              const data =  res.data;
              if (!!data) {
                const sensorKeys = Object.keys(data);
                // aqi六项置前,其他是有数据项 向前。
                sensorKeys.forEach(
                    key => {
                       const sensor = (<Array<Sensor>>this.sensorOptions[0].children).
                       find(item => {
                           return item.sensorKey === key;
                       });
                       let weight = this.aqiSort[key];
                       weight = !!weight ? weight : 101;
                    //    this.gridSensors.push(sensor);
                       const sensorData = data[key][0].map(
                           pair => {
                                if (weight > 100) {
                                    // pair.value 为null,权重后移
                                    weight = !!pair.value ? weight : weight + 1;
                                }
                                return !!pair.value ? String(Math.round(pair.value)) : '-';
                           }
                       );
                       this.grid.data.push({sensor: sensor, data: sensorData, weight: weight});
                    }
               );
              }
              this.grid.data.sort( (a, b) =>  a.weight - b.weight );
              this.grid.loading = false;
              this.switchSensor(0);
           }
        }
      );
        $('.ant-table-body').scroll(
            () => {
                this.sensorNameScrollLeft =  $('.ant-table-body').scrollLeft() + 'px';
            }
        );
    }
    private reloadChart(): void {
        const  timeList = this.grid.columns.map(item => item.text);
         if (!!this.echartsIntance) {
             this.chartOption = null;
             this.echartsIntance.clear();
         }
         this.initOpton({data: timeList});
        //  let series = null;
        //  if ( this.chartSelectedIndex < this.grid.data.length ) {
        //     series = [{type: 'line', data: this.grid.data[this.chartSelectedIndex]}];
        //  }
         this.initOpton({ xAxis : [{data : timeList}]});
         this.chartLoading = true;
         this.http.post(environment.SERVER_BASH_URL + '/report/line-chart', this.lineChartCriteria).subscribe(
            (res: ResultBean<Array<Array<PairData>>>) => {
               if (res.code === 1) {
                  const series = [];
                  const dataList =  res.data;
                  if (!!dataList && !!dataList.length) {
                    dataList.forEach(
                         data => {
                            const outData =  data.map( item => {
                                return item.value;
                            });
                            series.push({type: 'line', data: outData});
                        }
                    );
                    this.echartsIntance.setOption({
                        series: series
                    });
                    this.chartLoading = false;
                  }
               }
            }
       );
      }
      private initOpton(opt: {data: string[]}) {
          this.chartOption = {
      private initOpton(opt: {[key: string]: object}) {
         const defaultOption = {
            title: {
                text: ''
                left: 'center'
            },
            tooltip : {
                trigger: 'axis',
@@ -563,8 +533,7 @@
            xAxis : [
                {
                    type : 'category',
                    boundaryGap : false,
                    data : opt.data
                    boundaryGap : false
                }
            ],
            yAxis : [
@@ -575,11 +544,85 @@
            series : [
            ]
        };
        $.extend(true, defaultOption, opt);
        this.chartOption = defaultOption;
      }
      chartLoading: boolean;
      chartOption;
      echartsIntance;
      onChartInit(ec) {
        this.echartsIntance = ec;
      }
    public get sensorUnit() {
        return this.grid.data[this.chartSelectedIndex].sensor.unit;
    }
    // 报表标题暂存 防止联动
    public _chartTitleTemp: string;
    public get chartTitle(): string {
        const names = ['辖区', '地区', '时间', '项目'];
        switch ( this.dataCondition.areaRange ) {
            case AreaRange.MONITORPOINT :
            names[0] = '监控点';
            names[1] = this._monitorPoint.name; break;
            case AreaRange.DEVICE :
              names[0] = '设备';
            names[1] = this._device.name; break;
            default :
            names[0] = '';
            names[1] = this._areas.map( item => item.label).join('/');
            break;
        }
        names[2] = moment(this.actualTime).format(this._timeType.dateFormat);
        if ( this.grid.data.length > this.chartSelectedIndex) {
            names[3] = this.grid.data[this.chartSelectedIndex].sensor.name;
        }
        return names.join('  ') + '  报表';
    }
    public switchSensor(index: number): void {
        this.chartSelectedIndex = index;
        this.chartLoading = true;
        this._chartTitleTemp = this.chartTitle;
        setTimeout(() => {
            const series = [{type: 'line', data: this.grid.data[index].data}];
            this.echartsIntance.setOption({
                title: {
                        text: this.chartTitle
                },
                yAxis : [
                    {
                        name : '单位:' + this.sensorUnit
                    }
                ],
                series: series
            });
           this.chartLoading = false;
        }, 600);
    }
    private getPeriodDate(value: Date , type?: 'start'|'end' ): Date {
        let month = 0;
        let day = 1;
        let hour = 0;
        let minute = 0;
        let second = 0;
        let millisecond = 0;
        if ('end' === type) {
            month = 11;
            day = 31;
            hour = 23;
            minute = 59;
            second = 59;
            millisecond = 999;
        }
        const mo = moment(value);
        switch ( this.timeUnit.value ) {
            case TimeUnits.MONTH:
            mo.month(month).date(day).hour(hour).minute(minute).second(second).millisecond(millisecond); break;
            case TimeUnits.DAY:
            mo.date(day).hour(hour).minute(minute).second(second).millisecond(millisecond); break;
            case TimeUnits.HOUR:
            mo.hour(hour).minute(minute).second(second).millisecond(millisecond); break;
            case TimeUnits.MINUTE:
            mo.minute(minute).second(second).millisecond(millisecond); break;
            // case TimeUnits.MINUTE:
            // mo.second(second).millisecond(millisecond); break;
        }
        return mo.toDate();
    }
}