import { useSetState } from 'ahooks';
import moment from 'moment';
import sumBy from 'lodash/sumBy';
import React, { useEffect } from 'react';
import { secondToFormatTime } from '../../../util';
import { VMRangePicker } from '../../../vm-filter';
import SubTitle from '../../../vm-sub-title';
import VMTable from '../../../vm-table';
import { BaseService } from '../../api';
import AlarmType from './AlarmType';
import BaseInner from './BaseInner';
import './index.less';
import Situation from './Situation';

interface BaseInfoProps {
    id: string;
}

const BaseInfo = (props: BaseInfoProps) => {
    const { id } = props;
    // console.warn(1)
    const nowDate = moment().format('YYYY-MM-DD');
    const [state, setState] = useSetState({
        standardCode: '',
        startDate: nowDate,
        endDate: nowDate,
        alarmTabs: [{ key: '', name: '全部', value: 0 }],
        alarmTabsValue: [{}],
        totalCount: 0,
        pagination: {
            current: 1,
            pageSize: 10,
            total: 0,
        },
    });
    const {
        standardCode,
        startDate,
        endDate,
        alarmTabs,
        alarmTabsValue,
        totalCount,
        pagination,
    } = state;

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

    const { baseInfo, photos, situationRes } = BaseService.useBaseInfo(id, nowDate, nowDate);
    const { alarmTypeRes } = BaseService.useBaseAlarmInfo(
        id,
        moment(nowDate)
            .startOf('M')
            .format('YYYY-MM-DD'),
        moment(nowDate).format('YYYY-MM-DD'),
    );
    const { alarmTypeRes: alarmTs } = BaseService.useBaseAlarmTypes(
        id,
        `${startDate} 00:00:00`,
        `${endDate} 23:59:59`,
    );

    // 格式化报警类型数据
    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,
                name: ele.standardName,
                value: ele.count,
            };
            list.push(obj);
        });
        return { list, totalCount };
    };

    useEffect(() => {
        if (alarmTypeRes.length > 0) {
            const { list, totalCount } = formatAlarmType(alarmTypeRes);
            setState({
                alarmTabsValue: list,
                totalCount,
            });
        }
    }, [alarmTypeRes]);

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

    const { detail } = BaseService.useAlarmDetails(
        id,
        standardCode,
        startDate,
        endDate,
        pagination.current,
        pagination.pageSize,
    );
    const columns = [
        {
            title: '监测指标',
            dataIndex: 'standardName',
            key: 'standardName',
            width: 80,
            ellipsis: true,
        },
        {
            title: '报警名称',
            dataIndex: 'name',
            key: 'name',
            width: 80,
            ellipsis: true,
        },
        {
            title: '报警等级',
            dataIndex: 'level',
            key: 'level',
        },
        {
            title: '报警开始时间',
            dataIndex: 'startDate',
            key: 'startDate',
            width: 120,
        },
        {
            title: '报警结束时间',
            dataIndex: 'endDate',
            key: 'endDate',
            width: 120,
        },
        {
            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,
    };
    return (
        <div className="wr-baseContent">
            <div className="base-top">
                <BaseInner photos={photos} baseInfo={baseInfo} />

                <AlarmType data={alarmTabsValue} total={totalCount} />
            </div>
            <div className="base-bottom">
                <Situation situationRes={situationRes} />
                <div className="base-bottom-alarm-detail">
                    <div className="base-bottom-alarm-detail-date">
                        <SubTitle title="报警明细" />
                        <VMRangePicker
                            value={[moment(startDate), moment(endDate)]}
                            size="small"
                            onChange={(dates: any) =>
                                dates &&
                                handleDateChange(
                                    moment(dates[0]).format('YYYY-MM-DD'),
                                    moment(dates[1]).format('YYYY-MM-DD'),
                                )
                            }
                            // style={{ position: 'absolute', top: 24, right: 32 }}
                        />
                    </div>
                    <div className="base-bottom-alarm-detail-tab">
                        {alarmTabs.map((item: any) => (
                            <div
                                key={item.key}
                                className={`base-bottom-alarm-detail-tab-item ${standardCode ===
                                    item.key && 'base-bottom-alarm-detail-tab-item_active'}`}
                                onClick={() => {
                                    setState({
                                        standardCode: item.key,
                                    });
                                }}
                            >{`${item.name} (${item.value})`}</div>
                        ))}
                    </div>
                    <VMTable columns={columns} {...tableProps} />
                </div>
            </div>
        </div>
    );
};

export default BaseInfo;
