/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-01-06 10:19:41
 * @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 { ModalForm, ProFormCascader, ProFormCheckbox, ProFormDependency, ProFormDigit, ProFormSelect, ProFormSwitch } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Switch } from 'antd';
import { Fragment, Key, useEffect, useRef, useState } from 'react';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';


import { addData, delData, editData, getDrawerTableDataReq, getTableDataReq, saveConnectTableDataReq } from './service';

import './style.less';
import { KCIMLeftList } from '@/components/KCIMLeftList';
import { getTableList as getQualClassReq } from '../qualificationClassfiMana/service';
import { getDicDataBySysId } from '@/services/getDic';
import { KcimCenterSysId } from '@/constant';
import TableTransfer from './transform';
import React from 'react';



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


const transferTableColumn: ProColumns[] = [
    {
        title: '医嘱类型',
        dataIndex: 'hisItemType',
    },
    {
        title: '医嘱编码',
        ellipsis: true,
        dataIndex: 'hisItemId',
    },
    {
        title: '医嘱项目名称',
        dataIndex: 'hisItemName',
    },
    {
        title: '备注',
        dataIndex: 'memo',
    },

]

export default function QualifiDicMana({ 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 DragHandle = SortableHandle(() => <img width={16} style={{ cursor: 'pointer' }} src={require('../../static')} alt="" />);

    const tableRef = useRef<ActionType>();

    const columns: ProColumns[] = [
        {
            title: '资质编码',
            width: 150,
            ellipsis: true,
            dataIndex: 'code',
        },
        {
            title: '资质名称',
            ellipsis: true,
            dataIndex: 'name',
        },
        {
            title: '资质分类',
            ellipsis: true,
            dataIndex: 'qualificationTypeName',
            // render:(_:any)=>_ == 1?'指标':'自定义SQL'
        },
        {
            title: '授权依据',
            ellipsis: true,
            dataIndex: 'standard',
            // render:(_:any)=>_ == 1?'指标':'自定义SQL'
        },
        {
            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) && (<Fragment/>)
                    }
                </div>
            },
        },
        {
            title: '启用',
            width: 80,
            hideInTable:isChildComponent,
            dataIndex: 'enableFlag',
            renderText: (_: any, record: any) => {

                return <Switch size='small' checked={_ ? true : false} onChange={(bool) => switchChangeHandle(bool, record, 'enableFlag')} />
            }
        },
        {
            title: '操作',
            key: 'option',
            width: 120,
            hideInTable:isChildComponent,
            fixed: 'right',
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <UpDataActBtn key={'act'} record={record} type='CONNECT' />,
                    <UpDataActBtn key={'act2'} record={record} type='EDIT' />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },

    ]


    const getTableData = async (params: any) => {
        const { qualificationTypeCode } = params;
        const resp = isChildComponent?await getDrawerTableDataReq(params):await getTableDataReq(params);
        if (resp) {
            return {
                data: resp.list,
                success: true
            }
        } else {
            return []
        }
    }

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

    const switchChangeHandle = (checked: boolean, record: any, key: string) => {

        // const newData = dataSource.map((a: any) => {
        //     if (a.id == record.id) {
        //         return { ...a, [`${key}`]: checked ? 1 : 0 }
        //     }
        //     return a
        // });

        // set_dataSource([...newData]);
        updateTable({ ...record, [`${key}`]: checked ? 1 : 0 }, 'EDIT')
    }

    const updateTable = async (formVal: any, type: 'EDIT' | 'ADD' | 'CONNECT') => {

        try {

            if (type == 'ADD') {
                const resp = await addData({
                    code: formVal.code,
                    name: formVal.name,
                    qualificationTypeCode: formVal.qualificationType[formVal.qualificationType.length - 1],
                    standard: formVal.standard,
                    techFlag: formVal.operation?((formVal.operation.filter((a: string) => a == '医疗技术')).length > 0 ? 1 : 0):null,
                    operationFlag: formVal.operation?((formVal.operation.filter((a: string) => a == '手术')).length > 0 ? 1 : 0):null,
                    operationLevelCode: formVal.operationLevelCode?formVal.operationLevelCode:null,
                    enableFlag: formVal.enableFlag ? 1 : 0
                });
                if (resp) {
    
                    tableRef.current?.reload();
                    message.success('操作成功！');
                    return true
                }
    
            }
            if (type == 'CONNECT') {
                const resp = await saveConnectTableDataReq(formVal);
                if (resp) {
                    message.success('操作成功！');
                    tableRef.current?.reload();
                    return true
                }
    
            }
            if (type == 'EDIT') {
    
                const resp = await editData({
                    id: formVal.id,
                    code: formVal.code,
                    name: formVal.name,
                    qualificationTypeCode: formVal.qualificationType ? formVal.qualificationType[formVal.qualificationType.length - 1] : formVal.qualificationTypeCode,
                    standard: formVal.standard,
                    techFlag: formVal.operation ? ((formVal.operation.filter((a: string) => a == '医疗技术')).length > 0 ? 1 : 0) : formVal.techFlag,
                    operationFlag: formVal.operation ? ((formVal.operation.filter((a: string) => a == '手术')).length > 0 ? 1 : 0) : formVal.operationFlag,
                    operationLevelCode: formVal.operationLevelCode?formVal.operationLevelCode:null,
                    enableFlag: formVal.enableFlag ? 1 : 0
                });
                if (resp) {
                
                    tableRef.current?.reload();
                    message.success('操作成功！');
                    return true
                }
            }

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

        
        

    }

    const formRef = useRef();
    
    const UpDataActBtn = ({ record, type }: { record: any, type: 'EDIT' | 'ADD' | 'CONNECT' }) => {
        const ref = React.createRef<{ save: any; }>();

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : type == 'CONNECT' ? '关联医嘱项目' : '新增'}`}
                width={type == 'CONNECT' ? 972 : 352}
                formRef={formRef}
                initialValues={type == 'EDIT' ? {
                    ...record,
                    operation: [record.techFlag ? '医疗技术' : '', record.operationFlag ? '手术' : ''],
                    qualificationType: record.fullQualificationTypeCode ? record.fullQualificationTypeCode.split('|') : []
                } : { enableFlag: 1 }}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : type == 'CONNECT' ? <a className='add'>关联</a> : <a className='add'>新增</a>
                }
                onFinish={(val) => {
                    if (type == 'CONNECT') {
                        ref.current && ref.current.save();
                        return Promise.resolve(true);
                    } else {
                        return updateTable(type == 'EDIT' ? { ...record, ...val } : { ...val }, type);
                    }
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >

                {
                    type != 'CONNECT' && (
                        <>
                            <ProFormText
                                name="code"
                                label="资质编码："
                                placeholder="请输入"
                                disabled={type == 'EDIT'}
                                rules={[{ required: true, message: '资质编码不能为空!' }]}
                            />
                            <ProFormText
                                name="name"
                                label="资质名称："
                                placeholder="请输入"
                                rules={[{ required: true, message: '资质名称不能为空!' }]}
                            />
                            <ProFormCascader
                                name="qualificationType"
                                label="资质分类："
                                placeholder="请选择"
                                fieldProps={{
                                    fieldNames: { label: 'name', value: 'code' },
                                    options: dataSource
                                }}
                                rules={[{ required: true, message: '资质分类不能为空!' }]}
                            />
                            <ProFormTextArea
                                name="standard"
                                label="授权依据："
                                placeholder="请输入"
                                rules={[{ required: false, message: '授权依据不能为空!' }]}
                            />
                            <ProFormCheckbox.Group
                                name="operation"
                                layout='horizontal'
                                options={['医疗技术', '手术']}
                            />
                            <ProFormDependency name={['operation']}>
                                {
                                    ({ operation = [] }) => {
                                        const isShow = operation.findIndex((a: string) => a == '手术');
                                        return isShow != -1 && (
                                            <ProFormSelect
                                                name="operationLevelCode"
                                                label="手术级别："
                                                placeholder={'请选择'}
                                                request={async () => {
                                                    const resp = await getDicDataBySysId(KcimCenterSysId, 'SURGICAL_AND_OPERATIONAL_LEVELS');
                                                    if (resp) {
                                                        return resp.dataVoList.map((item: any) => ({ label: item.name, value: item.value }))
                                                    }
                                                }}
                                            />
                                        )
                                    }
                                }
                            </ProFormDependency>

                            <ProFormSwitch fieldProps={{ size: 'small' }} name="enableFlag" label="启用：" />
                        </>
                    )
                }
                {
                    type == 'CONNECT' && (
                        <TableTransfer
                            ref={ref}
                            record={record}
                            onSave={(keys, items) => {
                                const qualificationHisItemMap = items.map((a) => ({
                                    qualificationId: record.id,
                                    hisItemDicId: a.hisItemId,
                                    hisItemType: a.hisItemType,
                                    hisItemName: a.hisItemName,
                                    memo: a.memo
                                }))
                                updateTable({ qualificationId: record.id, qualificationHisItemMap }, 'CONNECT')
                            }}
                            leftColumns={transferTableColumn}
                            rightColumns={transferTableColumn}
                        ></TableTransfer>
                    )
                }

            </ModalForm>
        )
    }

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

    const getQualClassRequest = async () => {
        const resp = await getQualClassReq();
        if (true) {
            set_dataSource(resp);
            // set_dataSource([
            //     {
            //         "id": 29,
            //         "code": 88,
            //         "parentCode": "制保应从般重",
            //         "name": "谢艳",
            //         "description": "元性化点下在金火出正内定将理标号北。步样术算族县快铁温就气市。生拉解感年专把高第则石更阶年。",
            //         "sort": 55
            //     }
            // ]);
        }
    }

    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, qualificationTypeCode: currentSelectedType.code,qualificationTypeNameFilter:currentSelectedType.searchKeyword })
        }
    }, [currentSelectedType]);

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


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

    return (
        <KCIMPagecontainer className='QualifiDicMana' style={!isChildComponent?{}:{border:'none',padding:0}} title={false}>
            <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>
                                <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={isChildComponent?['医疗技术', '手术']:['医疗技术', '手术', '已停用']}
                                    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 }}>
                        {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,
                                  getCheckboxProps(record) {
                                    return {
                                        disabled: record.allowCheck == 0,
                                    }
                                  },
                                  onChange(selectedRowKeys, selectedRows, info) {
                                    onTableSelectChange&&onTableSelectChange(selectedRowKeys,selectedRows,info) 
                                  },
                            }:false}
                            components={{
                                body: {
                                    wrapper: DraggableContainer,
                                    row: DraggableBodyRow,
                                },
                            }}
                        />}
                    </div>
                </div>
            </div>
        </KCIMPagecontainer>
    )
}
