/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-07-07 14:26:29
 * @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 BMSPagecontainer from '@/components/BMSPageContainer';
import { BMSTable } from '@/components/BMSTable';

import { createFromIconfontCN } from '@ant-design/icons';
import { ActionType } from '@ant-design/pro-components';
import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Button, Dropdown, Input, MenuProps, message, Modal, Popconfirm, Space, Switch, Table } from 'antd';

import { TransferItem, TransferProps } from 'antd/es/transfer';
import React, { Key } from 'react';
import { useEffect, useImperativeHandle, useRef, useState } from 'react';

import { getMedicalGroup, getEmpTableDataFromMedicalGroup, addMedicalGroup, editMedicalGroup, delLeftReportData, getMedicalAllEmp, addMedicalGroupEmp, MedicalEmpInfoType, updateMedicalGroupEmpInfo, delTableData } from './service';

import './style.less';

import '../../../../utils/zhongtaiA'

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



const MedicalGroupSet = () => {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();

    const [typeList, set_typeList] = useState<any[]>([]);
    const [showTypeListArr, set_showTypeListArr] = useState<any[]>([]);
    const [currentSelectedType, set_currentSelectedType] = useState<any | undefined>(undefined);



    const [tableSelectedKeys, set_tableSelectedKeys] = useState<any[]>([]);

    const [selectedAddKeys, set_selectedAddKeys] = useState<Key[]>([]);

    const [ifShowModal, set_ifShowModal] = useState(false);

    const [currentEditLeftData, set_currentEditLeftData] = useState<any | undefined>(undefined);

    const [ifEditTable, set_ifEditTable] = useState(false);

    const tableRef = useRef<ActionType>();

    const ref = React.createRef<{ save: any; getSelectedKeys: any }>();

    const column = [

        {
            title: '工号',
            ellipsis: true,
            dataIndex: 'account',

        },
        {
            title: '姓名',
            dataIndex: 'name',

        },
        {
            title: '组长',
            dataIndex: 'medicalGroupManager',
            render: (_: any, record: any) => {
                return <Switch size='small' checked={_} onChange={(bool) => switchChangeHandle(bool, record, 'medicalGroupManager')} />
            }
        },
        {
            title: '操作',
            key: 'option',
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableDataHanfle(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },
    ]

    const delTableDataHanfle = async (record?: { id: number; }) => {
        const resp = await delTableData(record ? [record.id] : [...tableSelectedKeys]);

        if (resp) {
            set_tableSelectedKeys([]);
            tableRef.current?.reload();
        }
    }

    const [tableColumn, set_tableColumn] = useState<ProColumns[] | any[]>(column);


    const getTableData = async (params: any, sort: any, filter: any) => {
        const { medicalGroupCode } = params;

        if (medicalGroupCode) {
            const resp = await getEmpTableDataFromMedicalGroup(params);
            if (resp) {

                return {
                    data: resp.list,
                    success: true,
                    total: resp.totalCount,
                    pageSize: resp.pageSize,
                    totalPage: resp.totalPage,
                }

            }
        }
        return {
            data: [],
            success: true
        }
    }

    const switchChangeHandle = async (checked: boolean, record: any, key: string) => {
        const result = { ...record, medicalGroupManager: checked ? 1 : 0 }
        const resp = await updateMedicalGroupEmpInfo(result);
        if (resp) {
            tableRef.current?.reload();
        }
    }

    //获取左侧数据
    const getPageLeftData = async () => {
        const resp = await getMedicalGroup();

        if (resp) {

            set_typeList(resp);
            set_showTypeListArr(resp);
        }
    }


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

        // console.log({formVal,type});

        if (type == 'ADD_LEFTDATA') {
            const resp = await addMedicalGroup({
                name: formVal.name,
                remark: formVal.remark,
            });
            if (resp) {
                getPageLeftData();
            }
        }



        if (type == 'EDIT_LEFTDATA') {
            const resp = await editMedicalGroup({
                id: formVal.id,
                name: formVal.name,
                remark: formVal.remark
            });
            if (resp) {
                getPageLeftData();
            }
        }

        return true;

    }

    const UpDataActBtn = ({ record, type }: { record: any, type: 'EDIT' | 'ADD' | 'ADD_LEFTDATA' | 'EDIT_LEFTDATA' }) => {

        const getTrriger = () => {
            if (type == 'ADD') {
                return <span className='add'>添加</span>
            }
            if (type == 'EDIT') {
                return <a key="edit" >编辑</a>
            }
            if (type == 'ADD_LEFTDATA') {
                return (
                    <div className='add'>
                        <img src={require('../../../../../static/addIcon_black.png')} alt="" />
                    </div>
                )
            }
            if (type == 'EDIT_LEFTDATA') {
                return <a key="edit" >编辑</a>
            }
        }

        return (
            <ModalForm
                title={type == 'ADD_LEFTDATA' ? `新增医疗组` : `编辑医疗组`}
                width={352}
                initialValues={type == 'EDIT_LEFTDATA' ? { ...record } : {}}
                trigger={
                    getTrriger()
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT_LEFTDATA' ? { ...record, ...val } : val, type);
                }}
            >

                <ProFormText
                    label='医疗组名称：'
                    name='name'
                    rules={[{ required: true, message: '名称不能为空!' }]}
                />
                <ProFormTextArea
                    label='说明：'
                    name='remark'
                />
            </ModalForm>
        )
    }


    interface TableSelecterProps extends TransferProps<TransferItem> {
        tableSelecterColumn: any[];
        record: any
    }


    const tableSelecterColumn: any[] = [
        {
            title: '工号',
            dataIndex: 'account',
        },
        {
            title: '姓名',
            dataIndex: 'name',
        },
    ];

    const addGroupEmpHandle = () => {

        const ref = React.createRef<{ save: any; getSelectedKeys: any }>();

        set_ifShowModal(true);
    }

    const TableSelecter = React.forwardRef(({ tableSelecterColumn, record }: TableSelecterProps, ref) => {

        const [datasource, set_datasource] = useState<any[]>([]);
        const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
        const [showList, set_showList] = useState<any[]>([]);

        //获取表格数据
        const getFuncList = async () => {
            const resp = await getMedicalAllEmp({ medicalGroupCode: currentSelectedType.code });
            if (resp) {
                set_datasource(resp);
                set_showList(resp);
            }
        }


        const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
            setSelectedKeys([...newSelectedRowKeys]);

        };

        const save = async () => {

            const needData = datasource.filter(item => selectedKeys.includes(item.userId));

            const result = {
                medicalGroupCode: currentSelectedType.code as string,
                employee: needData as MedicalEmpInfoType[]
            };

            const resp = await addMedicalGroupEmp(result);

            if (resp) {
                message.success('添加成功！');
                set_ifShowModal(false);
                tableRef.current?.reload();
            }
        }

        useEffect(() => {
            getFuncList();
        }, [])

        return (
            <div className='TableSelecter'>
                <Input placeholder={'请输入'} allowClear
                    suffix={
                        <IconFont style={{color:'#99A6BF'}} type="iconsousuo" />
                    }
                    style={{ marginBottom: 8 }}
                    onChange={(e) => {
                        if (e.target.value.length != 0) {
                            const result = datasource.filter(item => item.name.indexOf(e.target.value) != -1);
                            set_showList(result);
                        } else {
                            set_showList(datasource);
                        }

                    }}

                />
                <BMSTable columns={tableSelecterColumn}
                    options={{
                        density: true,
                        setting: {
                            listsHeight: 100,
                        },
                    }}
                    rowKey='userId'
                    
                    tableAlertRender={false}
                    rowSelection={{
                        // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                        // 注释该行则默认不显示下拉选项
                        selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                        onChange: onSelectChange,
                    }}
                    pagination={{ showSizeChanger: false, pageSize:10, simple: true, showTitle: false }}
                    dataSource={showList}
                />                
                <div className='footer'>
                    <span className='cancel' onClick={() => set_ifShowModal(false)}>取消</span>
                    <span className='ok' onClick={() => save()}>{`确认(${selectedKeys.length > 0 && selectedKeys.length})`}</span>
                </div>
            </div>

        )
    });

    const moreItems: MenuProps['items'] = [
        {
            key: '1',
            label: <UpDataActBtn key={'act'} record={currentEditLeftData} type='EDIT_LEFTDATA' />,
        },
        {
            key: '2',
            label: (
                <a onClick={async (e) => {
                    e.preventDefault();
                    const resp = await delLeftReportData(currentEditLeftData.id);
                    if (resp) {
                        getPageLeftData();
                    }
                }}>
                    删除
                </a>
            ),
        }
    ];


    const onTableSelectChange = (newSelectedRowKeys: React.Key[]) => {
        set_tableSelectedKeys([...newSelectedRowKeys]);
    };


    useEffect(() => {

        if (currentSelectedType) {
            set_tableDataFilterParams({ ...tableDataFilterParams, medicalGroupCode: currentSelectedType.code });

        }
    }, [currentSelectedType])

    useEffect(() => {
        if (showTypeListArr.length > 0) {
            set_currentSelectedType(showTypeListArr[0]);
            //set_tableDataFilterParams({ ...tableDataFilterParams, medicalGroupCode: showTypeListArr[0].code });
        }
    }, [showTypeListArr]);


    useEffect(() => {
        getPageLeftData();
    }, [])



    return (
        <BMSPagecontainer title={false} className='MedicalGroupSet'>

            <ModalForm title={'添加医疗组人员信息'} width={400} submitter={{
                render: (props, defaultDoms) => []
            }} open={ifShowModal} modalProps={{
                closable: false,
            }}>
                <TableSelecter
                    ref={ref}
                    record={undefined}
                    tableSelecterColumn={tableSelecterColumn}
                ></TableSelecter>
            </ModalForm>

            <div className='left'>
                <div className='toolbar'>
                    <Input placeholder={'医疗组名称'} allowClear
                        suffix={
                            <IconFont style={{color:'#99A6BF'}} type="iconsousuo" />
                        }
                        style={{ width: 156 }}
                        onChange={(e) => {
                            const result = typeList.filter(item => item.name.indexOf(e.target.value) != -1);
                            set_showTypeListArr(result);
                        }}
                    />

                    <UpDataActBtn key={'act'} record={undefined} type='ADD_LEFTDATA' />

                </div>

                <div className='wrap'>
                    {
                        showTypeListArr.map((item, index) => {
                            return (
                                <div className={currentSelectedType ? currentSelectedType.id == item.id ? 'type on' : 'type' : 'type'}
                                    key={index}
                                    onClick={() => {
                                        if (ifEditTable) {
                                            //编辑状态还未保存
                                            Modal.confirm({
                                                title: '当前存在编辑未保存，请保存后再操作！',
                                                okText: '放弃编辑',
                                                cancelText: '继续编辑',
                                                onOk(...args) {
                                                    set_ifEditTable(false);
                                                    set_currentSelectedType(item);

                                                },
                                            })
                                        } else {
                                            set_currentSelectedType(item)
                                        }
                                    }}
                                >
                                    <div className='content'>
                                        <div className='name'>{item.name}</div>
                                    </div>

                                    <Dropdown menu={{ items: moreItems }} placement="bottom" onOpenChange={(bool) => { bool && set_currentEditLeftData(item) }}>
                                        <div className='more'>
                                            <img src={require('../../../../../static/more_point_gray.png')} alt="" />
                                        </div>
                                    </Dropdown>
                                </div>
                            )
                        })
                    }
                </div>
            </div>
            <div className='right'>
                <div className='toolBar'>
                    <div className='filter'>
                        <span style={{ fontSize: 16, color: '#17181A', fontWeight: 500 }}>{currentSelectedType ? currentSelectedType.name : ''}</span>
                    </div>
                    <div className='btnGroup'>
                        {<span className='manaBtn' onClick={() => addGroupEmpHandle()}>添加</span>}
                    </div>
                </div>
                <div style={{ marginTop: 16 }}>
                    {currentSelectedType && <BMSTable actionRef={tableRef} columns={tableColumn}
                        rowKey='id'
                        pagination={false}
                        tableAlertRender={false}
                        rowSelection={{
                            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                            // 注释该行则默认不显示下拉选项
                            //selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT, Table.SELECTION_NONE,],
                            onChange: onTableSelectChange,

                        }}
                        tableAlertOptionRender={() => {
                            return (

                                <Space size={16}>
                                    <Popconfirm
                                        title="是否确认删除？"
                                        key="del"
                                        onConfirm={() => delTableDataHanfle()}
                                    >
                                        <a>批量删除</a>
                                    </Popconfirm>
                                </Space>
                            );
                        }}
                        params={tableDataFilterParams}
                        request={(params, sort, filter) => getTableData(params, sort, filter)}
                    />}
                </div>
            </div>
            {
                tableSelectedKeys.length > 0 && (
                    <div className='bottomToolbar'>
                        <span className='leftAccount'>已选择<a>{tableSelectedKeys.length}</a>项</span>
                        <div className='btnGroup'>
                            <span className='cancel' onClick={() => tableRef.current?.clearSelected&&tableRef.current?.clearSelected()}>取消选择</span>
                            <Popconfirm
                                title="是否确认删除？"
                                key="del"
                                onConfirm={() => delTableDataHanfle()}
                            >
                                <span className='batchDel'>批量删除</span>
                            </Popconfirm>

                        </div>
                    </div>
                )
            }

        </BMSPagecontainer >
    )
}


export default MedicalGroupSet;
