/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-01-02 14:01:34
 * @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 } from '@ant-design/icons';
import { ActionType, ProFormDependency, ProFormInstance, ProFormText, ProFormSelect } from '@ant-design/pro-components';
import ProForm, { ModalForm, ProFormCheckbox, ProFormDateRangePicker, ProFormDigit, ProFormRadio, ProFormTextArea } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Drawer, Input, message, Popconfirm, Modal, Switch, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';

import 'moment/locale/zh-cn';


import { editData, getTableList } from './service';

import './style.less';

import { renameChildListToChildren } from '@/utils/tooljs';
import { useParams } from '@umijs/max';
import moment from 'moment';
import { authTimeType } from '@/constant';


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

const authTypeList = [
    { label: '长期授权', value: 1 },
    { label: '临时授权', value: 2 },
    { label: '单次授权', value: 3 }
]

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 QualificationApproval() {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const tableRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();
    const { type: roleType } = useParams();
    const [drawerVisible, set_drawerVisible] = useState(false);
    const [currentEditRow, set_currentEditRow] = useState<any>({ qualificationCode: '0' });

    const [actionType, set_actionType] = useState<'ADD' | 'EDIT' | 'DETAIL' | undefined>(undefined);
    const [deptOpinionText, set_deptOpinionText] = useState<string | undefined>(undefined);
    const [managerOpinionText, set_managerOpinionText] = useState<string | undefined>(undefined);
    const [masterOpinionText, set_masterOpinionText] = useState<string | undefined>(undefined);
    const [ifNeedMasterAudit, set_ifNeedMasterAudit] = useState(false);
    const [authTimerange, set_authTimerange] = useState<any[]>([]);
    const [authType, set_authType] = useState(1);
    const [isModalOpen, set_isModalOpen] = useState(false);
    const [batchAuthText, set_batchAuthText] = useState<string | undefined>(undefined);
    const [batchSelectRows, set_batchSelectRows] = useState<any[]>([]);
    const [batchQualificationPeriod, set_batchQualificationPeriod] = useState('1');
    const [batchAuthTimeRange, set_batchAuthTimeRange] = useState([`${moment().year()}-${moment().month() + 1}-${moment().date()}`]);
    const [batchIfNeedMasterAudit, set_batchIfNeedMasterAudit] = useState(false);



    const columns: ProColumns[] = [
        {
            title: '申请人',
            width: 90,
            ellipsis: true,
            renderText(text, record, index, action) {
                const { userInfo: { name } } = record;
                return name
            },
        },
        {
            title: '所在科室',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { userInfo: { deptName } } = record;
                return deptName
            },
        },
        {
            title: '资质名称',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualificationInfo: { name } } = record;
                return name
            },
        },
        {
            title: '资质编码',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualificationInfo: { code } } = record;
                return code
            },
        },
        {
            title: '资质分类',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualificationInfo: { qualificationTypeName } } = record;
                return qualificationTypeName
            },
        },
        {
            title: '申请日期',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { applyDate } = record;
                return applyDate
            },
        },
        {
            title: '操作',
            key: 'option',
            width: 60,
            fixed: 'right',
            valueType: 'option',
            render: (_: any, record: any) => {
                const { code } = record;
                return <a onClick={() => { set_currentEditRow(record); set_drawerVisible(true) }}>审批</a>
            },
        },

    ]


    const getTableData = async (params: any) => {
        const { role } = params;
        if (!role) {
            return {
                success: false
            }
        }
        const resp = await getTableList({ ...params });
        if (resp) {
            return {
                data: resp.list,
                success: true,
                total: resp.totalCount,
                pageSize: resp.pageSize,
                totalPage: resp.totalPage,
            }
        }
        return []
    }



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

        let result: any = {
            role: roleType,
            auditType: type,
            auditInfo: [{
                id: currentEditRow?.id,
            }]
        }

        if (roleType == '1') {

            result = {
                ...result,
                auditInfo: [{
                    ...result.auditInfo[0],
                    deptOpinion: deptOpinionText,
                }]
            }
        }
        if (roleType == '2') {

            result = {
                ...result,
                auditInfo: [{
                    ...result.auditInfo[0],
                    qualificationPeriod: authType,
                    beginDate: authTimerange[0],
                    endDate: authTimerange[1],
                    managerOpinion: managerOpinionText,
                    needMasterAudit: ifNeedMasterAudit ? 1 : 0
                }]
            }
        }
        if (roleType == '3') {

            result = {
                ...result,
                auditInfo: [{
                    ...result.auditInfo[0],
                    masterOpinion: masterOpinionText,
                }]
            }
        }

        const resp = await editData(result);
        if (resp) {
            set_drawerVisible(false);
            message.success('操作成功！');
            tableRef.current?.reload();
        }


        return true;

    }


    const tableDataSearchHandle = (paramName: string) => {

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

    }

    const cancelBatchAuthHandle = ()=>{
        set_batchSelectRows([]);
    }

    const batchAuthHandle = () => {
        set_isModalOpen(true);
    }

    const handleOk = async (type: 1 | 2) => {
        const result = roleType == '2' ? {
            role: roleType,
            auditType: type,
            auditInfo: batchSelectRows.map((a) => ({
                id: a.id,
                managerOpinion: batchAuthText,
                qualificationPeriod: batchQualificationPeriod,
                beginDate: batchAuthTimeRange[0],
                endDate: batchAuthTimeRange[1],
                needMasterAudit: batchIfNeedMasterAudit ? 1 : 0
            }))
        } : {
            role: roleType,
            auditType: type,
            auditInfo: batchSelectRows.map((a) => ({
                id: a.id,
                [`${roleType == '1' ? 'deptOpinion' : 'masterOpinion'}`]: batchAuthText
            }))
        }
        const resp = await editData(result);
        if (resp) {
            set_batchSelectRows([]);
            message.success('批量操作成功！');
            tableRef.current?.reload();
        }
    }

    useEffect(() => {
        if (roleType) {
            set_tableDataFilterParams({ ...tableDataFilterParams, current: 1, role: roleType });
            set_currentEditRow(undefined);
            set_deptOpinionText(undefined);
            set_managerOpinionText(undefined);
            set_masterOpinionText(undefined);
            set_ifNeedMasterAudit(false);
            set_authTimerange([]);
            set_authType(1);
            set_batchAuthText(undefined);
            set_batchSelectRows([]);
        }
    }, [roleType]);

    useEffect(() => {
        if (currentEditRow) {

            set_deptOpinionText(currentEditRow.deptOpinion);
            set_managerOpinionText(currentEditRow.managerOpinion);
            set_authTimerange([currentEditRow.beginDate, currentEditRow.endDate]);
            set_authType(currentEditRow.qualificationPeriod ? currentEditRow.qualificationPeriod : 1);
        }
    }, [currentEditRow]);

    return (
        <KCIMPagecontainer className='QualificationApproval' title={false}>
            <Modal width={352} title={roleType == '2' ? '批量审批' : '审批意见'} open={isModalOpen} destroyOnClose
                onCancel={() => set_isModalOpen(false)}
                footer={[
                    <span style={{
                        display: 'inline-block', width: 56, height: 24, lineHeight: '24px', textAlign: 'center', fontSize: 14,
                        color: '#17181A', border: '1px solid #DAE2F2', borderRadius: 4, background: '#FAFCFF', cursor: 'pointer'
                    }} onClick={() => { set_isModalOpen(false) }}>取消</span>,
                    <span style={{
                        display: 'inline-block', width: 56, height: 24, lineHeight: '24px', textAlign: 'center', fontSize: 14,
                        color: '#fff', borderRadius: 4, background: '#FF4D6A', marginLeft: 8, cursor: 'pointer'
                    }} onClick={() => { handleOk(2); set_isModalOpen(false) }}>驳回</span>,
                    <span style={{
                        display: 'inline-block', width: 56, height: 24, lineHeight: '24px', textAlign: 'center', fontSize: 14,
                        color: '#fff', borderRadius: 4, background: '#3377FF', marginLeft: 8, cursor: 'pointer'
                    }} onClick={() => { handleOk(1); set_isModalOpen(false) }}>通过</span>
                ]}
            >
                <ProForm submitter={false}>
                    {
                        roleType == '2' && (<>
                            <ProFormRadio.Group label='授权期限：' options={authTimeType}
                                fieldProps={{
                                    defaultValue: 1,
                                    onChange(e) {
                                        set_batchQualificationPeriod(e.target.value);
                                    },
                                }} />
                            <ProFormDateRangePicker label='授权时间：' fieldProps={{
                                defaultValue: [moment().startOf('days'), moment().endOf('days')],
                                onChange(values, formatString) {
                                    set_batchAuthTimeRange(formatString);
                                },
                            }} />

                        </>)
                    }
                    <ProFormTextArea label='审批意见：' fieldProps={{
                        autoSize: { minRows: 6 },
                        onChange: (e) => {
                            set_batchAuthText(e.target.value);
                        }
                    }} />
                    {roleType != '3' && (
                        <>
                            <ProFormCheckbox noStyle fieldProps={{

                                style: { marginRight: 4, marginBottom: 16 },
                                onChange(e) {
                                    set_batchIfNeedMasterAudit(e.target.checked)
                                },
                            }} />
                            提交院领导审核
                        </>
                    )}
                </ProForm>

            </Modal>
            <Drawer destroyOnClose={true} className='applyDrawer' width={1110}
                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>{'审批'}
                    </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='drawer-content'>
                    <div className='personInfo'>
                        <div className='avator'><img src={(currentEditRow?.userInfo?.avatarUrl)?currentEditRow?.userInfo?.avatarUrl:require('../../../../static/avatar.png')} alt="avator" /></div>
                        <div className='personInfo-detail'>
                            <div className='name'>{currentEditRow?.userInfo?.name}<img src={require(`../../../../static/${currentEditRow?.userInfo?.gender == '男' ? 'male' : 'female'}.png`)} /></div>
                            <div className='personInfo-detail-sub'>
                                工号：{currentEditRow?.userInfo?.id??'-'}<span style={{ padding: 8 }} />
                                科室：{currentEditRow?.userInfo?.deptName??'-'}<span style={{ padding: 8 }} />
                                职称：{currentEditRow?.userInfo?.title??'-'}<span style={{ padding: 8 }} />
                                职务：{currentEditRow?.userInfo?.jobTitle??'-'}
                            </div>
                        </div>
                    </div>
                    <div className='qualificationInfo'>
                        <div className='qualificationInfo-title'>资质信息</div>
                        <div className='qualificationInfo-tagWrapper'>
                            <div className='qualificationInfo-tagWrapper-tag'>资格证号：<span>{currentEditRow?.userInfo?.qualificationCertificateNo??'-'}</span></div>
                            <div className='qualificationInfo-tagWrapper-tag'>执业类别：<span>{currentEditRow?.userInfo?.practiceCate??'-'}</span></div>
                            <div className='qualificationInfo-tagWrapper-tag'>执业证号：<span>{currentEditRow?.userInfo?.practiceCertificateNo??'-'}</span></div>
                            <div className='qualificationInfo-tagWrapper-tag'>执业专业：<span>{currentEditRow?.userInfo?.major??'-'}</span></div>
                            <div className='qualificationInfo-tagWrapper-tag'>医师级别：<span>{currentEditRow?.userInfo?.doctorLevel??'-'}</span></div>
                        </div>
                        <div className='qualificationInfo-fileWrapper'>
                            {
                                currentEditRow?.userAttachment?.map((item: any, index: number) => {
                                    return (
                                        <div key={index} className='qualificationInfo-fileItem'>
                                            {(item.activeDate&&item.expireDate)&&<div className={item.validFlag?'dateTag':'dateTag valid'}><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?item.description:'暂无附件说明'}</div>
                                            </div>
                                            <Tooltip title='下载'>
                                                <div className='downloadBtn' ><IconFont type={'iconxiazai'} /></div>
                                            </Tooltip>
                                        </div>
                                    )
                                })
                            }
                        </div>


                    </div>
                    {
                        currentEditRow && (
                            <div className='qualificationInfo-apply'>
                                <div className='editContent-header-title'>
                                    <>{currentEditRow?.qualificationInfo?.name}({currentEditRow?.qualificationInfo?.code})</>
                                    <div>
                                        {
                                            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',
                                                    alignItems: 'center', background: '#E8FCF6', borderRadius: 4, fontSize: 12, color: '#009966'
                                                }}>{
                                                        currentEditRow?.qualificationInfo?.qualificationTypeName
                                                    }</span>
                                            )
                                        }
                                    </div>

                                </div>
                                <div className='editContent-header-title-sub'>
                                    <div>资质编码：<span>{currentEditRow?.qualificationInfo?.code??'-'}</span></div>
                                    <div>申请日期：<span>{currentEditRow?.applyDate??'-'}</span></div>
                                </div>
                                {currentEditRow?.qualificationInfo?.standard.length > 0 && <div className='editContent-header-title-detail'><span>授权依据：</span><div>{currentEditRow?.qualificationInfo?.standard}</div></div>}
                                {(currentEditRow?.applyMemo?.length > 0) && <div className='editContent-header-title-detail'>
                                    <span>备注：</span><div>{currentEditRow?.applyMemo}</div>
                                </div>}
                                {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>
                        )
                    }

                    <div className='deptOpinion'>
                        {roleType != '1' && <div className='deptOpinion-title'>科主任意见</div>}
                        {roleType == '1' && <div className='deptOpinion-title'>审批意见</div>}
                        {roleType == '1' && <ProFormTextArea fieldProps={{
                            onChange: (e) => {
                                set_deptOpinionText(e.target.value);
                            }
                        }} noStyle placeholder={'请输入审批意见'} />}
                        {roleType != '1' && <div className='deptOpinion-detail'>{deptOpinionText}</div>}
                    </div>
                    {
                        roleType != '1' && (
                            <div className='deptOpinion'>
                                {
                                    roleType == '3' && (
                                        <>
                                            <div className='deptOpinion-title'>医务部意见</div>
                                            <div className='time-info'>
                                                <div className='info-tag'>
                                                    授权期限：<span>{authTypeList[authType - 1].label}</span>
                                                </div>
                                                <div className='info-tag'>
                                                    授权时间：<span>{`${authTimerange[0]}至${authTimerange[1]}`}</span>
                                                </div>
                                            </div>
                                            <div className='manageOpinion-detail'>
                                                <span>审批意见：</span>
                                                <div>{managerOpinionText}</div>
                                            </div>
                                        </>
                                    )
                                }

                                {
                                    roleType == '2' && (
                                        <>
                                            <div className='deptOpinion-title'>审批信息</div>
                                            <div className='time-wrapper'>
                                                <div className='type'>
                                                    <span>授权期限：</span>
                                                    <ProFormRadio.Group noStyle options={authTypeList} fieldProps={{
                                                        defaultValue: 1,
                                                        onChange(e) {
                                                            set_authType(e.target.value);
                                                        },
                                                    }} />
                                                </div>
                                                <div className='time'>
                                                    <span>授权时间：</span>
                                                    <ProFormDateRangePicker noStyle fieldProps={{
                                                        defaultValue: [moment().startOf("day"), moment().endOf("day")],
                                                        // value:[moment(authTimerange[0],'YYYY-MM-DD'),moment(authTimerange[0],'YYYY-MM-DD')],
                                                        onChange(values, formatString) {
                                                            set_authTimerange(formatString)
                                                        },
                                                    }} />
                                                </div>
                                            </div>
                                            <div style={{ height: 14, lineHeight: '14px', fontSize: 14, color: '#17181A', marginBottom: 8 }}>审批意见：</div>
                                            <ProFormTextArea fieldProps={{
                                                onChange: (e) => {
                                                    set_managerOpinionText(e.target.value);
                                                }
                                            }} noStyle placeholder={'请输入'} />

                                            <div style={{ marginTop: 17 }}>
                                                <ProFormCheckbox noStyle fieldProps={{
                                                    style: { marginRight: 4 },
                                                    onChange(e) {
                                                        set_ifNeedMasterAudit(e.target.checked)
                                                    },
                                                }} />提交院领导审核
                                            </div>
                                        </>
                                    )
                                }


                            </div>
                        )
                    }
                    {
                        roleType != '1' && roleType != '2' && (
                            <div className='deptOpinion'>
                                <div className='deptOpinion-title'>审批意见</div>
                                <ProFormTextArea fieldProps={{
                                    onChange: (e) => {
                                        set_masterOpinionText(e.target.value);
                                    }
                                }} noStyle placeholder={'请输入审批意见'} />
                            </div>
                        )
                    }
                </div>
            </Drawer>




            <div className='pageContent'>
                <div className='toolBar'>
                    <div className='filter'>
                        <div className='filterItem'>
                            <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                            <Input placeholder={'申请人、资质分类、资质名称'} allowClear autoComplete='off'
                                style={{ width: 250 }}
                                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'>
                        {batchSelectRows.length > 0 && <span className='export' onClick={() => cancelBatchAuthHandle()}>取消选择</span>}
                        {batchSelectRows.length > 0 && <span className='add' onClick={() => batchAuthHandle()}>批量审批({batchSelectRows.length})</span>}
                    </div>
                </div>
                <KCIMTable columns={columns as ProColumns[]} scroll={{ y: 'calc(100vh - 232px)' }}
                tableAlertRender={false}
                    rowSelection={{
                        selectedRowKeys: batchSelectRows.map((a) => a.id),
                        onChange(selectedRowKeys, selectedRows, info) {
                            set_batchSelectRows(selectedRows);
                        },
                    }}
                    actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params) => getTableData(params)}
                />
            </div>
        </KCIMPagecontainer>
    )
}
