/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-09-23 14:54:02
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */






import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import { createFromIconfontCN, MoreOutlined } from '@ant-design/icons';

import { ActionType, arrayMoveImmutable, ProFormText, ProFormTextArea, useRefFunction } from '@ant-design/pro-components';
import ProForm, { ModalForm, ProFormCascader, ProFormCheckbox, ProFormDateRangePicker, ProFormDependency, ProFormDigit, ProFormRadio, ProFormSelect, ProFormSwitch, ProFormUploadDragger } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Drawer, Input, message, Popconfirm, Popover, Switch, Tooltip, Dropdown, Modal } from 'antd';
import { Fragment, Key, useEffect, useRef, useState, useMemo } from 'react';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';


import { editData, getDepartmentDataReq, getTableDataReq, reAuthData, getApplyListByDoctorReq, getDoctorInfoReq, getDictDataByType, updateDoctorQualInfo } from './service';

import './style.less';
import { KCIMLeftList } from '@/components/KCIMLeftList';
import { getTableList as getQualClassReq } from '../qualificationClassfiMana/service';
import { getDicDataBySysId } from '@/services/getDic';
import { authTimeType, KcimCenterSysId } from '@/constant';
import TableTransfer from './transform';
import React from 'react';
import 'moment/locale/zh-cn';
import moment from 'moment';
import AuthHisContent from './authHisttory';
import { buildTree } from '@/utils/format';
import { useAccess, useModel } from '@umijs/max';
import { addData as addUserAttachment, editData as editUserAttachment, delData as deleteUserAttachment } from '@/pages/personalCenter/myQualifications/service';




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




