/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2025-01-07 14:30:00
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-08-14 15:54:33
 * @FilePath: /KC-MiddlePlatform/src/pages/certificateMana/components/AddCertificateModal.tsx
 * @Description: 新增证书弹窗组件
 */

import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, DatePicker, Upload, Button, Select, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { getDoctorListForSelect, addCertificate, editCertificate } from '../service';
import { debounce } from 'lodash';
import { useModel } from '@umijs/max';
import moment from 'moment';

const { TextArea } = Input;
const { RangePicker } = DatePicker;

interface AddCertificateModalProps {
    visible: boolean;
    onCancel: () => void;
    onSuccess: () => void;
    currentDeptCode?: string; // 当前选中的科室代码
    editData?: any; // 编辑数据
}

interface DoctorOption {
    id: string;
    name: string;
    account: string;
}

const AddCertificateModal: React.FC<AddCertificateModalProps> = ({
    visible,
    onCancel,
    onSuccess,
    currentDeptCode,
    editData
}) => {
    const { initialState } = useModel('@@initialState');
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [doctorOptions, setDoctorOptions] = useState<DoctorOption[]>([]);
    const [doctorLoading, setDoctorLoading] = useState(false);
    const [fileList, setFileList] = useState<any[]>([]);

    // 加载医生列表
    const loadDoctors = async (searchValue: string = '') => {
        if (!currentDeptCode) {
            setDoctorOptions([]);
            return;
        }

        setDoctorLoading(true);
        try {
            const params = {
                deptCode: currentDeptCode,
                userName: searchValue, // 修正：使用userName作为搜索关键字
                current: 1,
                pageSize: 50 // 限制返回数量
            };

            const response = await getDoctorListForSelect(params);
            
            const doctors = response?.list || response?.data || [];
            
            // 转换为下拉选项格式
            const options: DoctorOption[] = doctors.map((doctor: any) => ({
                id: doctor.userInfo?.id || doctor.id || doctor.userId,
                name: doctor.userInfo?.name || doctor.name || doctor.doctorName,
                account: doctor.userInfo?.account || doctor.account || doctor.doctorCode || doctor.workNo
            }));

            setDoctorOptions(options);
        } catch (error) {
            console.error('获取医生列表失败:', error);
            message.error('获取医生列表失败');
        } finally {
            setDoctorLoading(false);
        }
    };

    // 防抖搜索医生，增加延迟减少请求频率
    const searchDoctors = debounce(loadDoctors, 500);

    // 处理医生搜索
    const handleDoctorSearch = (value: string) => {
        searchDoctors(value);
    };

    // 当弹窗打开时自动加载医生列表
    useEffect(() => {
        if (visible && currentDeptCode) {
            loadDoctors(); // 初始加载，不传搜索关键词
        } else if (!visible) {
            // 弹窗关闭时清空选项和表单
            setDoctorOptions([]);
            form.resetFields();
        }
    }, [visible, currentDeptCode]);

    // 当编辑数据变化时，设置表单初始值
    useEffect(() => {
        if (visible && editData) {
            const initialValues = getInitialValues();
            form.setFieldsValue(initialValues);
            
            // 设置文件列表
            const files = [{
                uid: editData.id,
                name: editData.fileName,
                url: editData.url,
                status: 'done'
            }];
            setFileList(files);
            
            // 为医生选择设置对应的选项（如果编辑数据中包含医生信息）
            if (editData.empNameAndCode) {
                // 从 empNameAndCode 解析医生姓名和工号
                // 格式可能是 "姓名(工号)" 或其他格式
                const match = editData.empNameAndCode.match(/^(.+)\((.+)\)$/);
                if (match) {
                    const [, name, account] = match;
                    setDoctorOptions([{
                        id: editData.userId,
                        name: name.trim(),
                        account: account.trim()
                    }]);
                }
            }
        } else if (!visible) {
            // 弹窗关闭时清空文件列表
            setFileList([]);
        }
    }, [visible, editData]);

    // 处理表单提交
    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            setLoading(true);

            // 检查文件上传
            const { doctorId, validityPeriod, attachmentDescription } = values;
            if (!fileList || fileList.length === 0) {
                message.error('请上传证书附件');
                return;
            }

            // 处理日期范围 - 按照个人中心的格式处理
            // validityPeriod是moment对象数组，需要转换为字符串数组
            let dateRange = undefined;
            if (validityPeriod && validityPeriod.length === 2) {
                dateRange = [
                    validityPeriod[0].format('YYYY-MM-DD'),
                    validityPeriod[1].format('YYYY-MM-DD')
                ];
            }
            
            // 按照个人中心的数据格式组织参数
            let submitData;
            const file = fileList[0];
            
            if (file.response) {
                // 新上传的文件，有response
                const response = file.response;
                
                // 检查上传是否成功
                if (response.code && response.code !== 0 && response.code !== 200) {
                    message.error(response.msg || '文件上传失败！');
                    return;
                }
                
                if (!response.data || !response.data.downUrl) {
                    message.error('文件上传返回数据异常，缺少下载地址！');
                    return;
                }
                
                const { downUrl } = response.data;
                const { name } = file;
                submitData = {
                    id: editData ? editData.id : null, // 编辑时使用原有id，新增时为null
                    userId: doctorId,
                    fileName: name,
                    url: downUrl,
                    description: attachmentDescription || '',
                    activeDate: dateRange ? dateRange[0] : undefined,
                    expireDate: dateRange ? dateRange[1] : undefined,
                };
            } else {
                // 已有文件（编辑时的情况）
                const { name, url } = file;
                submitData = {
                    id: editData ? editData.id : null, // 编辑时使用原有id，新增时为null
                    userId: doctorId,
                    fileName: name,
                    url: url,
                    description: attachmentDescription || '',
                    activeDate: dateRange ? dateRange[0] : undefined,
                    expireDate: dateRange ? dateRange[1] : undefined,
                };
            }

            // 根据是否是编辑模式调用不同的接口
            const resp = editData 
                ? await editCertificate(submitData)
                : await addCertificate(submitData);
            
            if (resp) {
                message.success(editData ? '修改证书成功！' : '新增证书成功！');
                form.resetFields();
                setDoctorOptions([]);
                onSuccess();
            } else {
                message.error('保存失败：接口返回空响应');
            }
        } catch (error) {
            console.error(editData ? '修改证书失败:' : '新增证书失败:', error);
            message.error(editData ? '修改证书失败，请重试' : '新增证书失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    // 处理取消
    const handleCancel = () => {
        form.resetFields();
        setDoctorOptions([]);
        setFileList([]);
        onCancel();
    };

    // 文件上传属性（参考个人中心的上传配置）
    const uploadProps = {
        name: 'file',
        action: '/gateway/centerSys/api/upload',
        maxCount: 1,
        fileList: fileList,
        headers: {
            token: initialState?.userData?.token as string
        },
        onChange: (info: any) => {
            const { status, response } = info.file;
            // 更新文件列表状态
            setFileList(info.fileList);
            
            if (status === 'done') {
                // 如果后端返回 code==500，表示上传失败，msg 为错误提示
                if (response && response.code === 500) {
                    message.error(response.msg || `${info.file.name} 文件上传失败。`);
                } else {
                    // 上传成功提示
                    message.success(`${info.file.name} 文件上传成功。`);
                }
            } else if (status === 'error') {
                // 上传失败提示
                message.error(`${info.file.name} 文件上传失败。`);
            }
        }
    };

    // 构造表单初始值
    const getInitialValues = () => {
        if (!editData) return {};
        
        // 构造日期范围
        let validityPeriod = undefined;
        if (editData.activeDate && editData.expireDate) {
            validityPeriod = [
                moment(editData.activeDate),
                moment(editData.expireDate)
            ];
        }
        
        return {
            doctorId: editData.userId,
            validityPeriod,
            attachmentDescription: editData.description
        };
    };

    return (
        <Modal
            title={editData ? "修改" : "新增"}
            open={visible}
            onCancel={handleCancel}
            footer={[
                <Button key="cancel" onClick={handleCancel}>
                    取消
                </Button>,
                <Button key="submit" type="primary" loading={loading} onClick={handleSubmit}>
                    {editData ? "保存" : "上传"}
                </Button>
            ]}
            width={352}
            destroyOnClose
        >
            <Form
                form={form}
                layout="vertical"
                requiredMark={false}
                initialValues={getInitialValues()}
            >
                <Form.Item
                    label={<span><span style={{ color: 'red' }}>*</span>医生：</span>}
                    name="doctorId"
                    rules={[{ required: true, message: '请选择医生' }]}
                >
                    <Select
                        showSearch
                        placeholder="请选择"
                        notFoundContent={doctorLoading ? '搜索中...' : '暂无数据'}
                        loading={doctorLoading}
                        filterOption={false}
                        onSearch={handleDoctorSearch}
                        onDropdownVisibleChange={(open) => {
                            // 当下拉框打开且还没有数据时，也尝试加载一次
                            if (open && doctorOptions.length === 0 && currentDeptCode) {
                                loadDoctors();
                            }
                        }}
                        onClear={() => setDoctorOptions([])}
                        allowClear
                    >
                        {doctorOptions.map(doctor => (
                            <Select.Option key={doctor.id} value={doctor.id}>
                                {doctor.name}({doctor.account})
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>

                <Form.Item
                    label={<span><span style={{ color: 'red' }}>*</span>上传证书附件：</span>}
                >
                    <Upload {...uploadProps}>
                        <Button icon={<UploadOutlined />}>点击上传</Button>
                    </Upload>
                </Form.Item>

                <Form.Item
                    label="有效期限："
                    name="validityPeriod"
                >
                    <RangePicker
                        style={{ width: '100%' }}
                        placeholder={['开始日期', '结束日期']}
                        format="YYYY-MM-DD"
                    />
                </Form.Item>

                <Form.Item
                    label="附件说明："
                    name="attachmentDescription"
                >
                    <TextArea
                        placeholder="请输入"
                        rows={4}
                    />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default AddCertificateModal;
