/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-12-31 13:58: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 } 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 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 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 updateTable = async (formVal: any, type: 'ADD' | 'EDIT') => {
        try {
            const { files, memo, id } = formVal;
            let result = {};
            if (files[0].response) {
                const { name, response: { data: { downUrl } } } = files[0];
                result = {
                    id: type == 'EDIT' ? id : null,
                    userId: userInfo.id,
                    fileName: name,
                    url: downUrl,
                    description: memo
                };
            } else {
                const { name ,url} = files[0];
                result = {
                    id: type == 'EDIT' ? id : null,
                    userId: userInfo.id,
                    fileName: name,
                    url: url,
                    description: memo
                };
            }


            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();
        }
    }, [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
                } : {}}

                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
                    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 } = info.file;
                        //     if (status !== 'uploading') {
                        //         console.log(info.file, info.fileList);
                        //     }
                        //     if (status === 'done') {

                        //         message.success(`${info.file.name} 文件上传成功。`);

                        //     } else if (status === 'error') {
                        //         message.error(`${info.file.name} 文件上传失败。`);
                        //     }
                        // },
                        // onDrop(e) {
                        //     console.log('拖拽上传的文件:', e.dataTransfer.files);
                        // },
                    }}
                />
                <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'>
                            {
                                currentEditRow?.applyList?.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.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 - 230px)` }}
                            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={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?.id}</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) => (
                                <div className='attachment-detail-list' key={index}>
                                    <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}</div>
                                    </div>
                                    <Dropdown trigger={['hover']} menu={{ items: drapDownItems(a) }}><span className='more'>...</span></Dropdown>
                                </div>
                            ))
                        }
                    </div>
                </div>
            </div>
        </KCIMPagecontainer>
    )
}