export default function QualificationAuth({ isChildComponent = false, qualifiCode, onTableSelectChange, defaultSelectedKeys }: {
    isChildComponent: boolean, qualifiCode: string, onTableSelectChange?: (selectedRowKeys: any[], selectedRows: any[], info: any) => void,
    defaultSelectedKeys?: Key[]
}) {

    const { initialState } = useModel('@@initialState');
    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const [dataSource, set_dataSource] = useState<any[]>([]);

    const SortableItem = SortableElement((props: any) => <tr {...props} />);
    const SortContainer = SortableContainer((props: any) => <tbody {...props} />);
    const [currentSelectedType, set_currentSelectedType] = useState<any | undefined>(undefined);
    const [operationLevel, set_operationLevel] = useState<any[]>([]);
    const [drawerVisible, set_drawerVisible] = useState(false);
    const [currentEditRow, set_currentEditRow] = useState<any>(undefined);
    const [currentPageTableData, set_currentPageTableData] = useState<any[]>([]);

    const tableRef = useRef<ActionType>();
    const drawerTableRef = useRef<ActionType>();
    const [drawerTableData, set_drawerTableData] = useState<any[]>([]);
    const [drawerUserInfo, set_drawerUserInfo] = useState<any | undefined>();
    // 进入编辑态时的备份，用于取消还原
    const [drawerUserInfoBackup, set_drawerUserInfoBackup] = useState<any | undefined>();
    const [ifeditQualifiInfo, set_ifeditQualifiInfo] = useState(false);
    // 字典数据
    const [dictPracticeCate, set_dictPracticeCate] = useState<any[]>([]);
    const [dictPracticeSubject, set_dictPracticeSubject] = useState<any[]>([]);
    const [dictDoctorLevel, set_dictDoctorLevel] = useState<any[]>([]);

    const access = useAccess();
    const tabs = access.whatCanIDoInThisPage(location.pathname.replace('/MediResourceManaSys', ''));
    const a = tabs.reduce((prev: any, cur: any) => `${prev},${cur.code}`, '');

    // 工具：判断附件是否在半年内到期
    const isExpiringWithinHalfYear = (expireDate: string) => {
        if (!expireDate) return false;
        const expireMoment = moment(expireDate);
        const now = moment();
        const sixMonthsLater = moment().add(6, 'months');
        return expireMoment.isBetween(now, sixMonthsLater, 'day', '[]') && expireMoment.isAfter(now);
    };

    const columns: ProColumns[] = [
        {
            title: '医生姓名',
            width: 100,
            ellipsis: true,
            renderText(text, record, index, action) {
                const { userInfo: { name } } = record;
                return name
            },
        },
        {
            title: '工号',
            width: 100,
            ellipsis: true,
            renderText(text, record, index, action) {
                const { userInfo: { account } } = record;
                return account
            },
        },
        {
            title: '所在科室',
            ellipsis: true,
            width: 120,
            renderText(text, record, index, action) {
                const { userInfo: { deptName } } = record;
                return deptName
            },
        },
        // {
        //     title: '资质权限',
        //     ellipsis: true,
        //     dataIndex: 'qualificationList'

        // },
        {
            title: '职称',
            ellipsis: true,
            dataIndex: 'title',
            renderText(text, record, index, action) {
                const { userInfo: { title } } = record;
                return title
            },

        },
        {
            title: '职务',
            ellipsis: true,
            dataIndex: 'jobTitle',
            renderText(text, record, index, action) {
                const { userInfo: { jobTitle } } = record;
                return jobTitle
            },

        },
        {
            title: '操作',
            key: 'option',
            width: 60,
            fixed: 'right',
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <a key={'detailBtn'} onClick={() => {
                        const isSame = currentEditRow?.userInfo?.id === record?.userInfo?.id;
                        set_currentEditRow(record);
                        set_drawerVisible(true);
                        // 重复点击同一条时主动刷新数据
                        if (isSame && record?.userInfo?.id) {
                            loadDrawerData(record.userInfo.id, record);
                        }
                    }}>详情</a>
                ]
            },
        },

    ];
    const drawerTablecolumns: ProColumns[] = [
        {
            title: '资质编码',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualificationInfo: { code } } = record;
                return code;
            },
        },
        {
            title: '资质名称',
            renderText(text, record, index, action) {
                const { qualificationInfo: { name, standard } } = record;
                return <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center' }}>
                    <span title={name} style={{ display: 'inline-block', maxWidth: 124, overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>{name}</span>
                    {(standard && standard.length > 0) && <Tooltip title={`授权依据：${standard}`}><IconFont style={{ marginLeft: 10, fontSize: 16, position: 'relative', top: 1 }} type={'iconchakan'} /></Tooltip>}
                </div>;
            },
        },
        {
            title: '授权期限',
            ellipsis: true,
            width: 80,
            dataIndex: 'qualificationPeriod',
            renderText(text, record, index, action) {
                const result = authTimeType.filter((a) => a.value == text);
                if (result.length > 0) {
                    return result[0].label
                }
            },

        },

        {
            title: '授权时间',
            width: 260,
            renderText(text, record, index, action) {
                const { beginDate, endDate, applyAdjust = [] } = record;
                const content = <AuthHisContent hisList={[...applyAdjust]} />

                return <>{`${beginDate}至${endDate}`}
                    {applyAdjust.length > 0 && (
                        <Popover className='qualificationAuth-popover' overlayInnerStyle={{ borderRadius: 4 }} content={content} title={false} >
                            <IconFont type={'icon-qingliangtishi'} style={{ marginLeft: 10 }} />
                        </Popover>
                    )}</>;
            },
        },
        {
            title: '特殊类别',
            ellipsis: true,
            width: 150,
            renderText(text, record, index, action) {
                const { qualificationInfo: { operationFlag, techFlag, operationLevelCode, operationLevelName } } = record;
                return <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center' }}>
                    {
                        techFlag == 1 && (
                            <span style={{
                                display: 'inline-flex', width: 64, height: 20, justifyContent: 'center',
                                alignItems: 'center', background: '#FFF5EB', borderRadius: 4, fontSize: 12, color: '#FF8000', marginRight: 4
                            }}>医疗技术</span>
                        )
                    }
                    {
                        operationFlag == 1 && (
                            <span style={{
                                display: 'inline-flex', width: 64, height: 20, justifyContent: 'center',
                                alignItems: 'center', background: '#E8FCF6', borderRadius: 4, fontSize: 12, color: '#009966'
                            }}>{
                                    operationLevelName
                                    // (operationLevel.filter((a) => a.value == operationLevelCode)).length>0?(operationLevel.filter((a) => a.value == operationLevelCode))[0].name:''
                                }</span>
                        )
                    }
                    {
                        (!operationFlag && !techFlag) && (<Fragment />)
                    }
                </div>
            },
        },
        {
            title: '当前状态',
            width: 80,
            ellipsis: true,
            dataIndex: 'currentStatus',
            renderText(text, record, index, action) {
                if (text == '授权中') {
                    return <><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: '50%', marginRight: 4, background: '#FFB54D' }}></span>{text}</>
                }
                if (text == '已过期') {
                    return <><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: '50%', marginRight: 4, background: '#FF4D6A' }}></span>{text}</>
                }
            },
        },
        {
            title: '操作',
            key: 'option',
            width: 100,
            hideInTable: a.indexOf('medical-adjust') == -1,
            fixed: 'right',
            valueType: 'option',
            render: (_: any, record: any) => {
                const { currentStatus, allowReAuthorize } = record;
                return [
                    currentStatus == '授权中' ? <UpDataActBtn key={'act'} record={record} type='EDIT' /> : allowReAuthorize == 1 && <UpDataActBtn key={'act'} record={record} type='AUTH' />,
                ]
            },
        },

    ]


    const getTableData = async (params: any) => {
        // 非子组件模式下，deptCode 必传；缺失时不发起请求
        if (!isChildComponent && !params?.deptCode) {
            return {
                data: [],
                success: true,
                total: 0,
                current: params?.current || 1,
                pageSize: params?.pageSize || 10,
            }
        }
        const resp = await getTableDataReq(params);
        if (resp) {
            const list = Array.isArray(resp.list) ? resp.list : [];
            const data = list.map((a: any, index: number) => ({ id: index, ...a }));
            set_currentPageTableData(data);
            return {
                data,
                success: true,
                total: resp.totalCount || resp.total || 0,
                current: resp.current || params?.current || 1,
                pageSize: resp.pageSize || params?.pageSize || 10,
            }
        } else {
            return {
                data: [],
                success: false,
                total: 0,
                current: params?.current || 1,
                pageSize: params?.pageSize || 10,
            }
        }
    }


    const updateTable = async (formVal: any, type: 'EDIT' | 'AUTH') => {
        try {
            if (type == 'EDIT') {
                const resp = await editData({
                    qualificationApplyId: formVal.id,
                    qualificationPeriod: Number(formVal.qualificationPeriod),
                    beginDate: formVal.timerange[0],
                    endDate: formVal.timerange[1],
                    memo: formVal.memo
                });
                if (resp) {
                    tableRef.current?.reload();
                    message.success('操作成功！');
                }
            } else {
                const resp = await reAuthData({
                    qualificationApplyId: formVal.id,
                    qualificationPeriod: Number(formVal.qualificationPeriod),
                    beginDate: formVal.timerange[0],
                    endDate: formVal.timerange[1],
                    memo: formVal.memo
                });
                if (resp) {
                    tableRef.current?.reload();
                    message.success('操作成功！');
                }
            }

            return true;

        } catch (error) {

            console.log({ error });
            return false;
        }
    }

    const formRef = useRef();
    // 资质信息编辑表单的引用
    const qualifiInfoFormRef = useRef<any>();
    const UpDataActBtn = ({ record, type }: { record: any, type: 'EDIT' | 'AUTH' }) => {
        const ref = React.createRef<{ save: any; }>();
        return (
            <ModalForm
                title={type == 'EDIT' ? '调整授权' : '重新授权'}
                width={352}
                formRef={formRef}
                initialValues={{
                    // memo: record.applyMemo,
                    qualificationPeriod: 1,
                    timerange: [moment().startOf("day"), moment().startOf("day")]
                }}
                trigger={
                    type == 'EDIT' ? <a key="edit" >调整</a> : <a className='auth'>重新授权</a>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val } : { ...record, ...val }, type);
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >

                <ProFormRadio.Group label='授权期限：' name={'qualificationPeriod'} options={authTimeType} />
                <ProFormDateRangePicker label='授权时间：' name='timerange' />
                <ProFormTextArea label='调整原因：' name={'memo'} />

            </ModalForm>
        )
    }

    // 进入资质信息编辑态
    const handleEnterEditQualInfo = () => {
        // 进入编辑态时备份当前数据，取消时用于回滚
        set_drawerUserInfoBackup(drawerUserInfo ? JSON.parse(JSON.stringify(drawerUserInfo)) : (currentEditRow?.userInfo ? JSON.parse(JSON.stringify(currentEditRow?.userInfo)) : undefined));
        set_ifeditQualifiInfo(true);
        // 拉取字典
        fetchDictionaries();
    }

    // 取消资质信息编辑
    const handleCancelEditQualInfo = () => {
        // 取消编辑：还原备份
        if (drawerUserInfoBackup) {
            set_drawerUserInfo(drawerUserInfoBackup);
            if (currentEditRow) {
                set_currentEditRow({ ...currentEditRow, userInfo: drawerUserInfoBackup });
            }
        }
        set_ifeditQualifiInfo(false);
    }

    // 保存资质信息（当前仅前端合并更新展示，后续可对接后端接口）
    const handleSaveQualInfo = async () => {
        try {
            const values = await (qualifiInfoFormRef?.current?.validateFields?.() || Promise.resolve({}));
            // 组包并提交接口
            const payload = {
                id: (drawerUserInfo || currentEditRow?.userInfo)?.id,
                qualificationCertificateNo: values.qualificationCertificateNo,
                practiceCate: values.practiceCate,
                practiceCertificateNo: values.practiceCertificateNo,
                // 与后端字段保持一致：practiceSubject
                practiceSubject: values.major,
                doctorLevel: values.doctorLevel,
            };
            const resp = await updateDoctorQualInfo(payload);
            if (resp) {
                const prevInfo = (drawerUserInfo || currentEditRow?.userInfo || {});
                // 根据 code 反查中文名，保证展示正确
                const getLabelByCode = (list: any[], code: any) => {
                    if (!Array.isArray(list)) return undefined;
                    const found = list.find((i: any) => String(i.value) === String(code));
                    return found?.label;
                };
                const newInfo = {
                    ...prevInfo,
                    qualificationCertificateNo: values.qualificationCertificateNo,
                    practiceCertificateNo: values.practiceCertificateNo,
                    // 同步维护 code 与中文名
                    practiceCateCode: values.practiceCate,
                    majorCode: values.major,
                    doctorLevelCode: values.doctorLevel,
                    practiceCate: getLabelByCode(dictPracticeCate, values.practiceCate) ?? prevInfo.practiceCate,
                    major: getLabelByCode(dictPracticeSubject, values.major) ?? prevInfo.major,
                    doctorLevel: getLabelByCode(dictDoctorLevel, values.doctorLevel) ?? prevInfo.doctorLevel,
                };
                set_drawerUserInfo(newInfo);
                if (currentEditRow) {
                    set_currentEditRow({ ...currentEditRow, userInfo: newInfo });
                }
                message.success('已保存');
                set_drawerUserInfoBackup(undefined);
                set_ifeditQualifiInfo(false);
            }
        } catch (e) {
            // 校验失败时不做处理，保持在编辑态
        }
    }

    // 拉取字典并缓存
    const fetchDictionaries = async () => {
        try {
            const [cate, subject, level] = await Promise.all([
                getDictDataByType('JOB_TYPE'),
                getDictDataByType('PROFESSIONAL_TYPE'),
                getDictDataByType('PHYSICIAN_TYPE'),
            ]);
            const mapToOptions = (arr: any[]) => (Array.isArray(arr) ? arr.map((i: any) => ({ label: i.name, value: i.code })) : []);
            set_dictPracticeCate(mapToOptions(cate));
            set_dictPracticeSubject(mapToOptions(subject));
            set_dictDoctorLevel(mapToOptions(level));
        } catch (e) {}
    }

    // 新增附件卡片（触发弹窗表单）
    const AddAttachmentCard = () => {
        return (
            <ModalForm
                title={'新增附件'}
                width={520}
                initialValues={{ validFlag: true }}
                trigger={
                    <div
                        style={{
                            width: '100%',
                            height: '100%',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            color: '#4E5969',
                            cursor: 'pointer',
                            padding: '0 12px',
                            border: 'none',
                            background: 'transparent',
                        }}
                    >
                        <span style={{ fontSize: 16, marginRight: 8 }}>+</span>
                        <span>上传文件</span>
                    </div>
                }
                onFinish={async (val) => {
                    // 走与个人中心一致的新增接口逻辑
                    try {
                        const { files, description, dateRange, validFlag } = val;
                        if (!files || files.length === 0) {
                            message.error('请上传附件文件');
                            return false;
                        }
                        let payload: any = {};
                        if (files[0].response) {
                            const resp = files[0].response;
                            if (resp && resp.code === 500) {
                                message.error(resp.msg || '文件上传失败');
                                return false;
                            }
                            const downUrl = resp?.data?.downUrl;
                            if (!downUrl) {
                                message.error('上传返回缺少下载地址');
                                return false;
                            }
                            payload = {
                                userId: (drawerUserInfo || currentEditRow?.userInfo)?.id,
                                fileName: files[0].name,
                                url: downUrl,
                                description: description,
                                activeDate: dateRange ? dateRange[0] : undefined,
                                expireDate: dateRange ? dateRange[1] : undefined,
                                validFlag: validFlag ? 1 : 0,
                            };
                        } else {
                            payload = {
                                userId: (drawerUserInfo || currentEditRow?.userInfo)?.id,
                                fileName: files[0].name,
                                url: files[0].url,
                                description: description,
                                activeDate: dateRange ? dateRange[0] : undefined,
                                expireDate: dateRange ? dateRange[1] : undefined,
                                validFlag: validFlag ? 1 : 0,
                            };
                        }

                        const resp = await addUserAttachment(payload);
                        if (resp) {
                            const prev = (drawerUserInfo || currentEditRow?.userInfo || {});
                            const list = Array.isArray(prev.attachments) ? prev.attachments : [];
                            const newInfo = { ...prev, attachments: [...list, { ...payload }] };
                            set_drawerUserInfo(newInfo);
                            if (currentEditRow) {
                                set_currentEditRow({ ...currentEditRow, userInfo: newInfo });
                            }
                            message.success('已添加');
                            return true;
                        }
                        return false;
                    } catch (e) {
                        return false;
                    }
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >
                <ProFormUploadDragger
                    rules={[{ required:true, message: '文件不能为空!' }]}
                    name='files'
                    action={'/gateway/centerSys/api/upload'}
                    max={1}
                    description={false}
                    title={<span style={{ fontSize: 14, color: '#17181A' }}>点击或将文件拖拽到这里上传</span>}
                    fieldProps={{
                        name: 'file',
                        height: 140,
                        multiple: false,
                        headers: {
                            token: initialState?.userData?.token as string
                        },
                    }}
                />
                <ProFormDateRangePicker name='dateRange' label='有效期：' />
                <ProFormSwitch name='validFlag' label='当前有效：' />
                <ProFormTextArea name='description' label='说明：' />
            </ModalForm>
        )
    }

    // 删除附件
    const handleRemoveAttachment = async (removeIndex: number) => {
        try {
            const prev = (drawerUserInfo || currentEditRow?.userInfo || {});
            const list = Array.isArray(prev.attachments) ? prev.attachments : [];
            const target = list[removeIndex];
            if (target?.id) {
                await deleteUserAttachment(target.id);
            }
            const newList = list.filter((_: any, idx: number) => idx !== removeIndex);
            const newInfo = { ...prev, attachments: newList };
            set_drawerUserInfo(newInfo);
            if (currentEditRow) {
                set_currentEditRow({ ...currentEditRow, userInfo: newInfo });
            }
            message.success('已删除');
        } catch (e) {
            message.error('删除失败');
        }
    }

    // 编辑附件按钮（弹窗表单）
    const EditAttachmentBtn = ({ index, item }: { index: number; item: any; }) => {
        return (
            <ModalForm
                title={'编辑附件'}
                width={520}
                initialValues={{
                    files: [{ uid: item?.id, name: item?.fileName, url: item?.url, status: 'done' }],
                    description: item?.description,
                    dateRange: (item?.activeDate && item?.expireDate) ? [moment(item.activeDate).format('YYYY-MM-DD'), moment(item.expireDate).format('YYYY-MM-DD')] : [],
                    validFlag: item?.validFlag === 1,
                }}
                trigger={<a>编辑</a>}
                onFinish={async (val) => {
                    try {
                        const { files, description, dateRange, validFlag } = val;
                        let payload: any = { id: item?.id };
                        if (files && files[0] && files[0].response) {
                            const resp = files[0].response;
                            if (resp && resp.code === 500) {
                                message.error(resp.msg || '文件上传失败');
                                return false;
                            }
                            const downUrl = resp?.data?.downUrl;
                            if (!downUrl) {
                                message.error('上传返回缺少下载地址');
                                return false;
                            }
                            payload = {
                                ...payload,
                                userId: (drawerUserInfo || currentEditRow?.userInfo)?.id,
                                fileName: files[0].name,
                                url: downUrl,
                            };
                        } else if (files && files[0]) {
                            payload = {
                                ...payload,
                                userId: (drawerUserInfo || currentEditRow?.userInfo)?.id,
                                fileName: files[0].name,
                                url: files[0].url,
                            };
                        }
                        payload = {
                            ...payload,
                            description: description,
                            activeDate: dateRange ? dateRange[0] : undefined,
                            expireDate: dateRange ? dateRange[1] : undefined,
                            validFlag: validFlag ? 1 : 0,
                        };

                        const resp = await editUserAttachment(payload);
                        if (resp) {
                            const prev = (drawerUserInfo || currentEditRow?.userInfo || {});
                            const list = Array.isArray(prev.attachments) ? [...prev.attachments] : [];
                            list[index] = { ...item, ...payload };
                            const newInfo = { ...prev, attachments: list };
                            set_drawerUserInfo(newInfo);
                            if (currentEditRow) {
                                set_currentEditRow({ ...currentEditRow, userInfo: newInfo });
                            }
                            message.success('已更新');
                            return true;
                        }
                        return false;
                    } catch (e) {
                        return false;
                    }
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >
                <ProFormUploadDragger
                    rules={[{ required:true, message: '文件不能为空!' }]}
                    name='files'
                    action={'/gateway/centerSys/api/upload'}
                    max={1}
                    description={false}
                    title={<span style={{ fontSize: 14, color: '#17181A' }}>点击或将文件拖拽到这里上传</span>}
                    fieldProps={{
                        name: 'file',
                        height: 140,
                        multiple: false,
                        headers: {
                            token: initialState?.userData?.token as string
                        },
                    }}
                />
                <ProFormDateRangePicker name='dateRange' label='有效期：' />
                <ProFormSwitch name='validFlag' label='当前有效：' />
                <ProFormTextArea name='description' label='说明：' />
            </ModalForm>
        )
    }

    const tableDataSearchHandle = (key: string) => {
        set_tableDataFilterParams({ ...tableDataFilterParams, current: 1, [key]: tableDataSearchKeywords })
    }

    const getDepartmentsHandle = async () => {
        const resp = await getDepartmentDataReq();
        if (resp) {
            set_dataSource(resp);
        }
    }

    const updateTableSortHandle = async (data: any[]) => {

    }

    const onSortEnd = useRefFunction(
        ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => {
            if (oldIndex !== newIndex) {
                const newData = arrayMoveImmutable({
                    array: [...dataSource],
                    fromIndex: oldIndex,
                    toIndex: newIndex,
                }).filter((el) => !!el);

                const updatedSortArr = newData.map((item: any, index: number) => ({ ...item, sort: index + 1 }));
                set_dataSource([...updatedSortArr]);
                updateTableSortHandle(updatedSortArr);
            }
        },
    );

    const DraggableContainer = (props: any) => (
        <SortContainer
            useDragHandle
            disableAutoscroll
            helperClass="row-dragging"
            onSortEnd={onSortEnd}
            {...props}
        />
    );

    const DraggableBodyRow = (props: any) => {
        const { className, style, ...restProps } = props;

        // function findIndex base on Table rowKey props and should always be a right array index
        const index = dataSource.findIndex((x) => x.id === restProps['data-row-key']);

        return <SortableItem index={index} {...restProps} />;
    };


    useEffect(() => {
        if (currentSelectedType && !isChildComponent) {
            // getTableData({ qualificationTypeCode: currentSelectedType.code });
            set_tableDataFilterParams({ ...tableDataFilterParams, current: 1, deptCode: currentSelectedType.code })
        }
    }, [currentSelectedType]);

    useEffect(() => {
        if (isChildComponent && qualifiCode) {
            set_currentSelectedType(true);
            set_tableDataFilterParams({ ...tableDataFilterParams, current: 1, qualificationTypeCode: qualifiCode })
        }
    }, [qualifiCode]);

    // 提炼为方法，便于重复点击同一行时强制刷新
    async function loadDrawerData(userId?: any, record?: any) {
        try {
            const id = userId ?? record?.userInfo?.id ?? currentEditRow?.userInfo?.id;
            if (!id) return;
            const applyResp = await getApplyListByDoctorReq({ userId: id });
            set_drawerTableData(Array.isArray(applyResp?.list) ? applyResp.list : (Array.isArray(applyResp) ? applyResp : []));
            const doctorResp = await getDoctorInfoReq({ userId: id });
            set_drawerUserInfo(doctorResp || {});
        } catch (e) {
            console.log('fetch drawer data error', e);
            if (record?.applyList) {
                set_drawerTableData([...record.applyList]);
            } else if (currentEditRow?.applyList) {
                set_drawerTableData([...currentEditRow.applyList]);
            }
            set_drawerUserInfo(record?.userInfo || currentEditRow?.userInfo || {});
        }
    };

    useEffect(() => {
        if (currentEditRow) {
            loadDrawerData();
        }
    }, [currentEditRow]);

    useEffect(() => {
        if (currentPageTableData && drawerVisible) {
            const needitem = currentPageTableData.filter((a) => a.userInfo.id == currentEditRow.userInfo.id);

            if (needitem.length > 0) {
                set_currentEditRow(needitem[0]);
            }

        }
    }, [currentPageTableData])

    useEffect(() => {
        getDepartmentsHandle()
    }, [])

    // 仅向表格透传业务筛选参数，去除 current/pageSize，避免覆盖 ProTable 内部分页参数
    const sanitizedTableParams = useMemo(() => {
        const p = { ...(tableDataFilterParams || {}) } as any;
        if (p && typeof p === 'object') {
            delete p.current;
            delete p.pageSize;
        }
        return p;
    }, [tableDataFilterParams]);

    return (
        <KCIMPagecontainer className='QualificationAuth' style={!isChildComponent ? {} : { border: 'none' }} title={false}>
            <Drawer destroyOnClose={true} className='doctorQualifiAuth-authDetailDrawer' width={1100}
                open={drawerVisible} headerStyle={{ display: 'none' }} bodyStyle={{ background: '#F5F7FA', padding: 16 }}
            >
                <div className='authDetailDrawer-topBar'>
                    <div className='authDetailDrawer-topBar-title'>
                        <div className='closeIcon' onClick={() => set_drawerVisible(false)}><IconFont type={'iconquxiao'} /></div>{'授权详情'}
                    </div>
                    {/* <div className='btnGroup'>
                        <span onClick={() => set_drawerVisible(false)}>取消</span>
                        <span className='reject' onClick={() => updateTable(2)}>驳回</span>
                        <span className='commit' onClick={() => updateTable(1)}>通过</span>
                    </div> */}
                </div>
                <div className='authDetailDrawer-content'>
                    <div className='authDetailDrawer-info'>
                        {(() => {
                            const currentUserInfo = drawerUserInfo || currentEditRow?.userInfo; return (
                                <>
                                    <div className='avator'><img src={(currentUserInfo?.avatarUrl) ? currentUserInfo?.avatarUrl : require('../../../../static/avatar.png')} alt="avator" /></div>
                                    <div className='authDetailDrawer-info-detail'>
                                        <div className='authDetailDrawer-info-title'>
                                            {currentUserInfo?.name}
                                            <img style={{ width: 16, height: 16, marginLeft: 8 }} src={require(`../../../../static/${currentUserInfo?.gender == '男' ? 'male' : 'female'}.png`)} alt="" />
                                        </div>
                                        <div className='authDetailDrawer-info-title-sub'>
                                            工号：{currentUserInfo?.account}<span style={{ padding: '0 8px' }}></span>
                                            科室：{currentUserInfo?.deptName}<span style={{ padding: '0 8px' }}></span>
                                            职称：{currentUserInfo?.jobTitle}<span style={{ padding: '0 8px' }}></span>
                                            职务：{currentUserInfo?.title}
                                        </div>
                                    </div>
                                </>
                            )
                        })()}
                    </div>
                    <div className='authDetailDrawer-qualication-info'>
                        <div className='authDetailDrawer-qualication-info-title'>资质信息
                            <span>
                                {!ifeditQualifiInfo && <a onClick={handleEnterEditQualInfo}>编辑</a>}
                                {ifeditQualifiInfo && <><a onClick={handleCancelEditQualInfo} style={{ paddingRight: 8 }}>取消</a><a onClick={handleSaveQualInfo}>保存</a></>}
                            </span>
                        </div>
                        {
                            !ifeditQualifiInfo && (<>
                                <div className='authDetailDrawer-qualication-info-tag-wrapper'>
                                    {(() => {
                                        const currentUserInfo = drawerUserInfo || currentEditRow?.userInfo; return (<>
                                            <div className='qualication-info-tag'>资质证号：<span>{currentUserInfo?.qualificationCertificateNo}</span></div>
                                            <div className='qualication-info-tag'>执业类别：<span>{currentUserInfo?.practiceCate}</span></div>
                                            <div className='qualication-info-tag'>执业证号：<span>{currentUserInfo?.practiceCertificateNo}</span></div>
                                            <div className='qualication-info-tag'>执业专业：<span>{currentUserInfo?.major}</span></div>
                                            <div className='qualication-info-tag'>医师级别：<span>{currentUserInfo?.doctorLevel}</span></div>
                                        </>)
                                    })()}

                                </div>
                            </>)
                        }
                        {
                            ifeditQualifiInfo && (<>
                                <ProForm
                                    layout='vertical'
                                    submitter={false}
                                    grid
                                    formRef={qualifiInfoFormRef}
                                    initialValues={(() => {
                                        // 使用抽屉内获取到的医生信息作为初始值
                                        const currentUserInfo = drawerUserInfo || currentEditRow?.userInfo || {};
                                        return {
                                            qualificationCertificateNo: currentUserInfo?.qualificationCertificateNo,
                                            practiceCate: currentUserInfo?.practiceCateCode ?? currentUserInfo?.practiceCate,
                                            practiceCertificateNo: currentUserInfo?.practiceCertificateNo,
                                            major: currentUserInfo?.majorCode ?? currentUserInfo?.major,
                                            doctorLevel: currentUserInfo?.doctorLevelCode ?? currentUserInfo?.doctorLevel,
                                        };
                                    })()}
                                >
                                    <ProFormText colProps={{ md: 12, xl: 8 }} label='资格证号：' name='qualificationCertificateNo' placeholder='请输入' />
                                    <ProFormSelect colProps={{ md: 12, xl: 8 }} label='执业类别：' name='practiceCate' placeholder='请选择' options={dictPracticeCate} />
                                    <ProFormText colProps={{ md: 12, xl: 8 }} label='执业证号：' name='practiceCertificateNo' placeholder='请输入' />
                                    <ProFormSelect colProps={{ md: 12, xl: 8 }} label='执业专业：' name='major' placeholder='请选择' options={dictPracticeSubject} />
                                    <ProFormSelect colProps={{ md: 12, xl: 8 }} label='医师级别：' name='doctorLevel' placeholder='请选择' options={dictDoctorLevel} />
                                </ProForm>
                            </>)
                        }


                        <div className='authDetailDrawer-qualication-info-certs'>
                            {(() => {
                                const currentUserInfo = drawerUserInfo || currentEditRow?.userInfo; return (
                                    <>
                                        {currentUserInfo?.attachments?.map((item: any, index: number) => {
                                            return (
                                            <div key={index} className='qualificationInfo-fileItem' style={{ position: 'relative' }}>
                                                {(item.activeDate && item.expireDate) && (() => {
                                                    const isExpiring = isExpiringWithinHalfYear(item.expireDate);
                                                    return <div className={`dateTag ${item.validFlag ? '' : 'valid'} ${isExpiring ? 'expiring' : ''}`}><span>{`${item.activeDate}~${item.expireDate}`}</span></div>
                                                })()}
                                                <img src={require('../../../../static/fileIcon.png')} alt="" />
                                                <div className='qualificationInfo-fileItem-detail'>
                                                    <div className='qualificationInfo-fileItem-detail-name'>{item.fileName}</div>
                                                    <div className='qualificationInfo-fileItem-detail-sub'>{item.description}</div>
                                                </div>
                                                {!ifeditQualifiInfo && (
                                                    <Tooltip title='下载'>
                                                        <a className='downloadBtn' href={item.url} target='_blank' ><IconFont style={{ color: '#17181A' }} type={'iconxiazai'} /></a>
                                                    </Tooltip>
                                                )}
                                                {ifeditQualifiInfo && (
                                                    <Dropdown
                                                        trigger={['hover']}
                                                        menu={{
                                                            items: [
                                                                {
                                                                    key: 'edit',
                                                                    label: <EditAttachmentBtn index={index} item={item} />,
                                                                },
                                                                {
                                                                    key: 'delete',
                                                                    label: <Popconfirm title='确认删除该附件？' onConfirm={() => handleRemoveAttachment(index)}><a>删除</a></Popconfirm>,
                                                                },
                                                            ],
                                                        }}
                                                    >
                                                        <a className='attachment-more'>
                                                            <MoreOutlined />
                                                        </a>
                                                    </Dropdown>
                                                )}
                                            </div>
                                            )
                                        })}
                                        {ifeditQualifiInfo && (
                                            <div key={'add-card'} className='qualificationInfo-fileItem addBtn'>
                                                <AddAttachmentCard />
                                            </div>
                                        )}
                                    </>
                                )
                            })()}
                        </div>
                    </div>
                    <div className='authDetailDrawer-content-table'>
                        <div className='authDetailDrawer-content-table-title'>授权信息</div>
                        <KCIMTable
                            actionRef={drawerTableRef} columns={drawerTablecolumns as ProColumns[]} rowKey='id'
                            // request={(params) => getTableData(params)}
                            dataSource={drawerTableData}
                            tableAlertRender={false}
                            scroll={{ y: 361 }}
                        />
                    </div>

                </div>


            </Drawer>
            <div className='pageContent'>
                {
                    !isChildComponent && (
                        <div className='left'>
                            <KCIMLeftList searchKey={'name'} dataSource={dataSource} fieldNames={{ title: 'name', key: 'code' }}
                                defaultSelectType='node'
                                listType='tree' onChange={(val) => set_currentSelectedType(val)} />
                        </div>
                    )
                }
                <div className='right' style={isChildComponent ? { width: '100%' } : { width: 'calc(100% - 236px)', padding: 16 }}>
                    <div className='toolBar'>
                        <div className='filter'>
                            <div className='filterItem'>
                                <span className='label'>检索：</span>
                                <Input placeholder={'医生名称'} style={{ width: 160, marginRight: 16 }} allowClear autoComplete='off'

                                    suffix={
                                        <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" onClick={() => tableDataSearchHandle('userName')} />
                                    }
                                    onChange={(e) => {
                                        set_tableDataSearchKeywords(e.target.value);
                                        if (e.target.value.length == 0) {
                                            set_tableDataSearchKeywords('');
                                            set_tableDataFilterParams({ ...tableDataFilterParams, userName: undefined })
                                        }
                                    }}

                                    onPressEnter={(e) => {
                                        tableDataSearchHandle('userName')
                                    }}

                                />
                            </div>
                        </div>
                        {/* {!isChildComponent && (
                            <div className='btnGroup'>
                                <UpDataActBtn record type='ADD' />
                            </div>
                        )} */}
                    </div>
                    <div style={{ marginTop: 16 }}>
                        {currentSelectedType && <KCIMTable
                            scroll={{ y: `calc(100vh - 230px)` }}
                            actionRef={tableRef} columns={columns as ProColumns[]} rowKey='id'
                            params={sanitizedTableParams}
                            request={(params) => getTableData(params)}
                            // dataSource={showList}
                            tableAlertRender={false}
                            rowSelection={isChildComponent ? {
                                defaultSelectedRowKeys: defaultSelectedKeys,
                                onChange(selectedRowKeys, selectedRows, info) {
                                    onTableSelectChange && onTableSelectChange(selectedRowKeys, selectedRows, info)
                                },
                            } : false}
                            components={{
                                body: {
                                    wrapper: DraggableContainer,
                                    row: DraggableBodyRow,
                                },
                            }}
                        />}
                    </div>
                </div>
            </div>
        </KCIMPagecontainer>
    )
}
