/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-04-11 19:51:04
 * @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, ProFormText, ProFormTextArea } 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 } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { getClolumnTableData, getReportColumn } from '../reportSetting/service';

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

import './style.less';


const IconFont = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/c/font_1927152_4nm5kxbv4m3.js',
});



export default function DiySqlMana() {

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

    const columns: ProColumns[] = [

        {
            title: 'SQL代码',
            dataIndex: 'sqlCode',
        },
        {
            title: 'SQL语句',
            dataIndex: 'sql',
        },
        {
            title: 'SQL说明',
            dataIndex: 'sqlDefinition',
            // render:(_:any)=>_ == 1?'指标':'自定义SQL'
        },
        {
            title: 'SQL类型',
            dataIndex: 'sqlTypeName',
        },
        {
            title: '序号',
            dataIndex: 'sort',
        },
        {
            title: '操作',
            key: 'option',
            width: 120,
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <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);
        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 updateTable = async (formVal: any, type: 'EDIT' | "ADD") => {

        if (type == 'ADD') {
            const resp = await addData({
                sqlCode: formVal.sqlCode,
                sql: formVal.sql,
                sqlDefinition: formVal.sqlDefinition,
                sqlType: formVal.sqlType.value,
                sort: formVal.sort
            });
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }

        }
        if (type == 'EDIT') {

            const resp = await editData({
                id: formVal.id,
                sql: formVal.sql,
                sqlDefinition: formVal.sqlDefinition,
                sqlType: formVal.sqlType,
                sort: formVal.sort
            });
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }
        }
        return true;

    }

    const formRef = useRef();

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

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}报表列`}
                width={352}
                formRef={formRef}
                initialValues={type == 'EDIT' ? { ...record } : {}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <span className='add'>新增</span>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val } : { ...val }, type);
                }}
                colProps={{ span: 24 }}
                grid
            >
                {
                    type != 'EDIT' && (
                        <ProFormText
                            name="sqlCode"
                            label="SQL代码："
                            placeholder="请输入"
                            rules={[{ required: true, message: '列名称不能为空!' }]}
                        />
                    )
                }

                <ProFormTextArea placeholder="请输入" name={'sql'} label='SQL语句：' rules={[{ required: true, message: 'SQL不能为空!' }]} />
                <ProFormTextArea placeholder="请输入" name={'sqlDefinition'} label='SQL说明：' rules={[{ required: true, message: '说明不能为空!' }]} />

                <ProFormSelect
                    name="sqlType"
                    label="SQL类型："
                    placeholder="请选择"
                    request={async () => {
                        const resp = await getSqlTypeList();

                        if (resp) {
                            return resp.list.map((a: any) => ({ label: a.name, value: a.code }))
                        }
                    }}
                    fieldProps={{
                        labelInValue: true
                    }}
                    rules={[{ required: true, message: '类型不能为空!' }]}
                />
                <ProFormDigit
                    name="sort"
                    label="顺序号："
                    placeholder="请输入"
                    rules={[{ required: true, message: '顺序号不能为空!' }]}
                />

            </ModalForm>
        )
    }

    const tableDataSearchHandle = (paramName: string) => {

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

    }


    useEffect(() => {

    }, [])

    return (
        <BMSPagecontainer className='DiySqlMana' title={false}>
            <div className='toolBar'>
                <div className='filter'>
                    <div className='filterItem'>
                        <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                        <Input placeholder={'请输入SQL类型'} allowClear
                            suffix={
                                <IconFont type="iconsousuo" onClick={() => tableDataSearchHandle('sqlType')} />
                            }
                            onChange={(e) => {
                                set_tableDataSearchKeywords(e.target.value);
                                if (e.target.value.length == 0) {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        sqlType: ''
                                    });
                                }
                            }}
                            onPressEnter={(e) => {

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

                        />
                    </div>
                </div>
                <div className='btnGroup'>
                    <UpDataActBtn 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>
    )
}
