/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-07-07 13:46:13
 * @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, arrayMoveImmutable, useRefFunction } from '@ant-design/pro-components';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Dropdown, Input, MenuProps, message, Modal, Switch, Table } from 'antd';
import { ColumnsType, TableRowSelection } from 'antd/es/table/interface';
import Transfer, { TransferItem, TransferProps } from 'antd/es/transfer';
import React from 'react';
import { useEffect, useImperativeHandle, useRef, useState } from 'react';


import difference from 'lodash/difference';

import { getReportColumn, getClolumnTableData, addReport, editReport, editReportTbaleData, delLeftReportData } from './service';


import './style.less';

import { addReportTableList, getReportListTableData, getReportListType } from '../reportListMana/service';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';

import '../../../../utils/zhongtaiB'
const IconFont = createFromIconfontCN({
    scriptUrl: '',
});

var temp_dataSource: any[] = [];

const ReportSetting = () => {

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

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



    const [dataSource, setDataSource] = useState<any[]>([]);
    const SortableItem = SortableElement((props: any) => <tr {...props} />);
    const SortContainer = SortableContainer((props: any) => <tbody {...props} />);

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

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

    const tableRef = useRef<ActionType>();

    const DragHandle = SortableHandle(() => <img width={16} style={{ cursor: 'pointer' }} src={require('../../../../../static/tuozhuai_icon.png')} alt="" />);

    const column = [

        {
            title: '列名称',
            width: 120,
            ellipsis: true,
            dataIndex: 'columnName',

        },
        {
            title: '列标题',
            width: 160,
            dataIndex: 'columnHeaderText',

        },
        {
            title: '主键',
            width: 120,
            dataIndex: 'primaryKey',
            render: (_: any, record: any) => {
                return <Switch disabled={!ifEditTable} size='small' checked={_} onChange={(bool) => switchChangeHandle(bool, record, 'primaryKey')} />
            }
        },
        {
            title: '隐藏',
            width: 120,
            dataIndex: 'hide',
            render: (_: any, record: any) => {
                return <Switch disabled={!ifEditTable} size='small' checked={_} onChange={(bool) => switchChangeHandle(bool, record, 'hide')} />
            }
        },
    ]

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




    const getTableData = async (params: any) => {
        const { reportCode } = params;

        if (reportCode) {
            const resp = await getClolumnTableData(params);
            if (resp) {
                //const dataSorted = resp.sort((prev:any,cur:any)=>prev.sort - cur.sort);
                setDataSource(resp);
                temp_dataSource = [...resp];
                
            }

        }

    }

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

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

        setDataSource([...newData]);
    }

    //获取左侧单元
    const getPageLeftReports = async () => {
        const resp = await getReportColumn();

        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 addReport({
                reportName: formVal.reportName,
                reportShortName: formVal.reportShortName,
                reportType: formVal.reportType
            });
            if (resp) {
                getPageLeftReports();
            }
        }



        if (type == 'EDIT_LEFTDATA') {
            const resp = await editReport({
                id: formVal.id,
                reportName: formVal.reportName,
                reportShortName: formVal.reportShortName,
                reportType: formVal.reportType
            });
            if (resp) {
                getPageLeftReports();
            }
        }

        if (type == 'EDIT') {

            let newDataSource = dataSource.map((a: any, index: number) => {
                //更新排序
                return { ...a, sort: index + 1 }
            })
            const resp = await editReportTbaleData(newDataSource);
            set_ifEditTable(false);
            if (resp) {
                getTableData({ reportCode: currentSelectedType.code });
            }
        }

        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='reportName'
                    rules={[{ required: true, message: '报表名称不能为空!' }]}
                />
                <ProFormText
                    label='报表简称：'
                    name='reportShortName'
                    rules={[{ required: true, message: '报表简称不能为空!' }]}
                />
                <ProFormSelect
                    name="reportType"
                    label="报表类型："
                    placeholder="请选择"
                    request={async () => {
                        const resp = await getReportListType();
                        if (resp) {
                            return resp.list.map((a: any) => ({ label: a.name, value: a.code }))
                        }
                    }}
                    rules={[{ required: true, message: '列类型不能为空!' }]}
                />
            </ModalForm>
        )
    }



    interface DataType {
        key: string;
        title: string;
        description: string;
        disabled: boolean;
        tag: string;
    }

    interface TableTransferProps extends TransferProps<TransferItem> {
        dataSource: DataType[];
        leftColumns: ColumnsType<DataType>;
        rightColumns: ColumnsType<DataType>;
        record: any
    }


    const transferTableColumn: any[] = [
        {
            title: '列名称',
            dataIndex: 'name',
            with: 100,
            ellipsis: true,
            key: 'name',
        },
        {
            title: '列标题',
            width: 120,
            dataIndex: 'headerText',
            key: 'headerText',
            ellipsis: true
        },
    ];

    const addReportColumnHandle = () => {

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

        Modal.confirm({
            title: `选择报表列`,
            icon: <></>,
            width: 750,
            centered: true,
            okText: '确定',
            cancelText: '取消',
            content: <TableTransfer
                ref={ref}
                record={undefined}
                leftColumns={transferTableColumn}
                rightColumns={transferTableColumn} dataSource={[]}
            ></TableTransfer>,
            onOk: () => {
                return ref.current && ref.current.save();
            }
        })
    }

    const TableTransfer = React.forwardRef(({ leftColumns, rightColumns, record, ...restProps }: TableTransferProps, ref) => {


        const [targetKeys, setTargetKeys] = useState<string[]>([]);
        const [datasource, set_datasource] = useState<any[]>([]);
        const [selectedKeys, setSelectedKeys] = useState<string[]>([]);

        //获取报表列管理
        const getFuncList = async () => {
            const resp = await getReportListTableData({ pageSize: 100000, current: 1 });
            if (resp) {

                set_datasource(resp.list);

                const defaultSelctedkeys = dataSource.map((item: any) => item.columnCode);

                setTargetKeys(defaultSelctedkeys);

            }
        }

        const onChange = (nextTargetKeys: string[]) => {
            setTargetKeys(nextTargetKeys);
        };

        const onSelectChange = (sourceSelectedKeys: string[], targetSelectedKeys: string[]) => {
            //console.log('sourceSelectedKeys:', sourceSelectedKeys,'targetSelectedKeys:',targetSelectedKeys);
            setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
        };

        useImperativeHandle(ref, () => ({
            save: async () => {
                const needData = datasource.filter(item => targetKeys.includes(item.code));

                const result = needData.map((a,index) => {
                    const hasEditedInfo = dataSource.filter((c: any) => c.columnCode == a.code);
                    return {
                        reportCode: currentSelectedType.code,
                        columnCode: a.code,
                        columnHeaderText: a.headerText,
                        columnName: a.name,
                        sort: hasEditedInfo.length>0?hasEditedInfo[0].sort:dataSource.length+1,
                        primaryKey:hasEditedInfo.length>0?hasEditedInfo[0].primaryKey:0,
                        hide:hasEditedInfo.length>0?hasEditedInfo[0].hide:0,
                    }
                });

                const resp = await addReportTableList(result);

                if (resp) {
                    message.success('添加成功！');
                    getTableData({ reportCode: currentSelectedType.code });
                }
            }
        }));

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

        return (
            <Transfer className='TableTransfer' showSearch
                titles={['待选项', '已选项']}
                locale={{
                    itemUnit: '项',
                    itemsUnit: '项',
                    searchPlaceholder: '请输入'
                }}
                onChange={onChange}
                onSelectChange={onSelectChange}
                dataSource={datasource}
                rowKey={record => record.code}
                targetKeys={targetKeys}
                selectedKeys={selectedKeys}
                filterOption={(inputValue, item) => {
                    return item.headerText!.indexOf(inputValue) !== -1

                }}
            >
                {({
                    direction,
                    filteredItems,
                    onItemSelectAll,
                    onItemSelect,
                    selectedKeys: listSelectedKeys,
                    disabled: listDisabled,
                }) => {

                    // console.log({ filteredItems, listSelectedKeys,direction });
                    const columns = direction === 'left' ? leftColumns : rightColumns;

                    const rowSelection: TableRowSelection<TransferItem> = {
                        getCheckboxProps: (item) => ({ disabled: listDisabled || item.disabled }),
                        onSelectAll(selected, selectedRows) {
                            const treeSelectedKeys = selectedRows.map(({ code }) => code);
                            const diffKeys = selected
                                ? difference(treeSelectedKeys, listSelectedKeys)
                                : difference(listSelectedKeys, treeSelectedKeys);
                            onItemSelectAll(diffKeys as string[], selected);
                        },
                        onSelect({ code }, selected) {
                            onItemSelect(code as string, selected);
                        },
                        selectedRowKeys: listSelectedKeys,
                    };

                    return (
                        <BMSTable
                            rowSelection={rowSelection}
                            columns={columns as TransferItem[]}
                            dataSource={filteredItems}
                            size="small"
                            rowKey={'code'}
                            scroll={{y:830}}
                            tableAlertRender={false}
                            pagination={{simple:true,pageSize:9,showTotal:()=>false}}
                            style={{ pointerEvents: listDisabled ? 'none' : undefined }}
                            onRow={({ code, disabled: itemDisabled }) => ({
                                onClick: () => {
                                    if (itemDisabled || listDisabled) return;
                                    onItemSelect(code as string, !listSelectedKeys.includes(code as string));
                                },
                            })}
                        />
                    );
                }}
            </Transfer>
        )
    })

    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) {
                        getPageLeftReports();
                    }
                }}>
                    删除
                </a>
            ),
        },
        {
            key: '3',
            label: (<a onClick={async (e) => {
                e.preventDefault();
                // 选取要复制的文本
                const textToCopy = currentEditLeftData.code;

                // 创建一个临时的textarea元素
                const tempTextArea = document.createElement("textarea");
                tempTextArea.value = textToCopy;
                document.body.appendChild(tempTextArea);

                // 选中并复制文本
                tempTextArea.select();
                document.execCommand("copy");

                // 移除临时元素
                document.body.removeChild(tempTextArea);
                message.success('复制成功！');

            }}>
                复制报表code
            </a>),
        },
    ];



    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}))
                setDataSource([...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) {
            set_tableDataFilterParams({ ...tableDataFilterParams, reportCode: currentSelectedType.code });
            getTableData({ reportCode: currentSelectedType.code });
        }
    }, [currentSelectedType])

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

    useEffect(() => {
        if (ifEditTable) {
            set_tableColumn([{
                title: '排序',
                dataIndex: 'sort',
                width: 60,
                className: 'drag-visible',
                render: () => <DragHandle />
            }, ...column,
                // {
                //     title: '操作',
                //     key: 'option',
                //     width: 120,
                //     valueType: 'option',
                //     render: (_: any, record: any) => {
                //         return [
                //             <Popconfirm
                //                 title="是否确认移除？"
                //                 key="del"
                //                 onConfirm={() => { delData(record.id); getTableData({ reportCode: currentSelectedType.code }); }}
                //             >
                //                 <a>移除</a>
                //             </Popconfirm>
                //         ]
                //     },
                // }
            ])
        } else {
            set_tableColumn(column);
        }
    }, [ifEditTable]);

    useEffect(() => {
        temp_dataSource = [...dataSource];
    }, [dataSource])

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



    return (
        <BMSPagecontainer title={false} className='ReportSetting'>
            <div className='left'>
                <div className='toolbar'>
                    <Input placeholder={'报表名称'} allowClear
                        suffix={
                            <IconFont type="iconsousuo" />
                        }
                        style={{ width: 156 }}
                        onChange={(e) => {
                            const result = typeList.filter(item => item.reportName.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);
                                                    getTableData({ reportCode: item.code });
                                                },
                                            })
                                        } else {
                                            set_currentSelectedType(item)
                                        }
                                    }}
                                >
                                    <img className='icon' src={require('../../../../../static/reportIcon.png')} alt="" />
                                    <div className='content'>
                                        <div className='name'>{item.reportName}</div>
                                        <div className='sub'>{item.reportTypeName}</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'>
                    </div>
                    <div className='btnGroup'>
                        {!ifEditTable && <span className='manaBtn' onClick={() => set_ifEditTable(true)}>管理列</span>}
                        {
                            ifEditTable && (
                                <div className='inner'>
                                    <span className='save' onClick={() => updateTable(undefined, 'EDIT')}>保存</span>
                                    <span className='add' onClick={() => addReportColumnHandle()}>添加列</span>
                                </div>
                            )
                        }
                    </div>
                </div>
                <div style={{ marginTop: 16 }}>
                    {currentSelectedType && <BMSTable actionRef={tableRef} columns={tableColumn}
                        scroll={{y:500}}
                        rowKey='id' dataSource={dataSource}
                        pagination={false}
                        components={{
                            body: {
                                wrapper: DraggableContainer,
                                row: DraggableBodyRow,
                            },
                        }}
                    />}
                </div>
            </div>
        </BMSPagecontainer>
    )
}


export default ReportSetting;
