import React, { useState, useEffect, useRef, useMemo, useLayoutEffect } from 'react';
import * as echarts from 'echarts';
import styles from './CustomerInfoManagement.less';
import { Select, Space, Button, Input } from 'antd';
import { PlusOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import StandardTable from '@/components/StandardTable';
import topIcon from '@/assets/business_basic/top_icon1.svg';
import topIcon2 from '@/assets/business_basic/top_icon2.svg';
import topIcon3 from '@/assets/business_basic/top_icon3.svg';
import topIcon4 from '@/assets/business_basic/top_icon4.svg';
import CustomerInfoManagementDetail from './CustomerInfoManagementDetail';
const CustomerInfoManagement = () => {
    const [searchKeyword, setSearchKeyword] = useState('');
    const [selectedRows, setSelectedRows] = useState([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    // 列表筛选与数据（演示数据，可替换为接口）
    const [filters, setFilters] = useState({
        customerType: '',
        customerGrade: '',
        cooperationStatus: '',
    });
    // 新增：详情页面切换状态
    const [showDetail, setShowDetail] = useState(false);
    const [detailData, setDetailData] = useState(null);
    const [prevScrollY, setPrevScrollY] = useState(0);

    // 图表引用
    const customerTypeChartRef = useRef(null);
    const customerValueChartRef = useRef(null);
    const customerTypeChartInstance = useRef(null);
    const customerValueChartInstance = useRef(null);

    // KPI数据
    const kpiData = {
        totalCustomers: 389,
        highValueCustomers: 180,
        inCooperation: 360,
        newThisMonth: 8,
    };

    // 客户类型分布图表配置
    const customerTypeChartOption = {
        // title: {
        //     text: '客户类型分布',
        //     left: 'left',
        //     textStyle: {
        //         fontSize: 16,
        //         fontWeight: 600,
        //         color: '#333',
        //     },
        // },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow',
            },
            backgroundColor: 'rgba(255,255,255,0.95)',
            borderColor: '#e0e0e0',
            borderWidth: 1,
            textStyle: { color: '#333' },
        },
        grid: {
            top: 16,
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
        },
        xAxis: {
            type: 'category',
            data: ['客户', '供应商', '第3周', '第4周'],
            axisLabel: {
                rotate: 0,
                color: '#4E5856',
            },
            axisLine: {
                lineStyle: { color: '#C9E3DE' },
            },
            axisTick: { show: false },
        },
        yAxis: {
            type: 'value',
            max: 100,
            axisLine: { show: false },
            axisTick: { show: false },
            axisLabel: { color: '#4E5856' },
            splitLine: {
                show: true,
                lineStyle: { color: '#E9F3F1', type: 'dashed' },
            },
        },
        series: [
            {
                name: '数量',
                type: 'bar',
                data: [56, 32, 85, 15],
                barWidth: 26,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#7FC8B6' },
                        { offset: 1, color: '#008F8E' },
                    ]),
                    // barBorderRadius: [6, 6, 0, 0],
                    shadowColor: 'rgba(0,0,0,0.08)',
                    shadowBlur: 6,
                    shadowOffsetY: 2,
                },
                label: {
                    show: true,
                    position: 'top',
                    color: '#4E5856',
                },
            },
        ],
    };

    // 客户价值分布环形图配置
    const customerValueChartOption = {
        // title: {
        //     text: '客户价值分布',
        //     left: 'left',
        //     textStyle: {
        //         fontSize: 16,
        //         fontWeight: 600,
        //     },
        // },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        legend: {
            orient: 'vertical',
            right: '6%',
            top: '32%',
            itemWidth: 16,
            itemHeight: 4,
            itemGap: 16,
            textStyle: {
                fontSize: 12,
                color: '#666',
                fontWeight: 'normal'
            }
        },
        series: [
            {
                name: '客户价值',
                type: 'pie',
                radius: ['40%', '65%'],
                center: ['30%', '50%'],
                // avoidLabelOverlap: false,
                itemStyle: {
                    // borderRadius: 10,
                    // borderColor: '#fff',
                    // borderWidth: 2,
                },
                label: {
                    show: false,
                },
                // emphasis: {
                //     label: {
                //         show: true,
                //         fontSize: 16,
                //         fontWeight: 'bold',
                //     },
                // },
                data: [
                    { value: 180, name: '高价值客户', itemStyle: { color: '#5CB3FF' } },
                    { value: 120, name: '中等客户', itemStyle: { color: '#FFDE73' } },
                    { value: 89, name: '小客户', itemStyle: { color: '#A990EA' } },
                ],
            },
        ],
    };

    // 图表初始化与销毁：根据详情模式切换，返回列表后重新初始化
    useEffect(() => {
        if (!showDetail) {
            if (customerTypeChartRef.current) {
                customerTypeChartInstance.current = echarts.init(customerTypeChartRef.current);
                customerTypeChartInstance.current.setOption(customerTypeChartOption);
                // 额外一次 resize，确保初始化后尺寸正确
                requestAnimationFrame(() => {
                    customerTypeChartInstance.current?.resize();
                });
            }
            if (customerValueChartRef.current) {
                customerValueChartInstance.current = echarts.init(customerValueChartRef.current);
                customerValueChartInstance.current.setOption(customerValueChartOption);
                // 额外一次 resize，确保初始化后尺寸正确
                requestAnimationFrame(() => {
                    customerValueChartInstance.current?.resize();
                });
            }

            const handleResize = () => {
                customerTypeChartInstance.current?.resize();
                customerValueChartInstance.current?.resize();
            };
            window.addEventListener('resize', handleResize);

            return () => {
                window.removeEventListener('resize', handleResize);
                customerTypeChartInstance.current?.dispose();
                customerTypeChartInstance.current = null;
                customerValueChartInstance.current?.dispose();
                customerValueChartInstance.current = null;
            };
        } else {
            // 进入详情时，释放实例以避免无容器绑定
            customerTypeChartInstance.current?.dispose();
            customerTypeChartInstance.current = null;
            customerValueChartInstance.current?.dispose();
            customerValueChartInstance.current = null;
        }
    }, [showDetail]);

    // 返回列表时恢复滚动位置，确保布局稳定后再滚动
    useLayoutEffect(() => {
        if (!showDetail) {
            // 等待本帧布局完成
            requestAnimationFrame(() => {
                window.scrollTo(0, prevScrollY || 0);
            });
        }
    }, [showDetail]);

    // 最近活动数据
    const recentActivities = [
        {
            id: 1,
            title: '新合同签署',
            description: '与中石化华东分公司签署年度供应合同',
            time: '2小时前',
        },
        {
            id: 2,
            title: '订单完成',
            description: '完成海南石油贸易有限公司的油品配送',
            time: '昨天',
        },
        {
            id: 3,
            title: '客户反馈',
            description: '收到华南能源集团的满意度调查回复',
            time: '昨天',
        },
        {
            id: 4,
            title: '新客户注册',
            description: '新客户"浙江能源有限公司"完成注册',
            time: '3天前',
        },
    ];

    // 表格数据
    const tableData = [
        {
            id: 'CUST-2023-001',
            customerName: '中国石化销售股份有限公司',
            contact: '钱亚男',
            phone: '18901563341',
            classification: '高价值',
            monthlyAmount: 1250000,
            cooperationStatus: '合作中',
            satisfaction: 4.5,
        },
        {
            id: 'CUST-2023-002',
            customerName: '中石化华东分公司',
            contact: '郑宇雅',
            phone: '15341731282',
            classification: '常规客户',
            monthlyAmount: 1250000,
            cooperationStatus: '合作中',
            satisfaction: 4.0,
        },
        {
            id: 'CUST-2023-003',
            customerName: '海南石油贸易有限公司',
            contact: '孙向明',
            phone: '13252257033',
            classification: '高价值',
            monthlyAmount: 850000,
            cooperationStatus: '合作中',
            satisfaction: 4.5,
        },
        {
            id: 'CUST-2023-004',
            customerName: '东莞石化有限公司',
            contact: '何思颖',
            phone: '18931788771',
            classification: '高价值',
            monthlyAmount: 980000,
            cooperationStatus: '合作中',
            satisfaction: 4.5,
        },
        {
            id: 'CUST-2023-005',
            customerName: '中国石油化工集团有限公司',
            contact: '钱佳仪',
            phone: '13743378254',
            classification: '常规客户',
            monthlyAmount: 980000,
            cooperationStatus: '暂停合作',
            satisfaction: 4.0,
        },
    ];

    // 列配置（用于 StandardTable）
    const columns = useMemo(() => {
        return [
            { title: '客户名称', dataIndex: 'customerName', key: 'customerName', width: 220 },
            { title: '联系人', dataIndex: 'contact', key: 'contact', width: 120 },
            { title: '联系电话', dataIndex: 'phone', key: 'phone', width: 140 },
            {
                title: '分类', dataIndex: 'classification', key: 'classification', width: 110,
                render: (val) => (
                    <span className={`${styles.tag} ${val === '高价值' ? styles.tagGold : styles.tagBlue}`}>{val}</span>
                )
            },
            {
                title: '交易额度(月)', dataIndex: 'monthlyAmount', key: 'monthlyAmount', width: 150,
                render: (v) => `¥${Number(v).toLocaleString()}`
            },
            {
                title: '合作状态', dataIndex: 'cooperationStatus', key: 'cooperationStatus', width: 110,
                render: (val) => (
                    <span className={`${styles.tag} ${val === '合作中' ? styles.tagGreen : styles.tagOrange}`}>{val}</span>
                )
            },
            {
                title: '满意度', dataIndex: 'satisfaction', key: 'satisfaction', width: 120,
            },
            {
                title: '操作', key: 'action', fixed: 'right', width: 200,
                render: (_, row) => (
                    <Space size={12}>
                        <Button type="link" size="small" className="viewDetailBtn" onClick={() => {
                            setPrevScrollY(window.pageYOffset || document.documentElement.scrollTop || 0);
                            setDetailData(row);
                            setShowDetail(true);
                        }}>查看详情</Button>
                        <Button type="link" size="small" className="editBtn">修改</Button>
                        <Button type="link" size="small" danger className="deleteBtn">删除</Button>
                    </Space>
                )
            },
        ];
    }, []);

    // 处理选择
    const handleSelectRow = (id) => {
        if (selectedRows.includes(id)) {
            setSelectedRows(selectedRows.filter(rowId => rowId !== id));
        } else {
            setSelectedRows([...selectedRows, id]);
        }
    };

    // 处理全选
    const handleSelectAll = () => {
        if (selectedRows.length === tableData.length) {
            setSelectedRows([]);
        } else {
            setSelectedRows(tableData.map(item => item.id));
        }
    };

    // 渲染星级评分
    const renderStars = (rating) => {
        const stars = [];
        const fullStars = Math.floor(rating);
        const hasHalfStar = rating % 1 !== 0;

        for (let i = 0; i < fullStars; i++) {
            stars.push(<span key={i} className={styles.starFull}>★</span>);
        }
        if (hasHalfStar) {
            stars.push(<span key="half" className={styles.starHalf}>★</span>);
        }
        const emptyStars = 5 - Math.ceil(rating);
        for (let i = 0; i < emptyStars; i++) {
            stars.push(<span key={`empty-${i}`} className={styles.starEmpty}>★</span>);
        }
        return stars;
    };

    // 计算总页数
    const totalPages = Math.ceil(85 / pageSize);
    // 当进入详情模式时，直接渲染详情页并提供返回按钮
    if (showDetail) {
        return (
            <div className={styles.container}>
                <div style={{ marginBottom: 10 }}>
                    <button
                        className={styles.backBtn}
                        onClick={() => {
                            setShowDetail(false);
                            // 恢复滚动位置
                            setTimeout(() => {
                                window.scrollTo(0, prevScrollY);
                            }, 0);
                        }}
                        style={{ padding: '6px 12px', border: '1px solid #d9d9d9', borderRadius: 6, background: '#fff', fontSize: 12, cursor: 'pointer' }}
                    >
                        ← 返回列表
                    </button>
                </div>
                <CustomerInfoManagementDetail data={detailData} />
            </div>
        );
    }

    return (
        <div className={styles.container}>
            <div className={styles.mainCard}>
                {/* KPI卡片区域 */}
                <div className={styles.kpiGrid}>
                    <div className={styles.kpiCard}>
                        <div className={styles.kpiText}>
                            <div className={styles.kpiValue}>{kpiData.totalCustomers}</div>
                            <div className={styles.kpiTitle}>总客户数</div>
                        </div>
                        <img src={topIcon} alt="icon" className={styles.kpiIconImg} />
                    </div>
                    <div className={styles.kpiCard}>
                        <div className={styles.kpiText}>
                            <div className={styles.kpiValue}>{kpiData.highValueCustomers}</div>
                            <div className={styles.kpiTitle}>高价值客户</div>
                        </div>
                        <img src={topIcon2} alt="icon" className={styles.kpiIconImg} />
                    </div>
                    <div className={styles.kpiCard}>
                        <div className={styles.kpiText}>
                            <div className={styles.kpiValue}>{kpiData.inCooperation}</div>
                            <div className={styles.kpiTitle}>合作中</div>
                        </div>
                        <img src={topIcon3} alt="icon" className={styles.kpiIconImg} />
                    </div>
                    <div className={styles.kpiCard}>
                        <div className={styles.kpiText}>
                            <div className={styles.kpiValue}>{kpiData.newThisMonth}</div>
                            <div className={styles.kpiTitle}>本月新增</div>
                        </div>
                        <img src={topIcon4} alt="icon" className={styles.kpiIconImg} />
                    </div>
                </div>

                {/* 图表和活动区域 */}
                <div className={styles.chartRow}>
                    {/* 客户类型分布图表 */}
                    <div className={styles.chartCard} style={{ flex: 9 }}>
                        <div className={styles.chartHeader}>
                            <div className={styles.chartTitle}>客户类型分布</div>
                            <Select
                                size="small"
                                className={styles.timeSelect}
                                defaultValue="全部时间"
                                options={[
                                    { value: '全部时间', label: '全部时间' },
                                    { value: '本月', label: '本月' },
                                    { value: '本季度', label: '本季度' },
                                    { value: '本年', label: '本年' },
                                ]}
                                onChange={(v) => {/* 可根据需要触发筛选 */ }}
                            />
                        </div>
                        <div
                            ref={customerTypeChartRef}
                            className={styles.chartContainer}
                        />
                    </div>

                    {/* 客户价值分布图表 */}
                    <div className={styles.chartCard} style={{ flex: 6 }}>
                        <div className={styles.chartHeader}>
                            <div className={styles.chartTitle}>客户价值分布</div>
                        </div>
                        <div
                            ref={customerValueChartRef}
                            className={styles.chartContainer}
                        />
                    </div>

                    {/* 最近活动列表 */}
                    <div className={styles.activityCard} style={{ flex: 9 }}>
                        <div className={styles.chartHeader}>
                            <div className={styles.chartTitle}>最近活动</div>
                        </div>
                        <div className={styles.activityGrid}>
                            {recentActivities.map((activity) => (
                                <div key={activity.id} className={styles.activityCardItem}>
                                    <div className={styles.activityCardHeader}>
                                        <div className={styles.activityCardTitle}>{activity.title}</div>
                                        <div className={styles.activityCardTime}>{activity.time}</div>
                                    </div>
                                    <div className={styles.activityCardDesc}>{activity.description}</div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>

                {/* 客户列表区域 */}
                <div className={styles.bottomSection}>
                    <div className={styles.sectionHeader}>
                        <span className={styles.sectionBar} />
                        <span className={styles.sectionTitle}>客户列表</span>
                    </div>
                    <div className={styles.filterContent}>
                        <div className={styles.filterItem}>
                            <Input.Search
                                placeholder="搜索关键词"
                                allowClear
                                value={searchKeyword}
                                onChange={(e) => setSearchKeyword(e.target.value)}
                                onSearch={(val) => setSearchKeyword(val)}
                                style={{ minWidth: 150 }}
                            />
                        </div>
                        <div className={styles.filterItem}>
                            <span className={styles.filterLabel}>客户类型:</span>
                            <Select
                                value={filters.customerType}
                                onChange={(v) => setFilters({ ...filters, customerType: v })}
                                placeholder="全部"
                                options={[
                                    { label: '全部', value: '' },
                                ]}
                                allowClear
                            />
                        </div>
                        <div className={styles.filterItem}>
                            <span className={styles.filterLabel}>客户等级:</span>
                            <Select
                                value={filters.customerGrade}
                                onChange={(v) => setFilters({ ...filters, customerGrade: v })}
                                placeholder="全部"
                                options={[
                                    { label: '全部', value: '' },
                                ]}
                                allowClear
                            />
                        </div>
                        <div className={styles.filterItem}>
                            <span className={styles.filterLabel}>合作状态:</span>
                            <Select
                                value={filters.cooperationStatus}
                                onChange={(v) => setFilters({ ...filters, cooperationStatus: v })}
                                placeholder="全部"
                                options={[
                                    { label: '全部', value: '' },
                                ]}
                                allowClear
                            />
                        </div>
                        <Space className={styles.filterButtons}>
                            <Button
                                type="primary"
                                icon={<SearchOutlined />}
                                className={styles.queryBtn}
                            >
                                查询
                            </Button>
                            <Button
                                icon={<ReloadOutlined />}
                                className={styles.resetBtn}
                            >
                                重置
                            </Button>
                        </Space>
                        <Space className={styles.filterButtonsRight}>
                            <Button
                                type="primary"
                                icon={<PlusOutlined />}
                                className={styles.addBtn}
                            >
                                新增客户
                            </Button>
                            <Button
                                // icon={<ExportOutlined />}
                                className={styles.exportBtn}
                            >
                                批量导出
                            </Button>
                        </Space>
                    </div>
                    <div className={styles.tableWrapper}>
                        <StandardTable
                            rowKey="id"
                            columns={columns}
                            data={{
                                list: tableData,
                                pagination: {
                                    total: tableData.length,
                                    pageSize,
                                    current: currentPage,
                                    showTotal: (total) => `共 ${total} 条`,
                                },
                            }}
                            selectionType="checkbox"
                            selectedRowKeys={selectedRows}
                            onSelectRow={(row) => handleSelectRow(row.id)}
                            onSelectAll={(checked) => checked ? setSelectedRows(tableData.map(i => i.id)) : setSelectedRows([])}
                            onChangePage={(page) => setCurrentPage(page)}
                            onChangePageSize={(size) => { setPageSize(size); setCurrentPage(1); }}
                        />
                    </div>
                </div>
            </div>
        </div>
    );
};

export default CustomerInfoManagement;
