/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-08-07 17:22:43
 * @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, ProFormDependency, ProFormInstance, ProFormText, ProFormSelect } from '@ant-design/pro-components';
import { ModalForm, ProFormDigit, ProFormTextArea } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Drawer, Input, message, Popconfirm, Popover, Switch, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';

import 'moment/locale/zh-cn';


import { addData, delData, editData, getTableList, uploadFilesReq, withdrawReq } from './service';

import './style.less';


import QualifiDicMana from '@/pages/qualificationMana/qualifiDicMana';
import Dragger from 'antd/es/upload/Dragger';
import { useModel } from '@umijs/max';
import { getDicDataBySysId } from '@/services/getDic';
import { KcimCenterSysId } from '@/constant';


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

export const applyStatus = [
    { label: '草稿', value: 1 },
    { label: '待科主任审核', value: 2 },
    { label: '待医务部审核', value: 3 },
    { label: '待院长审核', value: 4 },
    { label: '审核通过', value: 5 },
    { label: '驳回', value: 6 }
]

export const searchTree = (tree: any[], searchTerm: string) => {
    const searchTermLower = searchTerm.toLowerCase();

    function searchNode(node: any) {
        const matchedChildren: any[] = [];

        if (node.children && node.children.length > 0) {
            node.children.forEach((child: any) => {
                const matchedChild = searchNode(child);
                if (matchedChild) {
                    matchedChildren.push(matchedChild);
                }
            });
        }

        if (node.responsibilityName.toLowerCase().includes(searchTermLower) || (node.responsibilityCode && node.responsibilityCode.toLowerCase().includes(searchTermLower))) {
            return {
                ...node,
                children: matchedChildren.length > 0 ? matchedChildren : node.children
            };
        } else if (matchedChildren.length > 0) {
            return {
                ...node,
                children: matchedChildren
            };
        }

        return null;
    }

    return tree.map(rootNode => searchNode(rootNode)).filter(node => node !== null);
}


