/**
 * 报警记录
 */
import React, { useEffect } from 'react';
import moment from 'moment';
import sumBy from 'lodash/sumBy';
import VMTable from '../../../vm-table';
import { SubTabsLine } from '../../../vm-sub-tabs';
import SubTitle from '../../../vm-sub-title';
import { VMRangePicker } from '../../../vm-filter';
import { secondToFormatTime } from '../../../util';
import { BaseService, AlarmService } from '../../api';
import { useSetState } from 'ahooks';

import level1 from '../../imgs/level1.png';
import level2 from '../../imgs/level2.png';
import level3 from '../../imgs/level3.png';
import level4 from '../../imgs/level4.png';
import level5 from '../../imgs/level5.png';

interface TypeProps {
    id: string;
}

export default function AlarmRecord(props: TypeProps) {
    const { id } = props;
    const [state, setState] = useSetState({
        standardCode: 'all',
        alarmTabs: [{ key: '', label: '全部' }],
        startDate: moment().format('YYYY-MM-DD'),
        endDate: moment().format('YYYY-MM-DD'),
        pagination: {
            current: 1,
            pageSize: 10,
            total: 0,
        },
    });
    const { alarmTabs, pagination, standardCode, startDate, endDate } = state;

    const { alarmTypeRes: alarmTs } = BaseService.useBaseAlarmTypes(
        id,
        `${startDate} 00:00:00`,
        `${endDate} 23:59:59`,
    );
    const { detail } = AlarmService.useAlarmRecord(
        id,
        standardCode === 'all' ? '' : standardCode,
        startDate,
        endDate,
        pagination.current,
    );
    // 格式化报警类型数据
    const formatAlarmType = (dataList: Array<any>) => {
        let list: Array<any> = [];
        let totalCount = 0; // 报警类型总数
        totalCount = sumBy(dataList, function(o: any) {
            return o.count;
        });
        dataList.forEach((ele: any) => {
            const obj = {
                key: ele.standardCode,
                label: `${ele.standardName} (${ele.count})`,
            };
            list.push(obj);
        });
        return { list, totalCount };
    };

    useEffect(() => {
        let arr = [{ key: '', label: '全部' }]; // 报警明细标签
        if (alarmTs.length > 0) {
            const { list, totalCount } = formatAlarmType(alarmTs);
            arr[0].label = `全部 (${totalCount})`;
            setState({
                alarmTabs: arr.concat(list),
            });
        }
    }, [alarmTs]);

    const getLevel = (text: number) => {
        let src = '',
            color = '#1FEFA9',
            name = '';
        switch (text) {
            case 1:
                src = level1;
                name = '一';
                color = '#FF6A65';
                break;
            case 2:
                src = level2;
                name = '二';
                color = '#FFBD1E';
                break;
            case 3:
                src = level3;
                name = '三';
                color = '#E86CFF';
                break;
            case 4:
                src = level4;
                name = '四';
                color = '#00A8FF';
                break;
            case 5:
                src = level5;
                name = '五';
                color = '#1FEFA9';
                break;
            default:
                src = level1;
                name = '一';
                color = '#FF6A65';
                break;
        }
        return { src, name: `等级${name}`, color };
    };

    const columns = [
        {
            title: '监测指标',
            dataIndex: 'standardName',
            key: 'standardName',
            ellipsis: true,
        },
        {
            title: '报警名称',
            dataIndex: 'name',
            key: 'name',
            ellipsis: true,
        },
        {
            title: '报警等级',
            dataIndex: 'level',
            key: 'level',
            render: (text: number) => {
                const { src, name, color } = getLevel(text);
                return (
                    <span className="alarmLevel" style={{ color }}>
                        <img src={src} />
                        {name}
                    </span>
                );
            },
        },
        {
            title: '报警开始时间',
            dataIndex: 'startDate',
            key: 'startDate',
        },
        {
            title: '报警结束时间',
            dataIndex: 'endDate',
            key: 'endDate',
        },
        {
            title: '报警时长',
            dataIndex: 'endDate',
            key: 'endDate',
            width: 80,
            render: (text: string, record: any) => {
                return (
                    record?.startDate &&
                    text &&
                    secondToFormatTime(moment(text).diff(moment(record.startDate)) / 1000)
                );
            },
        },
    ];

    const pageChange = (page: number) => {
        setState({
            pagination: {
                ...pagination,
                current: page,
            },
        });
    };

    const tableProps = {
        pagination: {
            ...pagination,
            total: detail.total,
            defaultPageSize: 10,
            onChange: pageChange,
        },
        height: 160,
        dataSource: detail.dataSource,
    };

    const handleDateChange = (start: string, end: string) => {
        setState({
            startDate: start,
            endDate: end,
        });
    };

    return (
        <div className="alarm-record">
            <div className="alarm-record-head">
                <SubTitle title="报警记录" />
                <VMRangePicker
                    value={[moment(startDate), moment(endDate)]}
                    onChange={(dates: any) =>
                        dates &&
                        handleDateChange(
                            moment(dates[0]).format('YYYY-MM-DD'),
                            moment(dates[1]).format('YYYY-MM-DD'),
                        )
                    }
                />
            </div>
            <SubTabsLine
                items={alarmTabs}
                activeKey={standardCode}
                onChange={key => {
                    setState({
                        standardCode: key,
                    });
                }}
            />
            <div className="alarm-record-table">
                <VMTable columns={columns} {...tableProps} />
            </div>
        </div>
    );
}
