/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-12-31 14:25:56
 * @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, arrayMoveImmutable, ProFormText, ProFormTextArea, useRefFunction } from '@ant-design/pro-components';
import ProForm, { ModalForm, ProFormCascader, ProFormCheckbox, ProFormDateRangePicker, ProFormDependency, ProFormDigit, ProFormRadio, ProFormSelect, ProFormSwitch } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Drawer, Input, message, Popconfirm, Popover, Switch, Tooltip } from 'antd';
import { Fragment, Key, useEffect, useRef, useState } from 'react';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';


import { editData, getDepartmentDataReq, getTableDataReq, reAuthData } from './service';

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




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




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

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

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

    const tableRef = useRef<ActionType>();
    const drawerTableRef = useRef<ActionType>();
    const [drawerTableData, set_drawerTableData] = useState<any[]>([]);
    const [ifeditQualifiInfo, set_ifeditQualifiInfo] = useState(false);

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

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

        },
        {
            title: '操作',
            key: 'option',
            width: 60,
            fixed: 'right',
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <a key={'detailBtn'} onClick={() => {
                        set_currentEditRow(record);
                        set_drawerVisible(true);
                    }}>详情</a>
                ]
            },
        },

    ];
    const drawerTablecolumns: ProColumns[] = [
        {
            title: '资质编码',
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualificationInfo: { code } } = record;
                return code;
            },
        },
        {
            title: '资质名称',
            renderText(text, record, index, action) {
                const { qualificationInfo: { name,standard } } = record;
                return <>{name}{(standard&&standard.length>0)&&<Tooltip title={`授权依据：${standard}`}><IconFont style={{marginLeft:10,fontSize:16,position:'relative',top:1}} type={'iconchakan'} /></Tooltip>}</>;
            },
        },
        {
            title: '授权期限',
            ellipsis: true,
            width:80,
            dataIndex: 'qualificationPeriod',
            renderText(text, record, index, action) {
                const result = authTimeType.filter((a) => a.value == text);
                if (result.length > 0) {
                    return result[0].label
                }
            },

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

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

    ]


    const getTableData = async (params: any) => {
        const { qualificationTypeCode } = params;
        const resp = await getTableDataReq(params);
        if (resp) {
            const data = (resp.list).map((a: any, index: number) => ({ id: index, ...a }));
            set_currentPageTableData(data);
            return {
                data,
                success: true
            }
        } else {
            return []
        }
    }


    const updateTable = async (formVal: any, type: 'EDIT' | 'AUTH') => {
        try {
            if (type == 'EDIT') {

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

            return true;

        } catch (error) {

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




    }

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

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

            </ModalForm>
        )
    }

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

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

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

    }

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

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

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

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

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

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


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

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

    useEffect(() => {
        if (currentEditRow) {
            set_drawerTableData([
                ...currentEditRow.applyList,
            ]);
        }
    }, [currentEditRow]);

    useEffect(() => {
        if (currentPageTableData && drawerVisible) {
            const needitem = currentPageTableData.filter((a) => a.userInfo.id == currentEditRow.userInfo.id);
        
            if (needitem.length > 0) {
                set_currentEditRow(needitem[0]);
            }

        }
    }, [currentPageTableData])

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

    return (
        <KCIMPagecontainer className='QualificationAuth' style={!isChildComponent ? {} : { border: 'none' }} title={false}>
            <Drawer destroyOnClose={true} className='doctorQualifiAuth-authDetailDrawer' width={1100}
                open={drawerVisible} headerStyle={{ display: 'none' }} bodyStyle={{ background: '#F5F7FA', padding: 16 }}
            >
                <div className='authDetailDrawer-topBar'>
                    <div className='authDetailDrawer-topBar-title'>
                        <div className='closeIcon' onClick={() => set_drawerVisible(false)}><IconFont  type={'iconquxiao'} /></div>{'授权详情'}
                    </div>
                    {/* <div className='btnGroup'>
                        <span onClick={() => set_drawerVisible(false)}>取消</span>
                        <span className='reject' onClick={() => updateTable(2)}>驳回</span>
                        <span className='commit' onClick={() => updateTable(1)}>通过</span>
                    </div> */}
                </div>
                <div className='authDetailDrawer-content'>
                    <div className='authDetailDrawer-info'>
                        <div className='avator'><img src={(currentEditRow?.userInfo?.avatarUrl)?currentEditRow?.userInfo?.avatarUrl:require('../../../../static/avatar.png')} alt="avator" /></div>
                        <div className='authDetailDrawer-info-detail'>
                            <div className='authDetailDrawer-info-title'>
                                {currentEditRow?.userInfo?.name}
                                <img style={{ width: 16, height: 16, marginLeft: 8 }} src={require(`../../../../static/${currentEditRow?.userInfo?.gender == '男' ? 'male' : 'female'}.png`)} alt="" />
                            </div>
                            <div className='authDetailDrawer-info-title-sub'>
                                工号：{currentEditRow?.userInfo?.id}<span style={{ padding: '0 8px' }}></span>
                                科室：{currentEditRow?.userInfo?.deptName}<span style={{ padding: '0 8px' }}></span>
                                职称：{currentEditRow?.userInfo?.jobTitle}<span style={{ padding: '0 8px' }}></span>
                                职务：{currentEditRow?.userInfo?.title}
                            </div>
                        </div>

                    </div>
                    <div className='authDetailDrawer-qualication-info'>
                        <div className='authDetailDrawer-qualication-info-title'>资质信息
                            {/* <span>
                                {!ifeditQualifiInfo && <a onClick={() => set_ifeditQualifiInfo(true)}>编辑</a>}
                                {ifeditQualifiInfo && <><a onClick={() => set_ifeditQualifiInfo(true)} style={{ paddingRight: 8 }}>取消</a><a onClick={() => set_ifeditQualifiInfo(true)}>保存</a></>}
                            </span> */}
                        </div>
                        {
                            !ifeditQualifiInfo && (<>
                                <div className='authDetailDrawer-qualication-info-tag-wrapper'>
                                    <div className='qualication-info-tag'>资质证号：<span>{currentEditRow?.userInfo?.qualificationCertificateNo}</span></div>
                                    <div className='qualication-info-tag'>执业类别：<span>{currentEditRow?.userInfo?.practiceCate}</span></div>
                                    <div className='qualication-info-tag'>执业证号：<span>{currentEditRow?.userInfo?.practiceCertificateNo}</span></div>
                                    <div className='qualication-info-tag'>执业专业：<span>{currentEditRow?.userInfo?.major}</span></div>
                                    <div className='qualication-info-tag'>医师级别：<span>{currentEditRow?.userInfo?.doctorLevel}</span></div>

                                </div>
                            </>)
                        }
                        {
                            ifeditQualifiInfo && (<>
                                <ProForm layout='vertical' submitter={false} grid>
                                    <ProFormText colProps={{ md: 12, xl: 8 }} label='资格证号：' />
                                    <ProFormText colProps={{ md: 12, xl: 8 }} label='执业类别：' />
                                    <ProFormText colProps={{ md: 12, xl: 8 }} label='执业证号：' />
                                    <ProFormText colProps={{ md: 12, xl: 8 }} label='执业专业：' />
                                    <ProFormText colProps={{ md: 12, xl: 8 }} label='医师级别：' />
                                </ProForm>
                            </>)
                        }


                        <div className='authDetailDrawer-qualication-info-certs'>
                            {
                                currentEditRow?.userInfo?.attachments?.map((item: any, index: number) => {
                                    return (
                                        <div key={index} className='qualificationInfo-fileItem'>
                                            <img src={require('../../../../static/fileIcon.png')} alt="" />
                                            <div className='qualificationInfo-fileItem-detail'>
                                                <div className='qualificationInfo-fileItem-detail-name'>{item.fileName}</div>
                                                <div className='qualificationInfo-fileItem-detail-sub'>{item.description}</div>
                                            </div>
                                            <Tooltip title='下载'>
                                                <a className='downloadBtn' href={item.url} target='_blank' ><IconFont style={{color:'#17181A'}} type={'iconxiazai'} /></a>
                                            </Tooltip>
                                        </div>
                                    )
                                })
                            }
                        </div>
                    </div>
                    <div className='authDetailDrawer-content-table'>
                        <div className='authDetailDrawer-content-table-title'>授权信息</div>
                        <KCIMTable
                            actionRef={drawerTableRef} columns={drawerTablecolumns as ProColumns[]} rowKey='id'
                            // request={(params) => getTableData(params)}
                            dataSource={drawerTableData}
                            tableAlertRender={false}
                            scroll={{ y: 361 }}
                        />
                    </div>

                </div>


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

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

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

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