export default function MyApplication() {
    const { initialState, setInitialState } = useModel('@@initialState');
    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const tableRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();
    const [drawerVisible, set_drawerVisible] = useState(false);
    const [currentEditRow, set_currentEditRow] = useState<any>({ qualificationCode: '0' });
    const [checkedDrawerTableRows, set_checkedDrawerTableRows] = useState<any[]>([]);
    const [drawerTextAreaVal, set_drawerTextAreaVal] = useState<string | undefined>(undefined);
    const [drawerUploadFiles, set_drawerUploadFiles] = useState<any[]>([]);
    const [actionType, set_actionType] = useState<'ADD' | 'EDIT' | 'DETAIL' | undefined>(undefined);
    const [operationLevel, set_operationLevel] = useState<any[]>([]);
    const columns: ProColumns[] = [
        {
            title: '资质编码',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualificationInfo: { code, name } } = record;
                return code
            },
        },
        {
            title: '资质名称',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualificationInfo: { code, name } } = record;
                return name
            },
        },
        {
            title: '资质分类',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualificationInfo: { qualificationTypeName } } = record;
                return qualificationTypeName
            },
        },
        {
            title: '申请日期',
            ellipsis: true,
            dataIndex: 'applyDate',
        },
        {
            title: '准入日期',
            ellipsis: true,
            dataIndex: 'beginDate',
        },
        {
            title: '状态',
            ellipsis: true,
            dataIndex: 'applyStatus',
            renderText(num) {
                let color = '';
                if (num == 1) color = '#C3CAD9';
                if (num == 2 || num == 3 || num == 4) color = '#FFB54D';
                if (num == 5) color = '#00CC99';
                if (num == 6) color = '#FF4D6A';
                const needitem = applyStatus.filter((a) => a.value == num);
                if (needitem.length > 0) {
                    return <span style={{ fontSize: 14, fontWeight: 'bolder', color: '#17181A' }}>
                        <i style={{ display: 'inline-block', width: 8, height: 8, borderRadius: '50%', background: `${color}`, marginRight: 4 }}></i>{needitem[0].label}
                    </span>
                }

            },
        },
        {
            title: '操作',
            key: 'option',
            width: 120,
            fixed: 'right',
            valueType: 'option',
            render: (_: any, record: any) => {
                const { applyStatus } = record;
                if (applyStatus == 1) {
                    return [
                        <a key={'edit'} onClick={() => editRowHandle(record)}>编辑</a>,
                        <Popconfirm
                            title="是否确认删除？"
                            key="del"
                            onConfirm={() => delTableData(record)}
                        >
                            <a>删除</a>
                        </Popconfirm>,
                    ]
                }
                if (applyStatus == 2) {
                    return [
                        <a key={'detail'} onClick={() => { set_actionType('DETAIL'); set_currentEditRow(record) }}>详情</a>, <a key={'back'} onClick={() => rebackHandle(record.id)}>撤回</a>
                    ]
                }
                return [
                    <a key={'detail'} onClick={() => { set_actionType('DETAIL'); set_currentEditRow(record) }}>详情</a>
                ]

            },
        },

    ];

    const editRowHandle = (record: any) => {
        set_currentEditRow(record);
        set_drawerTextAreaVal(record.applyMemo);
        set_drawerUploadFiles(record.applyAttachment);
        set_actionType('EDIT');
    }


    const getTableData = async (params: any) => {
        const resp = await getTableList({ ...params });
        if (resp) {
            return {
                data: resp.list,
                success: true,
                total: resp.totalCount,
                pageSize: resp.pageSize,
                totalPage: resp.totalPage,
            }
        }
        return []
        // return {
        //     success: true,
        //     data: [
        //         {
        //             "id": 33,
        //             "qualificationCode": "决称表多需成最",
        //             "userid": 14,
        //             "qualificationPeriod": 48,
        //             "applyDate": "2006-07-16",
        //             "applyMemo": "共同",
        //             "beginDate": "1977-11-21",
        //             "endDate": "2019-11-16",
        //             "deptOpinion": "了",
        //             "managerOpinion": "同",
        //             "masterOpinion": "层",
        //             "applyStatus": 1,
        //             "userInfo": {
        //                 "name": "崔洋",
        //                 "account": "养干位等华声斯说权为维而积",
        //                 "gender": "女",
        //                 "deptName": "",
        //                 "title": "及四得正有理",
        //                 "jobTitle": "作反",
        //                 "qualificationCertificateNo": "",
        //                 "practiceCertificateNo": "子清",
        //                 "doctorLevel": "县状",
        //                 "practiceCate": "听产研中收目青划打又意图织根油光长还",
        //                 "major": "小件"
        //             },
        //             "userAttachment": [
        //                 {
        //                     "fileName": "学县八达划门位易积十空支院他因身劳出严厂还应算们思生今表张第品克少",
        //                     "url": "http://vbeekmyuo.tc/jqvuw",
        //                     "description": "七教备回自线色同严结几基想部。劳放次音们或形月质外观已先象其类。实通他工外强形铁美见北点及种百命车。向下质置关小么但技响我备。"
        //                 }
        //             ],
        //             "quanlificationInfo": {
        //                 "code": 30,
        //                 "name": "姜军",
        //                 "qualificationTypeName": "力起又器党价志",
        //                 "standard": "",
        //                 "techFlag": 69,
        //                 "operationFlag": 99,
        //                 "operationLevel": "通地验但后把石"
        //             },
        //             "applyAttachment": [
        //                 {
        //                     "fileName": "该相从今史斯两老对调持导属才百加亲放采完门史江据律风线着始易命铁间观",
        //                     "url": "http://eoeaipwg.bi/lqgtt"
        //                 }
        //             ]
        //         }
        //     ]
        // }
    }

    const rebackHandle = async (id: number) => {
        const resp = await withdrawReq(id);
        if (resp) {
            message.success('撤回成功！');
            tableRef.current?.reload();
        }
    }

    const delTableData = async (record: any) => {
        const resp = await delData(record.id);
        if (resp) {
            message.success('操作成功！');
            tableRef.current?.reload();
            // message.success('操作成功!');
        }
    }

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

    const updateTable = async (type?: 1 | 2) => {

        if (actionType == 'ADD') {

            const result = {
                addType: type,
                applyMemo: drawerTextAreaVal,
                qualificationList: checkedDrawerTableRows.map((a) => ({ code: a.code })),
                applyAttachment: drawerUploadFiles.map((a) => ({ fileName: a.fileName, url: a.url }))
            }
            const resp = await addData(result);
            if (resp) {
                set_drawerVisible(false);
                tableRef.current?.reload();
            }
        }
        if (actionType == 'EDIT') {
            const result = {
                id: currentEditRow.id,
                // addType: 2,
                applyMemo: drawerTextAreaVal,
                // qualificationList: checkedDrawerTableRows.map((a) => ({ code: a.code })),
                applyAttachment: drawerUploadFiles.map((a) => ({ fileName: a.fileName, url: a.url }))
            }
            const resp = await editData(result, type as number);
            if (resp) {
                message.success('操作成功！');
                set_drawerVisible(false);
                tableRef.current?.reload();
            }

        }
        return {
            success: false
        };

    }

    const tableDataSearchHandle = (paramName: string) => {

        set_tableDataFilterParams({
            ...tableDataFilterParams,
            current: 1,
            [`${paramName}`]: tableDataSearchKeywords
        })

    }

    useEffect(() => {
        if (actionType) {
            set_drawerVisible(true)
        } else {
            set_drawerVisible(false);
            set_currentEditRow({ qualificationCode: '0' });

        }
    }, [actionType]);

    useEffect(() => {
        if (!drawerVisible) {
            set_drawerTextAreaVal(undefined);
            set_drawerUploadFiles([]);
            set_checkedDrawerTableRows([]);
        }
    }, [drawerVisible]);

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

    return (
        <KCIMPagecontainer className='MyApplication' title={false}>
            <Drawer destroyOnClose={true} className='MyApplication-applyDrawer' width={actionType == 'ADD' ? 1160 : actionType == 'EDIT' ? 600 : 750}
                open={drawerVisible} headerStyle={{ display: 'none' }} bodyStyle={{ background: '#F5F7FA', padding: 16 }}
                afterOpenChange={(bool) => { !bool && set_actionType(undefined) }}
            >
                <div className='applyDrawer-topBar'>
                    <div className='applyDrawer-topBar-title'>
                        <div className='closeIcon' onClick={() => set_drawerVisible(false)}><IconFont type={'iconquxiao'} /></div>{actionType == 'ADD' ? '新增' : actionType == 'DETAIL' ? '详情' : '编辑'}
                    </div>
                    {
                        actionType != 'DETAIL' && (
                            <div className='btnGroup'>
                                <span onClick={() => set_drawerVisible(false)}>取消</span>
                                <span onClick={() => updateTable(1)}>暂存</span>
                                <span className='commit' onClick={() => updateTable(2)}>提交{checkedDrawerTableRows.length > 0 ? `(${checkedDrawerTableRows.length})` : ''}</span>
                            </div>
                        )
                    }
                </div>
                <div className='content' style={actionType == 'EDIT' || actionType == 'DETAIL' ? { flexDirection: 'column', justifyContent: 'flex-start' } : {}}>
                    {
                        (actionType == 'EDIT' || actionType == 'DETAIL') && (
                            <div className='editContent-header'>
                                <div className='editContent-header-title'>
                                    {currentEditRow?.qualificationInfo?.name}
                                    {
                                        currentEditRow?.qualificationInfo?.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?.qualificationInfo?.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?.qualificationInfo?.operationLevelCode)).length > 0 ? (operationLevel.filter((a) => a.value == currentEditRow?.qualificationInfo?.operationLevelCode))[0].name : ''
                                                }</span>
                                        )
                                    }
                                </div>
                                <div className='editContent-header-title-sub'>
                                    资质编码：{currentEditRow?.qualificationInfo.code ?? '-'}<span style={{ padding: 8 }}></span>资质分类：{currentEditRow?.qualificationInfo.qualificationTypeName ?? '-'}
                                    {actionType == 'DETAIL' && (<><span style={{ padding: 8 }}></span>申请日期：{currentEditRow?.applyDate ?? '-'}</>)}
                                </div>
                                {currentEditRow?.qualificationInfo.standard.length > 0 && <div className='editContent-header-title-authStandard'>{currentEditRow?.qualificationInfo.standard}</div>}


                            </div>
                        )
                    }
                    {
                        ((actionType == 'EDIT' || actionType == 'DETAIL')&&(currentEditRow?.applyMemo?.length > 0||currentEditRow?.applyAttachment?.length > 0)) && (
                            <div className='apply-info' >
                                <div className='apply-info-title'>申请信息</div>
                                {(currentEditRow?.applyMemo?.length > 0 && actionType == 'DETAIL') &&(
                                    <div className='apply-info-detail'>
                                        <div className='apply-info-detail-value'><span>备注：</span><div>{currentEditRow?.applyMemo}</div></div>
                                    </div>
                                )}
                                {actionType == 'DETAIL' && (currentEditRow?.applyAttachment?.length > 0) && <div className='appendix'>
                                    附件：{currentEditRow?.applyAttachment.map((a: any, index: number) => (<span key={index}><IconFont type={'iconfujian'} /><a href={a.url} target='_blank'>{a.fileName}</a></span>))}
                                </div>}
                            </div>
                        )
                    }

                    {
                        (actionType == 'DETAIL' && currentEditRow?.deptOpinion) && (
                            <div className='deptOpinion'>
                                <div className='deptOpinion-title'>科主任意见</div>
                                <div className='deptOpinion-detail'>{currentEditRow?.deptOpinion}</div>
                            </div>
                        )
                    }
                    {
                        (actionType == 'DETAIL' && currentEditRow?.managerOpinion) && (
                            <div className='managerOpinion'>
                                <div className='managerOpinion-title'>医务部意见</div>
                                <div className='managerOpinion-info'>授权期限：<span style={{ display: 'inline-block', marginRight: 200 }}>{currentEditRow?.qualificationPeriod == 1 ? '长期授权' : currentEditRow?.qualificationPeriod == 2 ? '临时授权' : '单次授权'}</span>授权时间：<span>{currentEditRow?.beginDate}至{currentEditRow?.endDate}</span></div>
                                <div className='managerOpinion-detail'><i>审批意见：</i><span>{currentEditRow?.managerOpinion}</span></div>
                            </div>
                        )
                    }
                    {
                        (actionType == 'DETAIL' && currentEditRow?.masterOpinion) && (
                            <div className='masterOpinion'>
                                <div className='masterOpinion-title'>院领导意见</div>
                                <div className='masterOpinion-detail'>{currentEditRow?.masterOpinion}</div>
                            </div>
                        )
                    }
                    {
                        (actionType == 'DETAIL' && currentEditRow?.applyStatus == 2) && (
                            <div className='detail-noAuthRecord'>
                                <img src={require('../../../../static/empty.png')} alt="" />
                                <div className='detail-noAuthRecord-title'>暂无内容</div>
                                <div className='detail-noAuthRecord-title-sub'>请耐心等待科主任审核</div>
                                <div className='backBtn' onClick={() => set_drawerVisible(false)}>返回</div>
                            </div>
                        )
                    }
                    {
                        actionType == 'ADD' && (
                            <div className='applyDrawer-left'>
                                <div className='applyDrawer-left-title'>资质字典</div>
                                <QualifiDicMana isChildComponent={true}
                                    qualifiCode={currentEditRow.qualificationCode}
                                    onTableSelectChange={(_, rows) => set_checkedDrawerTableRows([...rows])}
                                />
                            </div>
                        )
                    }

                    {
                        actionType != 'DETAIL' && (
                            <div className='applyDrawer-right' style={actionType == 'EDIT' ? { width: '100%' } : {}}>
                                <div className='applyDrawer-right-title'>申请信息</div>
                                <div className='applyDrawer-right-textarealable'>备注说明：</div>
                                <ProFormTextArea noStyle fieldProps={{ defaultValue: drawerTextAreaVal, style: { resize: 'none', height: 160, marginBottom: 16 }, onChange: (e) => { set_drawerTextAreaVal(e.target.value) } }} />
                                <div className='applyDrawer-right-textarealable'>上传附件：</div>
                                <div className='uploaderWrapper' style={{ height: 140 }}>
                                    <Dragger
                                        multiple
                                        action={'/gateway/centerSys/api/upload'}
                                        headers={{ token: initialState?.userData.token as string }}
                                        defaultFileList={[...(drawerUploadFiles.map((a, index) => ({ uid: `${index}`, name: a.fileName, url: a.url, status: 'done' })))] as any}
                                        onChange={(info) => {
                                            const { status, name } = info.file;
                                            if (status !== 'uploading') {
                                                console.log(info.file, info.fileList);
                                            }
                                            if (status == 'removed') {
                                                const temp = [...drawerUploadFiles];
                                                const result = temp.filter((a) => a.fileName != name);

                                                set_drawerUploadFiles([...result]);
                                            }
                                            if (status === 'done') {
                                                console.log('done');
                                                const { name, response: { data: { downUrl } } } = info.file;
                                                set_drawerUploadFiles([...drawerUploadFiles, { fileName: name, url: downUrl }]);
                                            } else if (status === 'error') {
                                                message.error(`${info.file.name} file upload failed.`);
                                            }
                                        }}
                                    >
                                        <p className="ant-upload-drag-icon">
                                            <InboxOutlined style={{ fontSize: 50, color: '#3377FF', marginBottom: 16 }} />
                                        </p>
                                        <p className="ant-upload-text">点击或将文件拖拽到这里上传</p>
                                    </Dragger>
                                </div>

                            </div>
                        )
                    }
                </div>
            </Drawer>

            <div style={{ padding: 16, background: '#fff', borderRadius: 4 }}>
                <div className='toolBar'>
                    <div className='filter'>
                        <div className='filterItem'>
                            <span className='label' style={{ whiteSpace: 'nowrap' }}> 当前状态：</span>
                            <ProFormSelect noStyle placeholder={'请选择'}
                                style={{ marginRight: 16, width: 160 }}
                                options={applyStatus}
                                fieldProps={{
                                    onChange(value, option) {
                                        set_tableDataFilterParams({ ...tableDataFilterParams, current: 1, applyStatus: value })
                                    },
                                }}
                            />
                        </div>
                        <div className='filterItem'>
                            <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                            <Input placeholder={'资质分类、资质名称'} allowClear autoComplete='off'
                                suffix={
                                    <IconFont type="iconsousuo" style={{ color: '#99A6BF' }} onClick={() => tableDataSearchHandle('queryCondition')} />
                                }
                                onChange={(e) => {
                                    set_tableDataSearchKeywords(e.target.value);
                                    if (e.target.value.length == 0) {
                                        set_tableDataFilterParams({
                                            ...tableDataFilterParams,
                                            current: 1,
                                            queryCondition: ''
                                        });
                                    }
                                }}
                                onPressEnter={(e) => {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        current: 1,
                                        queryCondition: (e.target as HTMLInputElement).value
                                    });
                                }}

                            />
                        </div>
                    </div>
                    <div className='btnGroup'>
                        <a className='add' onClick={() => { set_actionType('ADD') }}>新增</a>
                    </div>
                </div>
                <KCIMTable columns={columns as ProColumns[]} scroll={{ y: 'calc(100vh - 232px)' }} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params) => getTableData(params)} />
            </div>
        </KCIMPagecontainer>
    )
}
