/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-12-11 11:21:13
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-08-04 18:05:34
 * @FilePath: /MediResourceManaSys/src/pages/qualificationMana/qualificationBatchAuth/DoctorSelection/index.tsx
 * @Description: 从外部传入医生数据，并对外提供选中项的完整数据
 */

import React, { useState, useMemo, useEffect, ChangeEvent } from 'react';
import './style.less';
import { ProFormCheckbox, ProFormText } from '@ant-design/pro-components';

interface Doctor {
    account: string;
    name: string;
    id: string;
    deptName: string;
}

interface DoctorSelectionProps {
    doctorsData: Doctor[];
    // 当选中项变化时的回调，返回完整的选中医生数组
    onSelectedChange?: (selectedDoctors: Doctor[]) => void;
    // 新增属性，用于从外部控制清空当前已选中的医生。当此属性从false变为true时清空选择
    clearSelection?: boolean;
}

const DoctorSelection: React.FC<DoctorSelectionProps> = ({ doctorsData = [], onSelectedChange, clearSelection }) => {
    const [searchText, setSearchText] = useState('');
    const [selectedIds, setSelectedIds] = useState<string[]>([]);

    const filteredDoctors = useMemo(() => {
        const query = searchText.trim().toLowerCase();
        return doctorsData.filter(d =>
            d.name.toLowerCase().includes(query) ||
            `${d.id}`.toLowerCase().includes(query) ||
            d.deptName.toLowerCase().includes(query)
        );
    }, [searchText, doctorsData]);

    const handleCheck = (code: string) => {
        setSelectedIds(prev => {
            if (prev.includes(code)) {
                return prev.filter(item => item !== code);
            } else {
                return [...prev, code];
            }
        });
    };

    const isChecked = (code: string) => selectedIds.includes(code);

    const handleSearchChange = (e: ChangeEvent<HTMLInputElement>) => {
        setSearchText(e.target.value);
    };

    // 当 clearSelection 从父组件传入为 true 时清空所有选择
    useEffect(() => {
        if (clearSelection === true) {
            setSelectedIds([]);
        }
    }, [clearSelection]);

    // 当 selectedIds 变化时，通过 selectedIds 匹配对应的医生完整数据，将选中数据传递给 onSelectedChange 回调
    useEffect(() => {
        const selectedDoctors = doctorsData.filter(d => selectedIds.includes(d.id));
        onSelectedChange?.(selectedDoctors);
    }, [selectedIds, doctorsData, onSelectedChange]);

    return (
        <div className="doctor-selection-container">
            <div className="doctor-selection-header">选择医生</div>
            <div className='doctor-selection-filter'>
                <ProFormText 
                    noStyle 
                    placeholder="姓名, 工号, 科室" 
                    fieldProps={{
                        value: searchText,
                        onChange: handleSearchChange,
                    }} 
                />
            </div>

            <div className="doctor-selection-list">
                {filteredDoctors.map((d, index) => (
                    <div
                        key={index}
                        className={`doctor-selection-item ${isChecked(d.id) ? 'selected' : ''}`}
                    >
                        <img 
                            src={require('./images/renyuantubiao_yellow.png')} 
                            alt="avatar" 
                            className="doctor-selection-avatar" 
                        />
                        <div className="doctor-selection-info">
                            <div className="doctor-selection-name">{d.name}</div>
                            <div className="doctor-selection-subinfo">{d.account} | {d.deptName}</div>
                        </div>
                        <ProFormCheckbox  
                            className="doctor-selection-checkbox" 
                            noStyle 
                            fieldProps={{
                                checked: isChecked(d.id),
                                onChange: () => handleCheck(d.id)
                            }} 
                        />
                    </div>
                ))}
            </div>
        </div>
    );
};

export default DoctorSelection;
