/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-02-29 17:00:32
 * @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, ProFormCheckbox, ProFormRadio } from '@ant-design/pro-components';
import { ModalForm, ProFormDependency, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm } from 'antd';
import { useEffect, useRef, useState } from 'react';

import { addChildReportList, addData, delData, editData, getChildReportList, getManaIndic, getReportListTableData, getReportListType, getReportListTypeFromDic } from './service';

import './style.less';

import '../../../../utils/zhongtaiB';
import React from 'react';
import SQLEditor from '@/components/SQLEditor';
import { ReportListManaUpDataActBtn } from './UpDataActBtn';
const IconFont = createFromIconfontCN({
    scriptUrl: '',
});



export default function ReportListMana() {

    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 [ifShowModal, set_ifShowModal] = useState(false);

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

    const columns: ProColumns[] = [

        {
            title: '列名称',
            dataIndex: 'name',
            ellipsis: true
        },
        {
            title: '列标题',
            dataIndex: 'headerText',
            ellipsis: true
        },
        {
            title: '列类型',
            dataIndex: 'columnTypeName',
            ellipsis: true,
            // render:(_:any)=>_ == 1?'指标':'自定义SQL'
        },
        {
            title: '取数类型',
            dataIndex: 'dataSource',
            ellipsis: true,
            //render: (_: any) => _ == 1 ? '指标' : '自定义SQL',
            renderText(num, record, index, action) {
                return num == 1 ? '指标' : '自定义SQL'
            },
        },
        {
            title: '取数来源',
            width: 200,
            ellipsis: true,
            dataIndex: 'sql',
            render: (_: any, record: any) => {

                if (record.sql) return record.sql;
                if (record.indicatorCodeName) return record.indicatorCodeName
            }
        },
        {
            title: '子列',
            width: 200,
            ellipsis: true,
            dataIndex: 'childColumnList',
            render: (_: any, record: any) => {
                if (record.childColumnList) {
                    return record.childColumnList.reduce((prev: any, cur: any) => {
                        return `${prev.length > 0 ? prev + '|' : prev}${cur.headerText}`
                    }, '')
                }

            }
        },
        {
            title: '操作',
            key: 'option',
            width: 120,
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <a key='edit_child' onClick={() => { set_currentEditRow(record); set_ifShowModal(true) }}>子列</a>,
                    <ReportListManaUpDataActBtn onFinishedhandle={()=>{tableRef.current?.reload();message.success('操作成功！')}}  key={'act'} record={record} type='EDIT' />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },

    ]

    const tableSelecterColumn: ProColumns[] = [
        {
            title: '列名称',
            dataIndex: 'name',
            ellipsis: true
            // render:(_:any)=>_ == 1?'指标':'自定义SQL'
        },
        {
            title: '列标题',
            dataIndex: 'headerText',
            ellipsis: true
            // render:(_:any)=>_ == 1?'指标':'自定义SQL'
        },
    ]


    const getTableData = async (params: any) => {
        const resp = await getReportListTableData(params);
        if (resp) {
            return {
                data: resp.list,
                success: true,
                total: resp.totalCount,
                pageSize: resp.pageSize,
                totalPage: resp.totalPage,
            }
        }
        return []
    }

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



    const tableDataSearchHandle = (paramName: string) => {

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

    }


    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 getChildReportList(currentEditRow.code);
            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 () => {
            const result = selectedRows.map(a => ({
                code: a.code,
                columnType: a.columnType,
                dataSource: a.dataSource,
                dataType: a.dataType,
                headerText: a.headerText,
                indicatorCode: a.indicatorCode,
                indicatorCodeName: a.indicatorCodeName,
                name: a.name,
                sql: a.sql
            }))
            const resp = await addChildReportList({
                parentCode: currentEditRow.code,
                childColumnList: result
            });
            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='code'
                        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>

        )
    });


    useEffect(() => {

    }, [])

    return (
        <BMSPagecontainer className='ReportListMana' title={false}>
            <ModalForm title={`选择子报表列(${currentEditRow && currentEditRow.headerText})`} width={400} submitter={{
                render: (props, defaultDoms) => []
            }} open={ifShowModal} modalProps={{
                closable: false,
            }}>
                <TableSelecter
                    ref={ref}
                    record={undefined}
                    tableSelecterColumn={tableSelecterColumn}
                ></TableSelecter>
            </ModalForm>
            <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('columnName')} />
                            }
                            onChange={(e) => {
                                set_tableDataSearchKeywords(e.target.value);
                                if (e.target.value.length == 0) {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        columnName: ''
                                    });
                                }
                            }}
                            onPressEnter={(e) => {

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

                        />
                    </div>
                    <div className='filterItem' style={{ marginLeft: 16 }}>
                        <span className='label' style={{ whiteSpace: 'nowrap' }}> 类型：</span>
                        <ProFormSelect noStyle placeholder={'请选择类型'}
                            width={160}
                            request={async () => {
                                const resp = await getReportListTypeFromDic();
                                if (resp) {
                                    return resp.list.map((a: any) => ({ label: a.name, value: a.code }));
                                }
                                return []
                            }}
                            fieldProps={{
                                onChange(value, option) {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        columnType: value
                                    });
                                },
                            }}
                        />
                    </div>
                </div>
                <div className='btnGroup'>
                    <ReportListManaUpDataActBtn onFinishedhandle={()=>{tableRef.current?.reload();message.success('操作成功！')}}   record type='ADD' />
                </div>
            </div>

            <div style={{ marginTop: 16 }}>
                <BMSTable columns={columns as ProColumns[]} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params) => getTableData(params)} />
            </div>
        </BMSPagecontainer>
    )
}
