/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-08-07 17:23:04
 * @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, InboxOutlined } from '@ant-design/icons';

import { ActionType, arrayMoveImmutable, ProFormText, ProFormTextArea, useRefFunction } from '@ant-design/pro-components';
import ProForm, { ModalForm, ProFormCascader, ProFormCheckbox, ProFormDatePicker, ProFormDateRangePicker, ProFormDependency, ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormSwitch, ProFormUploadDragger } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Alert, Drawer, Dropdown, Form, Input, message, Popconfirm, Popover, Radio } from 'antd';
import { Fragment, Key, useEffect, useRef, useState } from 'react';



import { addData, delData, editData, getMyInfoReq, getTableDataReq, getQualificationHistoryReq } from './service';

import './style.less';

import { getDicDataBySysId } from '@/services/getDic';
import { authTimeType, KcimCenterSysId } from '@/constant';

import 'moment/locale/zh-cn';
import moment from 'moment';
import { sparse } from 'mathjs';
import AuthHisContent from './authHisttory';
import FormTabs from './tabs';
import { calculateDelayedDate } from '@/utils/tooljs';
import { debounce } from 'lodash';
import { useModel } from '@umijs/max';

// 判断附件是否在半年内到期
const isExpiringWithinHalfYear = (expireDate: string) => {
    if (!expireDate) return false;
    
    const expireMoment = moment(expireDate);
    const now = moment();
    const sixMonthsLater = moment().add(6, 'months');
    
    // 如果过期日期在现在和6个月后之间，且还未过期
    return expireMoment.isBetween(now, sixMonthsLater, 'day', '[]') && expireMoment.isAfter(now);
};


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


