import React, { useMemo, useState } from 'react';
import { Select, Tree } from 'antd';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts';
import { ReactComponent as Icon1 } from '@/assets/business_basic/icon1.svg';
import { ReactComponent as Icon2 } from '@/assets/business_basic/icon2.svg';
import styles from './HistoryTrend.less';

const buildingOptions = [
    { label: '工厂建筑', value: 'plant' },
    { label: '仓储设施', value: 'warehouse' },
];

const factoryOptions = [
    { label: '全部工厂', value: 'all' },
    { label: '上海油库', value: 'shanghai' },
    { label: '南京油库', value: 'nanjing' },
];

const rangeOptions = [
    { label: '近24小时', value: '24h' },
    { label: '近7天', value: '7d' },
    { label: '近30天', value: '30d' },
];

const rawTreeData = [
    {
        title: '上海油库',
        key: 'shanghai',
        tag: { label: '工厂', type: 'depot' },
        children: [
            {
                title: '汽油罐区',
                key: 'gasoline-area',
                tag: { label: '罐区', type: 'area' },
                children: [
                    {
                        title: '汽油调合罐组',
                        key: 'blend-group',
                        tag: { label: '罐组', type: 'group' },
                        children: [
                            {
                                title: 'T-101 汽油储罐',
                                key: 't101',
                                tag: { label: '储罐', type: 'tank' },
                                children: [
                                    {
                                        title: 'LT-101 液位变送器',
                                        key: 'lt101',
                                        tag: { label: '测点', type: 'sensor' },
                                    },
                                    {
                                        title: 'TT-101 温度变送器',
                                        key: 'tt101',
                                        tag: { label: '测点', type: 'sensor' },
                                    },
                                    {
                                        title: 'PT-101 压力变送器',
                                        key: 'pt101',
                                        tag: { label: '测点', type: 'sensor' },
                                    },
                                    {
                                        title: 'P-101A 输送泵',
                                        key: 'p101a',
                                        tag: { label: '设备', type: 'device' },
                                    },
                                    {
                                        title: 'P-101B 输送泵',
                                        key: 'p101b',
                                        tag: { label: '设备', type: 'device' },
                                    },
                                    {
                                        title: 'SP-101 密度计',
                                        key: 'sp101',
                                        tag: { label: '测点', type: 'sensor' },
                                    },
                                ],
                            },
                            {
                                title: 'T-102 汽油储罐',
                                key: 't102',
                                tag: { label: '储罐', type: 'tank' },
                            },
                            {
                                title: 'T-103 汽油储罐',
                                key: 't103',
                                tag: { label: '储罐', type: 'tank' },
                            },
                        ],
                    },
                ],
            },
            {
                title: '柴油罐区',
                key: 'diesel-area',
                tag: { label: '罐区', type: 'area' },
            },
            {
                title: '化危品库',
                key: 'hazard',
                tag: { label: '库区', type: 'depot' },
            },
        ],
    },
];

const TreeNodeTitle = ({ text, tag }) => (
    <span className={styles.treeNodeTitle}>
        <span className={styles.nodeText}>{text}</span>
        {tag ? (
            <span className={`${styles.nodeTag} ${styles[`tag-${tag.type}`] || ''}`}>
                {tag.label}
            </span>
        ) : null}
    </span>
);

const formatTreeNodes = data =>
    data.map(item => ({
        key: item.key,
        title: <TreeNodeTitle text={item.title} tag={item.tag} />,
        children: item.children ? formatTreeNodes(item.children) : undefined,
    }));

const timeAxis = ['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00'];

const liquidLevelSeries = [79, 18, 76, 45, 36, 69, 43, 74, 48, 53, 55, 21];
const temperatureSeries = [32.2, 31.1, 32.0, 30.6, 30.9, 32.1, 30.7, 32.8, 30.8, 31.7, 31.1, 30.6];
const pressureSeries = [0.116, 0.114, 0.113, 0.112, 0.114, 0.113, 0.116, 0.115, 0.111, 0.114, 0.115, 0.114];

