import React, { useState, useMemo, useLayoutEffect } from 'react';
import styles from './BusinessPlanManagement.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';
const BusinessPlanManagement = () => {
    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);


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


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


    // 表格数据
    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]);
        }
    };

    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.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 BusinessPlanManagement;
