/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-12-31 13:53:16
 * @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, ProFormInstance, ProFormRadio, ProFormSelect, ProFormSwitch } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Alert, Drawer, Input, message } from 'antd';
import { Key, useEffect, useRef, useState } from 'react';



import { batchAuthDataCheck, editData, getLeftDataReq, 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 DoctorSelection from './DoctorSelection';
import { sparse } from 'mathjs';



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




export default function QualificationBatchAuth({ isChildComponent = false, qualifiCode, onTableSelectChange, defaultSelectedKeys }: {
    isChildComponent: boolean, qualifiCode: string, onTableSelectChange?: (selectedRowKeys: any[], selectedRows: any[], info: any) => void,
    defaultSelectedKeys?: Key[]
}) {
    const formRef = useRef<ProFormInstance>();
    const drawerFormRef = useRef<ProFormInstance>();
    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const [dataSource, set_dataSource] = useState<any[]>([]);
    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 [currentSelectedLeftRows, set_currentSelectedLeftRows] = useState<any[]>([]);
    const [currentSelectedTableRows, set_currentSelectedTableRows] = useState<any[]>([]);
    const [currentSelectedDrawerTableRows, set_currentSelectedDrawerTableRows] = useState<any[]>([]);

    const tableRef = useRef<ActionType>();
    const drawerTableRef = useRef<ActionType>();
    const [drawerTableData, set_drawerTableData] = useState<any[]>([]);
    const [modalFormVisible, set_modalFormVisible] = useState(false);
    const [clearSelection, set_clearSelection] = useState(false);

    const columns: ProColumns[] = [
        {
            title: '资质编码',
            width: 150,
            ellipsis: true,
            dataIndex: 'code'
        },
        {
            title: '资质名称',
            ellipsis: true,
            dataIndex: 'name'
        },
        {
            title: '资质分类',
            ellipsis: true,
            dataIndex: 'qualificationTypeName'
        },
        {
            title: '授权依据',
            ellipsis: true,
            dataIndex: 'standard',

        },
        {
            title: '特殊类别',
            ellipsis: true,
            width: 150,
            renderText(text, record, index, action) {
                const { 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) && ('-')
                    } */}
                </div>
            },
        },


    ];

    const drawerTablecolumns: ProColumns[] = [
        {
            title: '姓名',
            width: 70,
            ellipsis: true,
            renderText(text, record, index, action) {
                const { userInfo: { name } } = record;
                return name;
            },
        },
        {
            title: '工号',
            ellipsis: true,
            dataIndex: 'userId'
        },
        {
            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: '授权',
            width: 320,
            ellipsis: true,
            renderText(text, record, index, action) {
                const { qualificationPeriod, beginDate, endDate, applyStatus } = record;
                // <>{`${beginDate}至${endDate}`}</>
                if (applyStatus == 2 || applyStatus == 3 || applyStatus == 4) {
                    return <span style={{ fontSize: 14, color: '#FF8C19' }}>申请中</span>
                } else {
                    return `${qualificationPeriod == 1 ? '长期授权' : qualificationPeriod == 2 ? '临时授权' : '单次授权'}（${beginDate}至${endDate}）`
                }
            },

        },
    ]


    const getTableData = async (params: any) => {
        const { qualificationTypeCode } = params;
        if (!qualificationTypeCode) {

        }
        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_DRAWER' | 'EDIT') => {
        try {
            let result: any[] = [];
            const arr = currentSelectedLeftRows.map((a) => {
                const qualifis = currentSelectedTableRows.map((b) => ({
                    qualifisCode: `${a.id}-${b.code}`,
                    userId: a.id,
                    qualificationCode: b.code,
                    qualificationPeriod: Number(formVal.qualificationPeriod),
                    beginDate: formVal.timerange[0],
                    endDate: formVal.timerange[1],
                    managerOpinion: formVal.memo
                }));
                return qualifis
            });
            if (currentSelectedDrawerTableRows.length > 0) {
                const keys = currentSelectedDrawerTableRows.map((a) => `${a.userId}-${a.qualificationCode}`);
                const needDelItems = drawerTableData.filter((a) => !(keys.includes(`${a.userId}-${a.qualificationCode}`)));
                const needDelItemsKey = needDelItems.map((a) => `${a.userId}-${a.qualificationCode}`);
                result = arr.flat().filter((a: any) => !(needDelItemsKey.includes(a.qualifisCode)));

            } else {
                const needDelItemsKey = drawerTableData.map((a) => `${a.userId}-${a.qualificationCode}`);

                result = arr.flat().filter((a: any) => !(needDelItemsKey.includes(a.qualifisCode)));
            }

            result.forEach(obj => {
                delete obj.qualifisCode;
            });
            const resp = await editData(result);
            if (resp) {

                set_currentSelectedLeftRows([]);
                set_currentSelectedDrawerTableRows([]);
                set_currentSelectedTableRows([]);
                set_clearSelection(true);
                setTimeout(() => set_clearSelection(false), 0);
                set_drawerVisible(false);
                set_modalFormVisible(false);


                tableRef.current?.reload();
                message.success('操作成功！');
            }

            return true;

        } catch (error) {

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




    }


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

    const getLeftDataHandle = async () => {
        const resp = await getLeftDataReq();
        if (true) {
            set_dataSource(resp);
        }
    }


    const cancelBatchAuthHandle = () => {
        set_currentSelectedLeftRows([]);
        set_currentSelectedTableRows([]);
        set_clearSelection(true);
        setTimeout(() => set_clearSelection(false), 0);
    }
    const batchAuthHandle = async () => {
        if (currentSelectedLeftRows.length == 0) {
            message.warn('请选择医生！');
            return
        }
        if (currentSelectedTableRows.length == 0) {
            message.warn('请选择资质！');
            return
        }
        const result = currentSelectedLeftRows.map((a) => {
            const qualifis = currentSelectedTableRows.map((b) => ({
                userId: a.id,
                qualificationCode: b.code
            }));
            return qualifis
        });

        const resp = await batchAuthDataCheck(result.flat());
        if (resp) {
            if (resp.length > 0) {
                set_drawerTableData(resp);
                set_drawerVisible(true);
            } else {
                set_modalFormVisible(true);
            }
        }
    }


    useEffect(() => {
        if (!modalFormVisible) {
            set_currentSelectedLeftRows([]);
            set_currentSelectedDrawerTableRows([]);
            set_currentSelectedTableRows([]);
            set_clearSelection(true);
            setTimeout(() => set_clearSelection(false), 0);
        }
    }, [modalFormVisible])


    useEffect(() => {
        if (!isChildComponent) {
            getLeftDataHandle();
        }
    }, [])

    return (
        <KCIMPagecontainer className='QualificationBatchAuth' style={!isChildComponent ? {} : { border: 'none' }} title={false}>
            <ModalForm
                title={''}
                width={352}
                formRef={formRef}
                open={modalFormVisible}
                initialValues={{
                    // memo: record.applyMemo,
                    qualificationPeriod: 1,
                    timerange: [moment().startOf("day"), moment().startOf("day")]
                }}

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

                <ProFormRadio.Group label='授权期限：' name={'qualificationPeriod'} options={authTimeType} />
                <ProFormDateRangePicker label='授权时间：' name='timerange' />
                <ProFormTextArea label='审批意见：' name={'memo'} />

            </ModalForm>
            <Drawer destroyOnClose={true} className='authDetailDrawer' width={900}
                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={() => {
                            const val = drawerFormRef.current?.getFieldsFormatValue?.();
                            updateTable({ ...val }, 'EDIT_DRAWER')
                        }}>授权</span>
                    </div>
                </div>
                <div className='authDetailDrawer-content'>
                    <div className='authDetailDrawer-content-table'>
                        <div className='authDetailDrawer-content-table-title'>处理重复授权</div>
                        <Alert style={{ borderRadius: 4, height: 32, marginBottom: 16 }} message="系统中已有下列授权，请逐一确认。您可以：勾选：用本次授权内容覆盖已有授权；不勾选：保持已有授权，忽略本次授权" type="info" showIcon />
                        <KCIMTable
                            actionRef={drawerTableRef} columns={drawerTablecolumns as ProColumns[]} rowKey='id'
                            // request={(params) => getTableData(params)}
                            dataSource={drawerTableData}
                            tableAlertRender={false}
                            scroll={{ y: 545 }}
                            rowSelection={{
                                onChange(selectedRowKeys, selectedRows, info) {
                                    set_currentSelectedDrawerTableRows(selectedRows);
                                },
                            }}
                        />
                    </div>
                    <ProForm formRef={drawerFormRef} submitter={false} initialValues={{
                        // memo: record.applyMemo,
                        qualificationPeriod: 1,
                        timerange: [moment().startOf("day"), moment().startOf("day")]
                    }}>
                        <div className='authDetailDrawer-content-form'>
                            <div className='authDetailDrawer-content-form-title'>批量资质授权</div>
                            <div className='formWrapper'>
                                <div>
                                    <ProFormRadio.Group label='授权期限：' name={'qualificationPeriod'} options={authTimeType} />
                                    <ProFormDateRangePicker label='授权时间：' name='timerange' />
                                </div>
                                <ProFormTextArea name={'memo'} fieldProps={{
                                    style: { width: 500, height: 85 }
                                }} label='审批意见：' />
                            </div>

                        </div>

                    </ProForm>
                </div>


            </Drawer>
            <div className='pageContent'>
                {
                    !isChildComponent && (
                        <div className='left'>
                            <DoctorSelection clearSelection={clearSelection} onSelectedChange={(arr) => { set_currentSelectedLeftRows(arr) }} doctorsData={dataSource} />
                        </div>
                    )
                }
                <div className='right' style={isChildComponent ? { width: '100%' } : { width: 'calc(100% - 236px)', padding: 16 }}>
                    <div className='right-content-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: null })
                                        }
                                    }}

                                    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,
                                                enableFlag: checkedValue.findIndex((a) => a == '已停用') != -1 ? 0 : 1,
                                            })
                                        },
                                    }}
                                />
                            </div>
                        </div>
                        {/* {!isChildComponent && (
                            <div className='btnGroup'>
                                <UpDataActBtn record type='ADD' />
                            </div>
                        )} */}
                    </div>
                    <div style={{ marginTop: 16 }}>
                        <KCIMTable scroll={{ y: `calc(100vh - 263px)` }}
                            actionRef={tableRef} columns={columns as ProColumns[]} rowKey='id'
                            params={tableDataFilterParams}
                            request={(params) => getTableData(params)}
                            // dataSource={showList}
                            tableAlertRender={false}
                            rowSelection={{
                                selectedRowKeys: currentSelectedTableRows.map((a) => a.id),
                                onChange(selectedRowKeys, selectedRows, info) {
                                    set_currentSelectedTableRows(selectedRows);
                                    onTableSelectChange && onTableSelectChange(selectedRowKeys, selectedRows, info)
                                },
                            }}

                        />
                    </div>
                </div>
            </div>
            {
                (currentSelectedLeftRows.length > 0 || currentSelectedTableRows.length > 0) && (
                    <div className='bottom'>
                        <div className='tags'>已选择医生<span>{currentSelectedLeftRows.length}</span>项，资质<span>{currentSelectedTableRows.length}</span>项</div>
                        <div className='btn-groups'>
                            <div className='cancelBtn' onClick={() => cancelBatchAuthHandle()}>取消选择</div>
                            <div className='batchBtn' onClick={() => batchAuthHandle()}>批量授权</div>
                        </div>

                    </div>
                )
            }
        </KCIMPagecontainer>
    )
}
