/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-04-26 15:49:07
 * @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, MenuOutlined } from '@ant-design/icons';

import { ActionType, useRefFunction } from '@ant-design/pro-components';
import { ModalForm, ProFormSelect } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm,Tabs } from 'antd';
import { Key, useEffect, useRef, useState } from 'react';

import { delData, editData, getModalTableList, getJobCateReq, getReportListTableData} from './service';

import './style.less';

import '../../../../utils/zhongtaiB';
import React from 'react';
import SQLEditor from '@/components/SQLEditor';
import { ReportListManaUpDataActBtn } from './UpDataActBtn';
import { getDicDataBySysId } from '@/services/getDic';
import { arrayMoveImmutable } from 'array-move';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
const IconFont = createFromIconfontCN({
    scriptUrl: '',
});

const DragHandle = SortableHandle(() => (
    <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />
));

export default function JobCateRetenSet() {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const tableRef = useRef<ActionType>();
    const [currentEditRow, set_currentEditRow] = useState<any | undefined>(undefined);
    const [tabs,set_tabs] = useState<any[]>([]);
    const [currentTabKey,set_currentTabKey] = useState<string|undefined>(undefined);
    const [dataSource,set_dataSource] = useState<any[]>([]);
    const SortableItem = SortableElement((props: any) => <tr {...props} />);
    const SortContainer = SortableContainer((props: any) => <tbody {...props} />);
    const [tableSelectedKeys,set_tableSelectedKeys] = useState<Key[]>([]);

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

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

    const columns: ProColumns[] = [
        {
            dataIndex: 'sort',
            width: 50,
            className: 'drag-visible',
            render: () => <DragHandle />
        },
        {
            title: '项目代码',
            dataIndex: 'retainCode',
            ellipsis: true
        },
        {
            title: '项目名称',
            dataIndex: 'retainName',
            ellipsis: true
        },
        {
            title: '项目类型',
            dataIndex: 'retainTypeName',
            ellipsis: true
        },
        {
            title: '说明',
            dataIndex: 'comment',
            ellipsis: true
        },
        {
            title: '操作',
            key: 'option',
            width: 120,
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData([record.id])}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },

    ]

    const tableSelecterColumn: ProColumns[] = [
        {
            title: '项目名称',
            dataIndex: 'retainName',
            ellipsis: true
            // render:(_:any)=>_ == 1?'指标':'自定义SQL'
        },
        {
            title: '数据格式',
            dataIndex: 'retainTypeName',
            ellipsis: true
            // render:(_:any)=>_ == 1?'指标':'自定义SQL'
        },
    ]


    const getTableData = async (params: any) => {
        const {unitType,filter} = params;
        if(!unitType) return []
        const resp = await getReportListTableData(params);
        if (resp) {
            set_dataSource(resp);
            if(filter){
                
                return {
                     data:resp.filter((a:any)=>a.retainName.indexOf(filter) != -1),
                     success: true,
                }
            }
            return {
                data: resp,
                success: true,
            }
        }
        return []
    }

    const delTableData = async (ids:Key[]) => {
        const resp = await delData(ids);
        if (resp) {
            message.success('操作成功！');
            tableRef.current?.reload();
            // message.success('操作成功!');
        }
        set_tableSelectedKeys([]);
    }



    const tableDataSearchHandle = (paramName: string) => {

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

    }

    const getTabsHandle = async ()=>{
          const resp = await getJobCateReq()
          if(resp){
               const arr = resp.list.map((a:any)=>({label:a.name,key:a.code}));
               set_tabs([...arr]);
               set_currentTabKey(arr[0].key);
          }
          
    }


    interface TableSelecterProps {
        tableSelecterColumn: any[];
        record: any
    }

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


        const [datasource, set_datasource] = useState<any[]>([]);
        const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
        const [selectedRows, set_selectedRows] = useState<any[]>([])
        const [showList, set_showList] = useState<any[]>([]);
        const [tableParams, set_tableParams] = useState<any>({});
        const [keywords, set_keywords] = useState('');
    

        //获取表格数据
        const getFuncList = async () => {
            const resp = await getModalTableList(currentTabKey as string);
            if (resp) {
                set_datasource(resp);
                set_showList(resp);

                // if (currentEditRow && currentEditRow.childColumnList) {
                //     const defaultKeys = currentEditRow.childColumnList.map((a: any) => a.code);
                //     setSelectedKeys(defaultKeys);
                // }
            }

        }


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

        };

        const save = async () => {
            // console.log({selectedRows});
            const arr = [...dataSource,...selectedRows];
            const resp = await editData({
                unitType:currentTabKey,
                retainList:arr.map((a,index)=>({
                    retainCode:a.retainCode,
                    retainName:a.retainName,
                    retainType:a.retainType,
                    comment:a.comment,
                    sort:index+1
                }))
            });
            if (resp) {
                set_ifShowModal(false);
                tableRef.current?.reload();
                message.success('操作成功！');
            }
        }

        

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

        return (
            <div className='TableSelecter'>
                <Input placeholder={'请输入'} allowClear
                    suffix={
                        <IconFont type="iconsousuo" />
                    }
                    style={{ marginBottom: 8 }}
                    onChange={(e) => {
                        if (e.target.value.length != 0) {
                            const result = datasource.filter(item => item.headerText.indexOf(e.target.value) != -1);
                            set_showList(result);
                        } else {
                            set_showList(datasource);
                        }
                    }}
                />
                <div className='wrapper' style={{ maxHeight: 489, overflowY: 'scroll' }}>
                    <BMSTable columns={tableSelecterColumn}
                        options={{
                            density: true,
                            setting: {
                                listsHeight: 100,
                            },
                        }}
                        rowKey='retainCode'
                        tableAlertRender={false}
                        rowSelection={{
                            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                            // 注释该行则默认不显示下拉选项
                            selectedRowKeys: selectedKeys,
                            onChange: onSelectChange,
                            checkStrictly: false
                        }}
                        dataSource={showList}
                        pagination={false}

                    />
                </div>

                <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 updateTableSortHandle = async (data: any[]) => {
        const resp = await editData({
            unitType:currentTabKey,
            retainList:data.map((a,index)=>({
                retainCode:a.retainCode,
                retainName:a.retainName,
                retainType:a.retainType,
                comment:a.comment,
                sort:index+1
            }))
        });
        if (resp) {
            tableRef.current?.reload();
        }
    }

    const onSortEnd = useRefFunction(
        ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => {
            if (oldIndex !== newIndex) {
                const newData = arrayMoveImmutable([...dataSource], oldIndex, 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} />;
    };

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


    useEffect(()=>{
        if(currentTabKey){
            set_tableDataFilterParams({...tableDataFilterParams,unitType:currentTabKey})
        }
    },[currentTabKey])

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

    return (
        <BMSPagecontainer className='JobCateRetenSet' title={false}>
            <ModalForm title={'添加保留项目'} width={400} submitter={{
                render: (props, defaultDoms) => []
            }} open={ifShowModal} modalProps={{
                closable: false,
            }}>
                <TableSelecter
                    ref={ref}
                    record={undefined}
                    tableSelecterColumn={tableSelecterColumn}
                ></TableSelecter>
            </ModalForm>
            {
                tabs.length > 0 && <Tabs
                    defaultActiveKey={currentTabKey}
                    onChange={(key)=>set_currentTabKey(key)}
                    items={tabs}
                />
            }
            <div className='toolBar'>
                <div className='filter'>
                    <div className='filterItem'>
                        <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                        <Input placeholder={'请输入项目名'} allowClear width={160}
                            suffix={
                                <IconFont type="iconsousuo" onClick={() => tableDataSearchHandle('filter')} />
                            }
                            onChange={(e) => {
                                set_tableDataSearchKeywords(e.target.value);
                                if (e.target.value.length == 0) {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        filter: ''
                                    });
                                }
                            }}
                            onPressEnter={(e) => {

                                set_tableDataFilterParams({
                                    ...tableDataFilterParams,
                                    filter: (e.target as HTMLInputElement).value
                                });
                            }}

                        />
                    </div>
                   
                </div>
                <div className='btnGroup'>
                <a className='add' onClick={() => { set_ifShowModal(true) }}>添加</a>
                </div>
            </div>

            <div style={{ marginTop: 16 }}>
                <BMSTable columns={columns as ProColumns[]} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} 
                request={(params) => getTableData(params)} 
                tableAlertRender={false}
                rowSelection={ {
                    onChange: onTableSelectChange,
                }}
                components={{
                    body: {
                        wrapper: DraggableContainer,
                        row: DraggableBodyRow,
                    },
                }}
                />
            </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={() => delTableData(tableSelectedKeys)}
                            >
                                <span className='batchDel'>批量删除</span>
                            </Popconfirm>

                        </div>
                    </div>
                )
            }

        </BMSPagecontainer>
    )
}
