'use client';
import { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import { AgGridReact } from 'ag-grid-react';
import { ColDef, ColGroupDef } from 'ag-grid-community';
import { api } from '@nice/client';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';
import { areaOptions } from '@web/src/app/main/staffinformation/area-options';
import type { CascaderProps } from 'antd/es/cascader';
import { SetFilterModule } from '@ag-grid-enterprise/set-filter';
import { zhCN } from 'ag-grid-community/dist/ag-grid-community';

// 修改函数类型定义

function getAreaName(codes: string[], level?: number): string {
    const result: string[] = [];
    let currentLevel: CascaderProps['options'] = areaOptions;
    
    for (const code of codes) {
        const found = currentLevel?.find(opt => opt.value === code);
        if (!found) break;

        result.push(String(found.label));
        currentLevel = found.children || [];
        if (level && result.length >= level) break; // 添加层级控制
    }
    

    return level ? result[level - 1] || '' : result.join(' / ') || codes.join('/');
}
// 自定义下拉过滤器组件
// interface ICustomFilterProps {
//     column: {
//         getColId: () => string;
//     };
//     api: {
//         forEachNode: (callback: (node: any) => void) => void;
//     };
//     filterChangedCallback?: () => void;  // 设置为可选属性
// }

// const CustomDropdownFilter = forwardRef((props: ICustomFilterProps, ref) => {
//     const [selectedValue, setSelectedValue] = useState<string>('');
//     const [uniqueValues, setUniqueValues] = useState<string[]>([]);

//     useEffect(() => {
//         const colId = props.column.getColId();
//         const values = new Set<string>();
        
//         props.api.forEachNode(node => {
//             const value = node.data[colId];
//             if (value != null) {
//                 values.add(String(value));
//             }
//         });

//         setUniqueValues(Array.from(values).sort());
//     }, [props.api, props.column]);

//     useImperativeHandle(ref, () => ({
//         isFilterActive: () => !!selectedValue,
//         doesFilterPass: (params: any) => {
//             const value = String(params.data[props.column.getColId()] || '');
//             // 精确匹配选中的值
//             return value === selectedValue;
//         },
//         getModel: () => {
//             return selectedValue ? { value: selectedValue } : null;
//         },
//         setModel: (model: any) => {
//             setSelectedValue(model?.value || '');
//         }
//     }));

//     const handleChange = (value: string) => {
//         setSelectedValue(value);
//         // 立即触发过滤器更新
//         if (props.filterChangedCallback) {
//             props.filterChangedCallback();
//         }
//     };

//     return (
//         <div style={{ padding: '4px', width: '100%' }}>
//             <Select
//                 value={selectedValue}
//                 onChange={handleChange}
//                 style={{ width: '100%' }}
//                 size="small"
//                 placeholder="选择筛选..."
//                 allowClear
//                 options={uniqueValues.map(value => ({
//                     value: value,
//                     label: value
//                 }))}
//                 onClear={() => handleChange('')}
//             />
//         </div>
//     );
// });

export default function StaffTable() {
    const { data: staffs, isLoading } = api.staff.findMany.useQuery({
        where: { deletedAt: null },
    });

    const columnDefs: (ColDef | ColGroupDef)[] = [
        { 
            field: 'username', 
            headerName: '姓名', 
            minWidth: 120, 
            pinned: 'left',
            // floatingFilter: true  // 确保启用浮动过滤器
        },
        {
            headerName: '个人基本信息',
            children: [
                { 
                    field: 'idNumber', 
                    headerName: '身份证号', 
                    minWidth: 180,
                },
                { 
                    field: 'type', 
                    headerName: '人员类型', 
                    minWidth: 120,
                },
                { field: 'officerId', headerName: '警号', minWidth: 120 },
                { field: 'phoneNumber', headerName: '手机号', minWidth: 130 },
                { field: 'age', headerName: '年龄', minWidth: 80 },
                { field: 'sex', headerName: '性别', minWidth: 80,
                  cellRenderer: (params: any) => params.value ? '男' : '女' },
                { field: 'bloodType', headerName: '血型', minWidth: 80 },
                { 
                    field: 'birthplace', 
                    headerName: '籍贯', 
                    minWidth: 200,
                    valueFormatter: (params) => params.value ? getAreaName(params.value.split('/')) : '',
                },
                { field: 'source', headerName: '来源', minWidth: 120 },
            ]
        },
        {
            headerName: '政治信息',
            children: [
                { field: 'politicalStatus', headerName: '政治面貌', minWidth: 150 },
                { field: 'partyPosition', headerName: '党内职务', minWidth: 120 }
            ]
        },
        {
            headerName: '职务信息',
            children: [
                {field: 'deptId', headerName: '所属部门', minWidth: 200 },
                { field: 'rank', headerName: '衔职级别', minWidth: 120 },
                { field: 'rankDate', headerName: '衔职时间', minWidth: 120,
                  valueFormatter: (params: any) => params.value ? new Date(params.value).toLocaleDateString() : '' },
                { field: 'proxyPosition', headerName: '代理职务', minWidth: 120 }
            ]
        },
        {
            headerName: '入职信息',
            children: [
                { field: 'hireDate', headerName: '入职时间', minWidth: 120,
                  valueFormatter: (params: any) => params.value ? new Date(params.value).toLocaleDateString() : '' },
                { field: 'seniority', headerName: '工龄认定时间', minWidth: 140,
                  valueFormatter: (params: any) => params.value ? new Date(params.value).toLocaleDateString() : '' },
                { field: 'sourceType', headerName: '来源类型', minWidth: 120 },
                { field: 'isReentry', headerName: '是否二次入职', minWidth: 120,
                  cellRenderer: (params: any) => params.value ? '是' : '否' },
                { field: 'isExtended', headerName: '是否延期服役', minWidth: 120,
                  cellRenderer: (params: any) => params.value ? '是' : '否' },
                { field: 'currentPositionDate', headerName: '现岗位开始时间', minWidth: 140,
                  valueFormatter: (params: any) => params.value ? new Date(params.value).toLocaleDateString() : '' }
            ]
        },
        {
            headerName: '教育背景',
            children: [
                { field: 'education', headerName: '学历', minWidth: 100 },
                { field: 'educationType', headerName: '学历形式', minWidth: 120 },
                { field: 'isGraduated', headerName: '是否毕业', minWidth: 100,
                  cellRenderer: (params: any) => params.value ? '是' : '否' },
                { field: 'major', headerName: '专业', minWidth: 150 },
                { field: 'foreignLang', headerName: '外语能力', minWidth: 120 }
            ]
        },
        {
            headerName: '培训信息',
            children: [
                { field: 'trainType', headerName: '培训类型', minWidth: 120 },
                { field: 'trainInstitute', headerName: '培训机构', minWidth: 150 },
                { field: 'trainMajor', headerName: '培训专业', minWidth: 150 },
                { field: 'hasTrain', headerName: '是否参加培训', minWidth: 120,
                  cellRenderer: (params: any) => params.value ? '是' : '否' }
            ]
        },
        {
            headerName: '鉴定信息',
            children: [
                { field: 'certRank', headerName: '鉴定等级', minWidth: 120 },
                { field: 'certWork', headerName: '鉴定工种', minWidth: 120 },
                { field: 'hasCert', headerName: '是否参加鉴定', minWidth: 120,
                  cellRenderer: (params: any) => params.value ? '是' : '否' }
            ]
        },
        {
            headerName: '工作信息',
            children: [
                { 
                    field: 'equipment', 
                    headerName: '操作维护装备',
                    minWidth: 150,
                    cellRenderer: (params: any) => (
                        <div 
                            style={{ lineHeight: '24px' }}
                            dangerouslySetInnerHTML={{ __html: params.value?.replace(/,/g, '<br/>') || '' }}
                        />
                    ),
                    autoHeight: true
                },
                { 
                    field: 'projects', 
                    headerName: '演训任务经历',
                    minWidth: 150,
                    cellRenderer: (params: any) => (
                        <div 
                            style={{ lineHeight: '24px' }}
                            dangerouslySetInnerHTML={{ __html: params.value?.replace(/,/g, '<br/>') || '' }}
                        />
                    ),
                    autoHeight: true
                },
                // 修改剩余两个字段的cellRenderer为相同结构
                { 
                    field: 'awards', 
                    headerName: '奖励信息',
                    minWidth: 150,
                    cellRenderer: (params: any) => (
                        <div 
                            style={{ lineHeight: '24px' }}
                            dangerouslySetInnerHTML={{ __html: params.value?.replace(/,/g, '<br/>') || '' }}
                        />
                    ),
                    autoHeight: true
                },
                { 
                    field: 'punishments', 
                    headerName: '处分信息',
                    minWidth: 150,
                    cellRenderer: (params: any) => (
                        <div 
                            style={{ lineHeight: '24px' }}
                            dangerouslySetInnerHTML={{ __html: params.value?.replace(/,/g, '<br/>') || '' }}
                        />
                    ),
                    autoHeight: true
                }
            ]
        }
    ];

    
    const defaultColDef: ColDef = {
        sortable: true,
        filter: 'agSetColumnFilter',
        // floatingFilter: true,
        resizable: false,
        flex: 1,
        minWidth: 150,
        maxWidth: 600,
        suppressMovable: true,
        cellStyle: { 
            whiteSpace: 'normal',
            overflowWrap: 'break-word'
        },
        tooltipValueGetter: (params: any) => params.value,
        wrapText: true,
        autoHeight: true
    };

    return (
        <div className="ag-theme-alpine w-full h-[calc(100vh-100px)]"
            style={{
                width: '100%',
                borderRadius: '12px',
                overflow: 'hidden',
                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)'
            }}
        >
            {isLoading ? (
                <div className="h-full flex items-center justify-center">
                    <div className="text-gray-600 text-xl">加载中...</div>
                </div>
            ) : (
                <AgGridReact
                    modules={[SetFilterModule]}
                    rowData={staffs}
                    columnDefs={columnDefs}
                    defaultColDef={{
                        ...defaultColDef,
                        filterParams: {
                            textCustomComparator: (_, value) => value !== '',
                        }
                    }}
                    localeText={zhCN} // 注入中文语言包
                    enableCellTextSelection={true}
                    pagination={true}
                    paginationAutoPageSize={true}
                    cacheQuickFilter={true}
                />
            )}
        </div>
    );
}