/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-03 11:31:03
 * @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 SQLEditor from '@/components/SQLEditor';
import { createFromIconfontCN, MenuOutlined } from '@ant-design/icons';

import { ActionType, ProFormText, ProFormTextArea, useRefFunction } from '@ant-design/pro-components';
import { ModalForm, ProFormDependency, ProFormDigit, ProFormSelect } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Switch } from 'antd';
import { arrayMoveImmutable } from 'array-move';
import { useEffect, useRef, useState } from 'react';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import { getClolumnTableData, getReportColumn } from '../reportSetting/service';

import { addData, delData, editData, getSqlListTableData, getSqlTypeList, updateTableSort } from './service';

import './style.less';



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


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


export default function DiySqlMana() {

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

    const [dataSource, set_dataSource] = useState<any[]>([]);
    const [showList, set_showList] = useState<any[]>([]);

    const SortableItem = SortableElement((props: any) => <tr {...props} />);
    const SortContainer = SortableContainer((props: any) => <tbody {...props} />);

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

    const tableRef = useRef<ActionType>();

    const columns: ProColumns[] = [
        {
            dataIndex: 'sort',
            width: 50,
            className: 'drag-visible',
            render: () => <DragHandle />
        },
        {
            title: 'SQL代码',
            width: 150,
            ellipsis: true,
            dataIndex: 'sqlCode',
        },
        {
            title: 'SQL语句',
            ellipsis: true,
            dataIndex: 'sql',
        },
        {
            title: 'SQL说明',
            ellipsis: true,
            dataIndex: 'sqlDefinition',
            // render:(_:any)=>_ == 1?'指标':'自定义SQL'
        },
        {
            title: '启用',
            width: 80,
            dataIndex: 'status',
            renderText: (_: any, record: any) => {

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

    ]


    const getTableData = async (params: any) => {
        const resp = await getSqlListTableData({ ...params,pageSize:500 });
        if (resp) {
            set_dataSource(resp.list);
            set_showList(resp.list);
        }
        return []
    }

    const getSqlTypeRequest = async () => {
        const resp = await getSqlTypeList();
        if (resp) {
            set_typeList(resp.list);
            set_showTypeListArr(resp.list);
        }
    }

    const delTableData = async (record: any) => {
        const resp = await delData(record.id);
        if (resp) {
            message.success('操作成功！');
            getTableData({ sqlType: currentSelectedType.code });
            // 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" | 'ADD_NEXT') => {

        if (type == 'ADD') {
            const resp = await addData({
                sqlCode: formVal.sqlCode,
                sql: formVal.sql,
                sqlDefinition: formVal.sqlDefinition,
                sqlType: currentSelectedType.code,
                sort: dataSource.length + 1,
                status: 1
            });
            if (resp) {
                getTableData({ sqlType: currentSelectedType.code });
                message.success('操作成功！');
            }

        }

        if (type == 'ADD_NEXT') {
            const { sort } = formVal;

            const temp = [...dataSource];

            const index = temp.findIndex(a => a.sort == sort);

            const objectToInsert = {
                sqlCode: formVal.sqlCode,
                sql: formVal.sql,
                sqlDefinition: formVal.sqlDefinition,
                sqlType: currentSelectedType.code,
                status: 1
            }

            temp.splice(index + 1, 0, objectToInsert);
            const arr = temp.map((a, index) => ({ ...a, sort: index + 1 }));
            updateTableSortHandle(arr);


        }

        if (type == 'EDIT') {

            const resp = await editData({
                id: formVal.id,
                sql: formVal.sql,
                sqlDefinition: formVal.sqlDefinition,
                sqlType: formVal.sqlType,
                sort: formVal.sort,
                status: formVal.status
            });
            if (resp) {
                getTableData({ sqlType: currentSelectedType.code });
                message.success('操作成功！');
            }
        }
        return true;

    }

    const formRef = useRef();

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

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : type == 'ADD_NEXT' ? '插入' : '新增'}自定义SQL`}
                width={1200}
                formRef={formRef}
                initialValues={type == 'EDIT' ? { ...record } : {}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : type == 'ADD_NEXT' ? <a>插入</a> : <span className='add'>新增</span>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val } : type == 'ADD_NEXT' ? { ...record, ...val } : { ...val }, type);
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >
                <div className='formContent' style={{ display: 'flex',width:'100%', flexDirection: 'row', alignContent: 'flex-start',overflow:'hidden'}}>
                    <div className='left' style={{ width: 240,minWidth:240, marginRight: 16 }}>
                        <ProFormText
                            name="sqlCode"
                            label="SQL代码："
                            placeholder="请输入"
                            disabled={type == 'EDIT'}
                            rules={[{ required: true, message: 'SQL代码不能为空!' }]}
                        />
                        <ProFormTextArea fieldProps={{rows:18}} placeholder="请输入" name={'sqlDefinition'} label='SQL说明：' rules={[{ required: true, message: '说明不能为空!' }]} />

                    </div>
                    <div className='right' style={{ width: 'calc(1200px - 288px)',marginBottom:'-15px'}}>
                        {/* <ProFormTextArea placeholder="请输入" name={'sql'} label='SQL语句：' rules={[{ required: true, message: 'SQL不能为空!' }]} /> */}
                        <SQLEditor
                            name="sql"
                            label="SQL语句："
                            rules={[{ required: true, message: 'SQL不能为空!' }]}
                            form={formRef}
                            height={'435px'}
                        />
                    </div>
                </div>
            </ModalForm>
        )
    }

    const tableDataSearchHandle = (key: string) => {
        const result = dataSource.filter((a) => a.sqlDefinition.indexOf(tableDataSearchKeywords) != -1);
        set_showList(result);
    }


    const updateTableSortHandle = async (data: any[]) => {
        const resp = await updateTableSort(data);
        if (resp) {
            getTableData({ sqlType: currentSelectedType.code });
        }
    }

    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} />;
    };

    useEffect(() => {
        if (showTypeListArr.length > 0) {
            set_currentSelectedType(showTypeListArr[0]);
        }
    }, [showTypeListArr]);

    useEffect(() => {
        if (currentSelectedType) {
            getTableData({ sqlType: currentSelectedType.code });
        }
    }, [currentSelectedType]);

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

    return (
        <BMSPagecontainer className='DiySqlMana' title={false}>
            <div className='left'>
                <Input placeholder={'请输入类目名称'} allowClear
                    suffix={
                        <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" />
                    }
                    onChange={(e) => {
                        const result = typeList.filter(item => item.name.indexOf(e.target.value) != -1);
                        set_showTypeListArr(result);
                    }}

                />
                <div className='wrap'>
                    {
                        showTypeListArr.map((item, index) => {
                            return (
                                <div className={currentSelectedType ? currentSelectedType.id == item.id ? 'type on' : 'type' : 'type'}
                                    key={index}
                                    onClick={() => set_currentSelectedType(item)}
                                >{item.name}</div>
                            )
                        })
                    }
                </div>
            </div>
            <div className='right'>
                <div className='toolBar'>
                    <div className='filter'>
                        <div className='filterItem'>
                            <span className='label'>检索：</span>
                            <Input placeholder={'sql说明'} style={{ width: 160 }} allowClear

                                suffix={
                                    <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" onClick={() => tableDataSearchHandle('sqlDefinition')} />
                                }
                                onChange={(e) => {
                                    set_tableDataSearchKeywords(e.target.value);
                                    if (e.target.value.length == 0) {
                                        set_tableDataSearchKeywords('');
                                        getTableData({ sqlType: currentSelectedType.code });
                                    }
                                }}

                                onPressEnter={(e) => {
                                    tableDataSearchHandle('sqlDefinition')
                                }}

                            />
                        </div>
                    </div>
                    <div className='btnGroup'>
                        <UpDataActBtn record type='ADD' />
                    </div>
                </div>
                <div style={{ marginTop: 16 }}>
                    {currentSelectedType && <BMSTable scroll={{ y: `calc(100vh - 230px)` }} actionRef={tableRef} columns={columns as ProColumns[]} rowKey='id'
                        dataSource={showList}
                        tableAlertRender={false}
                        pagination={false}
                        components={{
                            body: {
                                wrapper: DraggableContainer,
                                row: DraggableBodyRow,
                            },
                        }}
                    />}
                </div>
            </div>
        </BMSPagecontainer>
    )
}
