/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2025-08-06 10:12:30
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-08-14 17:59:20
 * @FilePath: /MediResourceManaSys/src/pages/certificateMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-12-25 16:00:00
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-08-06 10:28:55
 * @FilePath: /KC-MiddlePlatform/src/pages/certificateMana/index.tsx
 * @Description: 证书管理页面
 */

import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import { KCIMLeftList } from '@/components/KCIMLeftList';
import { createFromIconfontCN } from '@ant-design/icons';
import { ActionType, ProFormDatePicker, ProFormText } from '@ant-design/pro-components';
import { ProColumns } from '@ant-design/pro-table';
import { Button, Input, message, Modal, Popconfirm, Space } from 'antd';
import { Fragment, Key, useEffect, useRef, useState } from 'react';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { getCertificateList, getDepartmentList, deleteCertificate, getDoctorAttachmentList } from './service';
import AddCertificateModal from './components/AddCertificateModal';
import './style.less';

const IconFont = createFromIconfontCN({
    scriptUrl: '',
});

export default function CertificateMana() {
    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const [certificateSearchKeywords, set_certificateSearchKeywords] = useState<string>('');
    const [departmentData, set_departmentData] = useState<any[]>([]);
    const [currentSelectedDepartment, set_currentSelectedDepartment] = useState<any | undefined>(undefined);
    const [selectedRowKeys, set_selectedRowKeys] = useState<Key[]>([]);
    const [selectedRows, set_selectedRows] = useState<any[]>([]);
    const [addModalVisible, set_addModalVisible] = useState<boolean>(false);
    const [editModalVisible, set_editModalVisible] = useState<boolean>(false);
    const [currentEditRecord, set_currentEditRecord] = useState<any>(undefined);

    const tableRef = useRef<ActionType>();

    // 表格列定义
    const columns: ProColumns[] = [
        {
            title: '证书',
            dataIndex: 'fileName',
            width: 150,
            ellipsis: true,
        },
        {
            title: '医生',
            dataIndex: 'empNameAndCode',
            width: 160,
            ellipsis: true,
        },
        {
            title: '有效期限',
            dataIndex: 'validityPeriod',
            width: 280,
            ellipsis: true,
            renderText: (text, record) => {
                // 检查是否有有效的日期数据
                if (record.activeDate && record.expireDate) {
                    return `${record.activeDate} 至 ${record.expireDate}`;
                }
                return '暂未设置';
            },
        },
        {
            title: '附件说明',
            dataIndex: 'description',
            ellipsis: true,
        },
        {
            title: '操作',
            key: 'option',
            width: 150,
            fixed: 'right',
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <a key="download" onClick={() => handleDownload(record)}>
                        下载
                    </a>,
                    <a key="edit" onClick={() => handleEdit(record)}>
                        修改
                    </a>,
                    <Popconfirm
                        key="delete"
                        title="确定要删除这条证书记录吗？"
                        onConfirm={() => handleDelete(record)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <a>删除</a>
                    </Popconfirm>
                ];
            },
        },
    ];

    // 获取表格数据（对接后端真实接口 listAllDoctorAttachments）
    const getTableData = async (params: any) => {
        const { departmentCode, doctorName, fileName, expirationDate, current = 1, pageSize = 10 } = params || {};

        // 将选择的日期作为 expireDate 传入
        let expireDate: string | undefined = undefined;
        if (expirationDate) {
            // 兼容 moment/dayjs 字符串
            expireDate = typeof expirationDate === 'string' ? expirationDate : (expirationDate?.format ? expirationDate.format('YYYY-MM-DD') : expirationDate?.toString());
        }

        const query = {
            doctorName: tableDataSearchKeywords || doctorName,
            attachmentName: certificateSearchKeywords || fileName,
            deptCode: (currentSelectedDepartment?.code || departmentCode),
            expireDate,
            current, // 使用ProTable传递的current参数
            pageSize, // 使用ProTable传递的pageSize参数
        } as any;

        const resp = await getDoctorAttachmentList(query);

        // 根据实际接口返回结构处理
        if (Array.isArray(resp)) {
            return {
                data: resp,
                success: true,
                total: resp.length,
            };
        }

        // 处理 { status, msg, data: { list, totalCount, ... } } 结构
        const data = resp?.data || resp;
        const list = data?.list || [];
        const total = data?.totalCount || data?.total || 0;

        return {
            data: list,
            success: true,
            total,
        };
    };

    // 获取科室列表（对齐医生授权管理返回结构）
    const getDepartmentListData = async () => {
        const resp = await getDepartmentList();
        // 后端直接返回树数组；兼容历史 { success, data } 包装
        const data = Array.isArray(resp) ? resp : (resp?.data || resp?.list || []);
        if (Array.isArray(data)) {
            set_departmentData(data);
        } else {
            set_departmentData([]);
        }
    };

    // 处理下载
    const handleDownload = async (record: any) => {
        try {
            if (!record.url) {
                message.error('文件下载地址不存在！');
                return;
            }
            
            // 使用fetch获取文件数据，强制下载
            const response = await fetch(record.url);
            if (!response.ok) {
                throw new Error('文件下载失败');
            }
            
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            
            // 创建下载链接
            const link = document.createElement('a');
            link.href = url;
            link.download = record.fileName || '证书文件';
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 清理对象URL
            window.URL.revokeObjectURL(url);
            
            message.success('下载成功！');
        } catch (error) {
            console.error('下载失败:', error);
            message.error('下载失败！');
        }
    };

    // 处理编辑
    const handleEdit = (record: any) => {
        set_currentEditRecord(record);
        set_editModalVisible(true);
    };

    // 处理删除
    const handleDelete = async (record: any) => {
        try {
            await deleteCertificate(record.id);
            message.success('删除成功！');
            tableRef.current?.reload();
        } catch (error) {
            message.error('删除失败！');
        }
    };

    // 处理新增
    const handleAdd = () => {
        if (!currentSelectedDepartment?.code) {
            message.warning('请先选择科室');
            return;
        }
        set_addModalVisible(true);
    };

    // 处理新增成功
    const handleAddSuccess = () => {
        set_addModalVisible(false);
        tableRef.current?.reload();
        message.success('新增证书成功！');
    };

    // 处理新增取消
    const handleAddCancel = () => {
        set_addModalVisible(false);
    };

    // 处理编辑成功
    const handleEditSuccess = () => {
        set_editModalVisible(false);
        set_currentEditRecord(undefined);
        tableRef.current?.reload();
        message.success('修改证书成功！');
    };

    // 处理编辑取消
    const handleEditCancel = () => {
        set_editModalVisible(false);
        set_currentEditRecord(undefined);
    };

    // 处理批量删除
    const handleBatchDelete = () => {
        if (selectedRows.length === 0) {
            message.warning('请先选择要删除的证书');
            return;
        }
        
        const modal = Modal.confirm({
            title: '确认批量删除',
            content: `确定要删除选中的 ${selectedRows.length} 个证书吗？此操作不可恢复。`,
            okText: '确定删除',
            cancelText: '取消',
            onOk: async () => {
                try {
                    // 并发删除所有选中的证书
                    const deletePromises = selectedRows.map(record => 
                        deleteCertificate(record.id)
                    );
                    
                    await Promise.all(deletePromises);
                    
                    message.success(`成功删除 ${selectedRows.length} 个证书！`);
                    
                    // 清空选择并刷新表格
                    set_selectedRowKeys([]);
                    set_selectedRows([]);
                    tableRef.current?.reload();
                } catch (error) {
                    console.error('批量删除失败:', error);
                    message.error('批量删除失败，请重试');
                }
            }
        });
    };

    // 取消批量选择
    const handleCancelBatchSelect = () => {
        set_selectedRowKeys([]);
        set_selectedRows([]);
    };

    // 处理表格选择变化
    const handleTableSelectChange = (selectedRowKeys: Key[], selectedRows: any[], info: any) => {
        set_selectedRowKeys(selectedRowKeys);
        set_selectedRows(selectedRows);
    };

    // 处理医生姓名搜索
    const handleSearch = () => {
        set_tableDataFilterParams({
            ...tableDataFilterParams,
            doctorName: tableDataSearchKeywords,
        });
        // 搜索时重置到第一页
        tableRef.current?.reload();
    };

    // 处理证书名称搜索
    const handleCertificateSearch = () => {
        set_tableDataFilterParams({
            ...tableDataFilterParams,
            fileName: certificateSearchKeywords,
        });
        // 搜索时重置到第一页
        tableRef.current?.reload();
    };

    // 处理科室选择变化
    const handleDepartmentChange = (selectedItem: any) => {
        set_currentSelectedDepartment(selectedItem);
        set_tableDataFilterParams({
            ...tableDataFilterParams,
            departmentCode: selectedItem?.code,
        });
    };

    useEffect(() => {
        getDepartmentListData();
    }, []);

    useEffect(() => {
        if (currentSelectedDepartment) {
            set_tableDataFilterParams({
                ...tableDataFilterParams,
                departmentCode: currentSelectedDepartment.code,
            });
        }
    }, [currentSelectedDepartment]);

    return (
        <KCIMPagecontainer className="CertificateMana" title={false} >
            <div className="pageContent">
                <div className="left">
                    <KCIMLeftList
                        searchKey="name"
                        dataSource={departmentData}
                        fieldNames={{ title: 'name', key: 'code' }}
                        defaultSelectType="node"
                        listType="tree"
                        onChange={handleDepartmentChange}
                        placeholder="请输入科室名称"
                    />
                </div>
                <div className="right">
                    <div className="toolBar">
                        <div className="filter">
                            <div className="filterItem">
                                <span className="label">医生姓名：</span>
                                <Input
                                    placeholder="请输入医生姓名"
                                    style={{ width: 200, marginRight: 16 }}
                                    allowClear
                                    autoComplete="off"
                                    suffix={
                                        <IconFont
                                            style={{ color: '#99A6BF' }}
                                            type="iconsousuo"
                                            onClick={handleSearch}
                                        />
                                    }
                                    onChange={(e) => {
                                        set_tableDataSearchKeywords(e.target.value);
                                        if (e.target.value.length === 0) {
                                            set_tableDataSearchKeywords('');
                                            set_tableDataFilterParams({
                                                ...tableDataFilterParams,
                                                doctorName: undefined,
                                            });
                                        }
                                    }}
                                    onPressEnter={handleSearch}
                                />
                            </div>
                            <div className="filterItem">
                                <span className="label">证书名称：</span>
                                <Input
                                    placeholder="请输入证书名称"
                                    style={{ width: 200, marginRight: 16 }}
                                    allowClear
                                    autoComplete="off"
                                    suffix={
                                        <IconFont
                                            style={{ color: '#99A6BF' }}
                                            type="iconsousuo"
                                            onClick={handleCertificateSearch}
                                        />
                                    }
                                    onChange={(e) => {
                                        set_certificateSearchKeywords(e.target.value);
                                        if (e.target.value.length === 0) {
                                            set_certificateSearchKeywords('');
                                            set_tableDataFilterParams({
                                                ...tableDataFilterParams,
                                                fileName: undefined,
                                            });
                                        }
                                    }}
                                    onPressEnter={handleCertificateSearch}
                                />
                            </div>
                            <div className="filterItem">
                                <span className="label">到期时间：</span>
                                <ProFormDatePicker
                                    noStyle
                                    name="expirationDate"
                                    style={{ width: 200, marginRight: 16 }}
                                    placeholder="请选择日期"
                                    fieldProps={{
                                        locale: locale,
                                        format: 'YYYY-MM-DD',
                                        onChange: (date) => {
                                            set_tableDataFilterParams({
                                                ...tableDataFilterParams,
                                                expirationDate: date,
                                            });
                                        },
                                    }}
                                />
                            </div>
                        </div>
                        <div className="btnGroup">
                            <a className="add" onClick={handleAdd}>
                                新增
                            </a>
                        </div>
                    </div>
                    <div style={{ marginTop: 16 }}>
                        <KCIMTable
                            scroll={{ y: `calc(100vh - 230px)` }}
                            actionRef={tableRef}
                            columns={columns as ProColumns[]}
                            rowKey="id"
                            params={tableDataFilterParams}
                            request={(params) => getTableData(params)}
                            tableAlertRender={false}
                            rowSelection={{
                                selectedRowKeys,
                                onChange: handleTableSelectChange,
                            }}
                            pagination={{
                                showSizeChanger: true,
                                showQuickJumper: false,
                                showTotal: (total) => `共计${total}条记录`,
                            }}
                        />
                    </div>
                </div>
            </div>
            
            {/* 新增证书弹窗 */}
            <AddCertificateModal
                visible={addModalVisible}
                onCancel={handleAddCancel}
                onSuccess={handleAddSuccess}
                currentDeptCode={currentSelectedDepartment?.code}
            />
            
            {/* 编辑证书弹窗 */}
            <AddCertificateModal
                visible={editModalVisible}
                onCancel={handleEditCancel}
                onSuccess={handleEditSuccess}
                currentDeptCode={currentSelectedDepartment?.code}
                editData={currentEditRecord}
            />
            
            {/* 批量操作底部条 */}
            {selectedRows.length > 0 && (
                <div className='bottom'>
                    <div className='tags'>已选择证书<span>{selectedRows.length}</span>项</div>
                    <div className='btn-groups'>
                        <div className='cancelBtn' onClick={handleCancelBatchSelect}>取消选择</div>
                        <div className='batchBtn danger' onClick={handleBatchDelete}>批量删除</div>
                    </div>
                </div>
            )}
        </KCIMPagecontainer>
    );
} 