export default function MyQualifications() {
    const { initialState, setInitialState } = useModel('@@initialState');
    const formRef = useRef<ProFormInstance>();
    const drawerFormRef = useRef<ProFormInstance>();
    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const [drawerVisible, set_drawerVisible] = useState(false);
    const [currentEditRow, set_currentEditRow] = useState<any>(undefined);

    const [currentSelectedTableRows, set_currentSelectedTableRows] = useState<any[]>([]);

    // 添加授权历史记录状态
    const [qualificationHistory, set_qualificationHistory] = useState<any[]>([]);
    const [historyLoading, set_historyLoading] = useState<boolean>(false);


    const tableRef = useRef<ActionType>();
    const [modalFormVisible, set_modalFormVisible] = useState(false);
    const [operationLevel, set_operationLevel] = useState<any[]>([]);
    const [userInfo, set_userInfo] = useState<any>(undefined);
    const [currentEditAttachment, set_currentEditAttachment] = useState<any>(undefined);


    const columns: ProColumns[] = [
        {
            title: '资质编码',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualification: { code } } = record;
                return code
            },
        },
        {
            title: '资质名称',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualification: { name } } = record;
                return name
            },
        },
        {
            title: '资质分类',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualification: { qualificationTypeName } } = record;
                return qualificationTypeName
            },
        },
        {
            title: '特殊类别',
            ellipsis: true,
            width: 150,
            renderText(text, record, index, action) {
                const { qualification: { operationFlag, techFlag, operationLevelCode } } = record;
                return <div>
                    {
                        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 && operationLevelCode && (
                            <span style={{
                                display: 'inline-flex', width: 64, height: 20, justifyContent: 'center',
                                alignItems: 'center', background: '#E8FCF6', borderRadius: 4, fontSize: 12, color: '#009966'
                            }}>{
                                    (operationLevel.filter((a) => a.value == operationLevelCode)).length > 0 ? (operationLevel.filter((a) => a.value == operationLevelCode))[0].name : ''
                                }</span>
                        )
                    }
                    {
                        (!operationFlag && !techFlag) && (<Fragment />)
                    }
                </div>
            },
        },
        {
            title: '操作',
            key: 'option',
            width: 80,
            fixed: 'right',
            valueType: 'option',
            render: (_: any, record: any) => {
                return <a key={1} onClick={() => {
                    set_currentEditRow(record);
                    set_drawerVisible(true)
                }}>详情</a>
            },
        },

    ];


    const getTableData = async (params: any) => {
        const resp = await getTableDataReq({ ...params });
        if (resp) {
            return {
                data: resp.list,
                success: true
            }
        } else {
            return []
        }
    }

    const getOperationLevelList = async () => {
        const resp = await getDicDataBySysId(KcimCenterSysId, 'SURGICAL_AND_OPERATIONAL_LEVELS');
        if (resp) {
            set_operationLevel(resp.dataVoList);
        }
    }

    // 获取资质授权历史记录
    const getQualificationHistory = async (qualificationCode: string) => {
        set_historyLoading(true);
        try {
            const resp = await getQualificationHistoryReq(qualificationCode);
            if (resp) {
                set_qualificationHistory(resp);
            } else {
                set_qualificationHistory([]);
            }
        } catch (error) {
            console.error('获取授权历史失败:', error);
            set_qualificationHistory([]);
        } finally {
            set_historyLoading(false);
        }
    }


    const updateTable = async (formVal: any, type: 'ADD' | 'EDIT') => {
        console.log({formVal});
        try {
            const { files, memo, id,dateRange=undefined } = formVal;
            let result = {};
            // 处理上传文件的 response 结构和错误
            if (files[0].response) {
                const response = files[0].response;
                // 判断接口返回是否成功（code为0或200，根据实际后端约定）
                if (response.code && response.code !== 0 && response.code !== 200) {
                    // 上传失败，提示后端返回的错误信息
                    message.error(response.msg || '文件上传失败！');
                    return false;
                }
                // 判断 data/downUrl 是否存在
                if (!response.data || !response.data.downUrl) {
                    message.error('文件上传返回数据异常，缺少下载地址！');
                    return false;
                }
                const { name } = files[0];
                const { downUrl } = response.data;
                result = {
                    id: type == 'EDIT' ? id : null,
                    userId: userInfo.id,
                    fileName: name,
                    url: downUrl,
                    description: memo,
                    activeDate:dateRange?dateRange[0]:undefined,
                    expireDate:dateRange?dateRange[1]:undefined,
                };
            } else {
                const { name ,url} = files[0];
                result = {
                    id: type == 'EDIT' ? id : null,
                    userId: userInfo.id,
                    fileName: name,
                    url: url,
                    description: memo,
                    activeDate:dateRange?dateRange[0]:undefined,
                    expireDate:dateRange?dateRange[1]:undefined,
                };
            }


            const resp = type == 'ADD' ? await addData(result) : await editData(result);
            if (resp) {

                set_currentEditAttachment(undefined);
                getUserInfo();
                set_modalFormVisible(false);
                message.success('操作成功！');
            }

            return true;

        } catch (error) {

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




    }


    const tableDataSearchHandle = (key: string) => {
        set_tableDataFilterParams({ ...tableDataFilterParams, current: 1, [key]: tableDataSearchKeywords })
    }
    const getAuthPeriod = (code: number) => {
        const result = authTimeType.filter(a => a.value == code);
        return result.length > 0 ? result[0].label : '-'
    }

    const getUserInfo = async () => {
        const resp = await getMyInfoReq();
        if (resp) {
            set_userInfo(resp);
        }
    }

    const delUseerAttachmentHandle = async (record: any) => {
        const resp = await delData(record.id);
        if (resp) {
            getUserInfo();
            set_modalFormVisible(false);
            message.success('操作成功！');
        }
    }

    const drapDownItems = (fileData: any) => [
        {
            key: '1',
            label: (
                <a onClick={() => {
                    set_currentEditAttachment(fileData);
                    set_modalFormVisible(true);
                }}>编辑</a>
            ),
        },
        {
            key: '2',
            label: (
                <Popconfirm
                    title="是否确认删除？"
                    key="del"
                    onConfirm={() => delUseerAttachmentHandle(fileData)}
                >
                    <a>删除</a>
                </Popconfirm>
            )
        },
    ]

    useEffect(() => {
        if (drawerVisible) {
            getOperationLevelList();
            // 获取授权历史记录
            if (currentEditRow?.qualification?.code) {
                getQualificationHistory(currentEditRow.qualification.code);
            }
        }
    }, [drawerVisible]);
    
    useEffect(()=>{
        if(!modalFormVisible){
            set_currentEditAttachment(undefined);
        }
    },[modalFormVisible]);

    useEffect(() => {
        getUserInfo();
    }, []);
    return (
        <KCIMPagecontainer className='MyQualifications' title={false} >
            <ModalForm
                title={currentEditAttachment ? '编辑附件' : '上传附件'}
                width={352}
                formRef={formRef}
                open={modalFormVisible}
                initialValues={currentEditAttachment ? {
                    files: [{ uid: currentEditAttachment.id, name: currentEditAttachment.fileName, url: currentEditAttachment.url, status: 'done' }],
                    memo: currentEditAttachment.description,
                    dateRange:(currentEditAttachment.activeDate&&currentEditAttachment.expireDate)?[moment(currentEditAttachment.activeDate).format('YYYY-MM-DD'),moment(currentEditAttachment.expireDate).format('YYYY-MM-DD')]:[]
                } : {}}

                onFinish={(val) => {
                    return updateTable(currentEditAttachment ? { ...currentEditAttachment, ...val } : { ...val }, currentEditAttachment ? 'EDIT' : 'ADD');
                }}
                modalProps={{ destroyOnClose: true, onCancel: () => set_modalFormVisible(false), }}
                colProps={{ span: 24 }}
                grid
                submitter={{
                    searchConfig: {
                        submitText: '确认',
                        resetText: '取消',
                    },
                }}
            >

                <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
                        },
                        // 上传状态变更时的回调，处理成功和失败的提示
                        onChange(info) {
                            const { status, response } = info.file;
                            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} 文件上传失败。`);
                            }
                        },
                        // onDrop(e) {
                        //     console.log('拖拽上传的文件:', e.dataTransfer.files);
                        // },
                    }}
                />
                <ProFormDateRangePicker rules={[{ required:false, message: '有效期限不能为空!' }]}
                 label='有效期限：' name={'dateRange'} fieldProps={{
                    // defaultValue: [moment().startOf('days'), momentq().endOf('days')]
                }} />
                <ProFormTextArea name={'memo'} fieldProps={{
                    style: { height: 85 }
                }} label='附件说明：' />

            </ModalForm>
            <Drawer destroyOnClose={true} className='MyQualifications-authDetailDrawer' width={700}
                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>
                <div className='authDetailDrawer-content'>
                    <div className='authDetailDrawer-info'>
                        <div className='authDetailDrawer-info-title'>
                            {currentEditRow?.qualification?.name}
                            {
                                currentEditRow?.qualification?.techFlag == 1 && (
                                    <span style={{
                                        display: 'inline-flex', height: 20, justifyContent: 'center', marginLeft: 8, padding: '0 12px',
                                        alignItems: 'center', background: '#FFF5EB', borderRadius: 4, fontSize: 12, color: '#FF8000', marginRight: 4
                                    }}>医疗技术</span>
                                )
                            }
                            {
                                currentEditRow?.qualification?.operationFlag == 1 && (
                                    <span style={{
                                        display: 'inline-flex', height: 20, justifyContent: 'center', padding: '0 12px', marginLeft: 8,
                                        alignItems: 'center', background: '#E8FCF6', borderRadius: 4, fontSize: 12, color: '#009966'
                                    }}>{
                                            ((operationLevel.filter((a) => a.value == currentEditRow?.qualification?.operationLevelCode))).length > 0 ? ((operationLevel.filter((a) => a.value == currentEditRow?.qualification?.operationLevelCode)))[0].name : ''
                                        }</span>
                                )
                            }
                        </div>
                        <div className='authDetailDrawer-info-title-sub'>
                            资质编码：{currentEditRow?.qualification?.code}<span style={{ padding: '0 8px' }}></span>
                            资质分类：{currentEditRow?.qualification?.qualificationTypeName}
                            {currentEditRow?.qualification?.standard.length > 0 && (
                                <div className='authDetailDrawer-info-standard'>
                                    {currentEditRow.qualification.standard}
                                    <img src={require('../../../../static/shouquanyiju.png')} alt="" />
                                </div>
                            )}
                        </div>
                    </div>
                    <div className='authHistory'>
                        <div className='authHistory-title'>授权记录</div>
                        <div className='historyListWrapper'>
                            {historyLoading ? (
                                <div style={{ textAlign: 'center', padding: '20px' }}>加载中...</div>
                            ) : (
                                qualificationHistory.map((a: any, index: number) => {
                                    return <div className='historyList' key={index}>
                                        <img src={require(`../../../../static/${index == 0 ? 'gou_black' : 'gou_white'}.png`)} alt="" />
                                        <div className='historyList-detail'>
                                            {(authTimeType.filter((b) => b.value == a.qualificationPeriod)).length > 0 ? (authTimeType.filter((b) => b.value == a.qualificationPeriod))[0].label : ''}
                                            |{`${a.beginDate}至${a.endDate}`}
                                            {a.applyAdjust && a.applyAdjust.length > 0 && (
                                                <Popover className='qualificationAuth-popover' overlayInnerStyle={{borderRadius:4}} content={<AuthHisContent hisList={[...a.applyAdjust]} />} title={false} >
                                                    <IconFont type={'icon-qingliangtishi'} style={{ marginLeft: 10, cursor: 'pointer' }} />
                                                </Popover>
                                            )}
                                        </div>
                                        <div className={`status ${a.currentStatus == '授权中'?'authing':'expired'}`}>{a.currentStatus}</div>
                                    </div>
                                })
                            )}
                        </div>
                    </div>

                </div>


            </Drawer>
            <div className='pageContent'>
                <div className='left'>
                    <div className='pageContent-title'>我的资质</div>
                    <div className='toolBar'>
                        <div className='filter'>
                            <div className='filterItem'>
                                <span className='label'>手术级别：</span>
                                <ProFormSelect noStyle
                                    style={{ width: 160, marginRight: 16 }}
                                    placeholder={'请选择'}
                                    request={async () => {
                                        const resp = await getDicDataBySysId(KcimCenterSysId, 'SURGICAL_AND_OPERATIONAL_LEVELS');
                                        if (resp) {
                                            set_operationLevel(resp.dataVoList);
                                            return resp.dataVoList.map((item: any) => ({ label: item.name, value: item.value }))
                                        }
                                    }}
                                    fieldProps={{
                                        onChange(value, option) {
                                            set_tableDataFilterParams({ ...tableDataFilterParams, current: 1, operationLevelCode: value })
                                        },
                                    }}
                                />
                            </div>
                            <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('name')} />
                                    }
                                    onChange={(e) => {
                                        set_tableDataSearchKeywords(e.target.value);
                                        if (e.target.value.length == 0) {
                                            set_tableDataSearchKeywords('');
                                            set_tableDataFilterParams({ ...tableDataFilterParams, name: undefined })
                                        }
                                    }}

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

                                />
                            </div>
                            <div className='filterItem'>
                                <ProFormCheckbox.Group
                                    name="checkbox"
                                    layout='horizontal'
                                    noStyle
                                    options={['医疗技术', '手术']}
                                    fieldProps={{
                                        onChange(checkedValue) {
                                            set_tableDataFilterParams({
                                                ...tableDataFilterParams,
                                                current: 1,
                                                techFlag: checkedValue.findIndex((a) => a == '医疗技术') != -1 ? 1 : 0,
                                                operationFlag: checkedValue.findIndex((a) => a == '手术') != -1 ? 1 : 0,
                                            })
                                        },
                                    }}
                                />
                            </div>
                        </div>
                        {currentSelectedTableRows.length > 0 && (
                            <div className='btnGroup'>
                                <span className='batchAdjust' onClick={() => set_modalFormVisible(true)}>批量调整</span>
                            </div>
                        )}
                    </div>
                    <div style={{ marginTop: 16 }}>
                        <KCIMTable scroll={{ y: `calc(100vh - 264px)` }}
                            actionRef={tableRef} columns={columns as ProColumns[]} rowKey='id'
                            params={tableDataFilterParams}
                            request={(params) => getTableData(params)}
                            // dataSource={showList}
                            tableAlertRender={false}


                        />
                    </div>
                </div>
                <div className='right'>
                    <div className='avatar-info'>
                        <img src={userInfo?.avatarUrl?userInfo?.avatarUrl:require('../../../../static/avatar.png')} alt="" />
                        <div className='name'>
                            <div className='name-text'>{userInfo?.name}{userInfo?.gender&&<img src={require(`../../../../static/${userInfo?.gender == '男' ? 'male' : 'female'}.png`)} alt="" />}</div>
                            <div className='id'>{userInfo?.account}</div>
                        </div>
                    </div>
                    <div className='jobInfo'>
                        <div className='jobInfo-block'>
                            <div className='value'>{userInfo?.deptName??'-'}</div>
                            <div className='label'>科室</div>
                        </div>
                        <div className='jobInfo-block'>
                            <div className='value'>{userInfo?.title??'-'}</div>
                            <div className='label'>职称</div>
                        </div>
                        <div className='jobInfo-block'>
                            <div className='value'>{userInfo?.jobTitle??'-'}</div>
                            <div className='label'>职务</div>
                        </div>
                    </div>
                    <div className='qualifi-info-title'><span>资质信息</span></div>
            
                    <div className='qualifi-info-detail'>
                        <div className='qualifi-info-list'>资格证号：<span>{userInfo?.qualificationCertificateNo??'-'}</span></div>
                        <div className='qualifi-info-list'>执业类别：<span>{userInfo?.practiceCate??'-'}</span></div>
                        <div className='qualifi-info-list'>执业证号：<span>{userInfo?.practiceCertificateNo??'-'}</span></div>
                        <div className='qualifi-info-list'>执业专业：<span>{userInfo?.major??'-'}</span></div>
                        <div className='qualifi-info-list'>医师级别：<span>{userInfo?.doctorLevel??'-'}</span></div>
                    </div>
                    <div className='attachment-title'><span>相关附件</span><a onClick={() => set_modalFormVisible(true)}>上传</a></div>
                    <div className='attachment-detail'>
                        {
                            userInfo?.attachments.map((a: any, index: number) => {
                                const isExpiring = isExpiringWithinHalfYear(a.expireDate);
                                return (
                                    <div className='attachment-detail-list' key={index}>
                                        {(a.activeDate&&a.expireDate)&&<div className={`dateTag ${a.validFlag ? '' : 'valid'} ${isExpiring ? 'expiring' : ''}`}><span>{`${a.activeDate}~${a.expireDate}`}</span></div>}
                                        <img src={require('../../../../static/fileIcon.png')} alt="" />
                                        <div className='attachment-detail-list-info'>
                                            <div className='attachment-list-name'>{a.fileName}</div>
                                            <div className='attachment-list-subText'>{a.description?a.description:'暂无附件说明'}</div>
                                        </div>
                                        <Dropdown trigger={['hover']} menu={{ items: drapDownItems(a) }}><span className='more'>...</span></Dropdown>
                                    </div>
                                );
                            })
                        }
                    </div>
                </div>
            </div>
        </KCIMPagecontainer>
    )
}