const HistoryTrend = () => {
    const [buildingType, setBuildingType] = useState('plant');
    const [factory, setFactory] = useState('all');
    const [selectedKeys, setSelectedKeys] = useState(['t101']);
    const [checkedKeys, setCheckedKeys] = useState(['t101']);
    const [levelRange, setLevelRange] = useState('24h');
    const [tempRange, setTempRange] = useState('24h');

    const treeData = useMemo(() => formatTreeNodes(rawTreeData), []);

    const levelTrendOption = useMemo(() => {
        const areaGradient = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(45, 158, 157, 0.35)' },
            { offset: 1, color: 'rgba(45, 158, 157, 0.02)' },
        ]);

        return {
            color: ['#2d9e9d'],
            tooltip: {
                trigger: 'axis',
                backgroundColor: '#0f3030',
                borderColor: 'rgba(45, 158, 157, 0.4)',
                textStyle: { color: '#dff4f2' },
                axisPointer: {
                    lineStyle: {
                        color: '#2d9e9d',
                    },
                },
            },
            legend: {
                data: ['液位 (%)'],
                left: 'center',
                top: 10,
                textStyle: { color: '#4e5856' },
            },
            grid: { left: 40, right: 20, top: 50, bottom: 30 },
            xAxis: {
                type: 'category',
                data: timeAxis,
                boundaryGap: false,
                axisTick: { show: false },
                axisLine: { lineStyle: { color: '#d6e5df' } },
                axisLabel: { color: '#76807d' },
            },
            yAxis: {
                type: 'value',
                min: 0,
                max: 100,
                axisLabel: { formatter: '{value}%', color: '#76807d' },
                splitLine: { lineStyle: { color: '#e6f1ec' } },
            },
            series: [
                {
                    name: '液位 (%)',
                    type: 'line',
                    symbol: 'circle',
                    symbolSize: 6,
                    lineStyle: { width: 1 },
                    itemStyle: { color: "#fff", borderColor: '#2d9e9d', borderWidth: 1 },
                    lineStyle: { color: '#2d9e9d' },
                    areaStyle: { color: areaGradient },
                    data: liquidLevelSeries,
                },
            ],
        };
    }, []);

    const temperaturePressureOption = useMemo(
        () => ({
            color: ['#2a7b8d', '#c2b453'],
            tooltip: {
                trigger: 'axis',
                backgroundColor: '#0f3030',
                borderColor: 'rgba(42, 123, 141, 0.4)',
                textStyle: { color: '#dff4f2' },
                axisPointer: { type: 'cross', link: [{ xAxisIndex: 'all' }] },
            },
            legend: {
                data: [
                    '温度 (℃)',
                    '压力 (MPa)',
                ],
                left: 'center',
                top: 10,
                textStyle: { color: '#4e5856' },
            },
            grid: { left: 50, right: 50, top: 50, bottom: 30 },
            xAxis: [
                {
                    type: 'category',
                    data: timeAxis,
                    boundaryGap: false,
                    axisTick: { show: false },
                    axisLine: { lineStyle: { color: '#d6e5df' } },
                    axisLabel: { color: '#76807d' },
                },
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '温度 (℃)',
                    min: 28,
                    max: 33,
                    axisLabel: { formatter: '{value}', color: '#76807d' },
                    nameTextStyle: { color: '#76807d' },
                    splitLine: { lineStyle: { color: '#e6f1ec' } },
                },
                {
                    type: 'value',
                    name: '压力 (MPa)',
                    min: 0.11,
                    max: 0.12,
                    position: 'right',
                    axisLabel: { formatter: '{value}', color: '#76807d' },
                    nameTextStyle: { color: '#76807d' },
                    splitLine: { show: false },
                },
            ],
            series: [
                {
                    name: '温度 (℃)',
                    type: 'line',
                    // smooth: true,
                    symbol: 'circle',
                    symbolSize: 6,
                    itemStyle: { color: '#fff', borderColor: "#2a7b8d", borderWidth: 1 },
                    lineStyle: { width: 2, color: '#2a7b8d' },
                    data: temperatureSeries,
                },
                {
                    name: '压力 (MPa)',
                    type: 'line',
                    // smooth: true,
                     symbol: 'circle',
                    symbolSize: 6,
                    lineStyle: { width: 2, color: '#c2b453' },
                    itemStyle: { color: '#fff', borderColor: "#c2b453", borderWidth: 1 },
                    yAxisIndex: 1,
                    data: pressureSeries,
                },
            ],
        }),
        [],
    );

    return (
        <div className={styles.container}>
            <section className={styles.leftPanel}>
                <div className={styles.blockHeader}>
                    <span className={styles.titleIcon} />
                    <span className={styles.blockTitle}>工厂层级结构</span>
                </div>
                <div className={styles.filters}>
                    <Select
                        value={buildingType}
                        onChange={setBuildingType}
                        options={buildingOptions}
                        className={styles.filterSelect}
                        dropdownMatchSelectWidth={false}
                        size="small"
                    />
                    <Select
                        value={factory}
                        onChange={setFactory}
                        options={factoryOptions}
                        className={styles.filterSelect}
                        dropdownMatchSelectWidth={false}
                        size="small"
                    />
                </div>
                <div className={styles.treeWrapper}>
                    <Tree
                        showIcon={false}
                        showLine={{ showLeafIcon: false }}
                        defaultExpandAll
                        checkable
                        selectable
                        treeData={treeData}
                        checkedKeys={checkedKeys}
                        selectedKeys={selectedKeys}
                        onCheck={keys => setCheckedKeys(keys.checked || keys)}
                        onSelect={keys => setSelectedKeys(keys)}
                        className={styles.tree}
                        virtual={false}
                        switcherIcon={nodeProps =>
                            nodeProps.expanded ? (
                                <Icon2 width={14} height={14} />
                            ) : (
                                <Icon1 width={14} height={14} />
                            )
                        }
                    />
                </div>
            </section>

            <section className={styles.rightPanel}>
                <div className={styles.trendCard}>
                    <div className={styles.trendHeader}>
                        <div className={styles.headerTitle}>
                            <span className={styles.titleIcon} />
                            <span className={styles.blockTitle}>液位历史趋势</span>
                        </div>
                        <Select
                            value={levelRange}
                            onChange={setLevelRange}
                            options={rangeOptions}
                            className={styles.rangeSelect}
                            dropdownMatchSelectWidth={false}
                            size="small"
                        />
                    </div>
                    <div className={styles.chartWrapper}>
                        <ReactECharts option={levelTrendOption} style={{ height: '260px' }} notMerge lazyUpdate />
                    </div>
                </div>

                <div className={styles.trendCard}>
                    <div className={styles.trendHeader}>
                        <div className={styles.headerTitle}>
                            <span className={styles.titleIcon} />
                            <span className={styles.blockTitle}>温度与压力趋势</span>
                        </div>
                        <Select
                            value={tempRange}
                            onChange={setTempRange}
                            options={rangeOptions}
                            className={styles.rangeSelect}
                            dropdownMatchSelectWidth={false}
                            size="small"
                        />
                    </div>
                    <div className={styles.chartWrapper}>
                        <ReactECharts
                            option={temperaturePressureOption}
                            style={{ height: '260px' }}
                            notMerge
                            lazyUpdate
                        />
                    </div>
                </div>
            </section>
        </div>
    );
};

export default HistoryTrend;

