import { KCIMTable } from "@/components/KCIMTable";
import SQLEditor from "@/components/SQLEditor";
import { FormInstance, ModalForm, ProColumns, ProFormDependency, ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from "@ant-design/pro-components";
import { useEffect, useRef, useState } from "react";
import { addData, editData, getReportListTableData, getReportListType } from "./service";
import { Form, Switch, Input, message } from 'antd'




import React from 'react';
import { createFromIconfontCN } from "@ant-design/icons";


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

interface UpDataActBtnProps {
    record: any;  // 根据实际情况定义类型
    type: 'EDIT' | 'ADD' | 'EDIT_CHILD';
    tableRef?: any,
    onUpdated?: () => void
}



const getTableData_form = 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 UpDateActBtn: React.FC<UpDataActBtnProps> = ({ record, type, tableRef, onUpdated }) => {
    // 组件逻辑
    const [tableDataSearchKeywords_form, set_tableDataSearchKeywords_form] = useState<string>('');
    const [tableDataFilterParams_form, set_tableDataFilterParams_form] = useState<any | undefined>();
    const [initialValues, set_initialValues] = useState<any | undefined>(undefined);
    const [isModalVisible, setIsModalVisible] = useState(false);

    const formRef = useRef<ProFormInstance>();
    const columnsTwo: ProColumns[] = [
        {
            title: '列代码',
            width: 80,
            dataIndex: 'code',
        },
        // {
        //     title: '列名称',
        //     dataIndex: 'name',
        //     ellipsis: true
        // },
        {
            title: '列标题',
            dataIndex: 'headerText',
            ellipsis: true
        },
        {
            title: '列类型',
            dataIndex: 'typeName',
            ellipsis: true,
            // render:(_:any)=>_ == 1?'指标':'自定义SQL'
        },
        {
            title: '操作',
            key: 'option',
            width: 50,
            valueType: 'option',
            render: (_: any, record: any) => {

                return [
                    <a key='edit_child' onClick={() => {
                        const _formula = formRef.current?.getFieldValue('formula');
                        formRef.current?.setFieldValue('formula', `${_formula ? _formula : ''}[${record.code}]`)
                    }}>选择</a>,
                ]
            },
        },

    ];

    const tableDataSearchHandle_form = (paramName: string) => {

        set_tableDataFilterParams_form({
            ...tableDataFilterParams_form,
            [`${paramName}`]: tableDataSearchKeywords_form
        })

    }

    const updateTable = async (formVal: any, type: 'EDIT' | "ADD" | 'EDIT_CHILD') => {

        let result = {
            name: formVal.name,
            headerText: formVal.headerText,
            type: formVal.type,
            dataType: formVal.dataType,
            dataSource: formVal.dataSource,
            formula: formVal.dataSource == 1 ? formVal.formula : '',
            sql: formVal.dataSource == 2 ? formVal.sql : '',
            decimalPlace: (formVal.dataType == 3 || formVal.dataType == 2) ? formVal.decimalPlace : undefined,
            permil: formVal.dataType == 3 ? (formVal.permil ? '1' : '0') : undefined
        }

        if (type == 'ADD') {
            const resp = await addData({ ...result });
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }
        }
        if (type == 'EDIT') {
            const resp = await editData({ ...result, id: formVal.id });
            if (resp) {
                tableRef?.current?.reload();
                message.success('操作成功！');
            }
        }
        setIsModalVisible(false);
        onUpdated && onUpdated();
        return true;

    }


    const setFormInit = async (record: any) => {
        const { columnHeaderText, columnCode } = record;
        const resp = await getReportListTableData({ columnName: columnHeaderText, pageSize: 500 });
        if (resp) {
            const { list } = resp;
            if (list.length > 1) {
                const result = list.filter((a) => a.code == columnCode);
                set_initialValues(result[0]);
            } else {
                set_initialValues(list[0]);
            }
        }

    }



    const openModal = async () => {
        
        if (record) {
            const { request } = record;
            if (request) {
                await setFormInit(record);
            } else {
                set_initialValues(type === 'EDIT' ? { ...record, permil: record.permil === '1' ? true : false } : { decimalPlace: 2, dataSource: 2, permil: false });
            }
        }

        setIsModalVisible(true);  // 在状态更新后显示模态框
    };


    return (
        <>
            {type === 'EDIT_CHILD' ?
                <a key="edit_child" onClick={openModal}>子列</a> :
                type === 'EDIT' ?
                    <a key="edit" onClick={openModal}>编辑</a> :
                    <span className='add' onClick={openModal}>新增</span>
            }
            {
              (
                    <ModalForm
                        title={`${type == 'EDIT' ? '编辑' : '新增'}报表列`}
                        width={880}
                        open={isModalVisible}
                        formRef={formRef}
                        initialValues={initialValues}
                        onOpenChange={bool=>setIsModalVisible(bool)}
                        onFinish={(val) => {
                            return updateTable(type == 'EDIT' ? (record.request?{...val,id:initialValues.id, sql: val.sql ? val.sql : ''}:{ ...record, ...val, sql: val.sql ? val.sql : '', }) : { ...val }, type);
                        }}
                        colProps={{ span: 24 }}

                        modalProps={{
                            destroyOnClose: true,
                            afterClose: () => setIsModalVisible(false),
                        }}
                        grid
                    >
                        {
                            (type != 'EDIT_CHILD') && (
                                <div className='formContent' style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'flex-start' }}>
                                    <div className='left' style={{ marginRight: 16, width: 240 }}>
                                        <ProFormText
                                            name="name"
                                            label="列名称："
                                            placeholder="请输入"
                                            rules={[{ required: true, message: '列名称不能为空!' }]}
                                        />
                                        <ProFormText
                                            name="headerText"
                                            label="列标题："
                                            placeholder="请输入"
                                            rules={[{ required: true, message: '列标题不能为空!' }]}
                                        />
                                        <ProFormSelect
                                            name="type"
                                            label="列类型："
                                            placeholder="请选择"
                                            request={async () => {
                                                const resp = await getReportListType();
                                                if (resp) {
                                                    return resp.map((a: any) => ({ label: a.name, value: a.code }));
                                                }
                                                return []
                                            }}
                                            rules={[{ required: true, message: '列类型不能为空!' }]}
                                        />


                                        <ProFormRadio.Group
                                            name="dataType"
                                            label="数据格式："
                                            options={[
                                                {
                                                    label: '文本',
                                                    value: 1,
                                                },
                                                {
                                                    label: '百分比',
                                                    value: 2,
                                                },
                                                {
                                                    label: '数值',
                                                    value: 3,
                                                },
                                            ]}
                                            rules={[{ required: true, message: '取数格式不能为空!' }]}
                                        />
                                        <ProFormDependency name={['dataType']}>
                                            {
                                                ({ dataType }) => (dataType == 3 || dataType == 2) && (
                                                    <div style={{ display: 'flex', flexDirection: 'row' }}>
                                                        <ProFormDigit
                                                            name="decimalPlace"
                                                            label="小数位："
                                                            colProps={{ span: 14 }}
                                                            placeholder="例：([1]+[2])/[3]"
                                                            rules={[{ required: true, message: '小数位不能为空!' }]}
                                                        />
                                                        {
                                                            dataType == 3 && (
                                                                <>
                                                                    <Form.Item name='permil'>
                                                                        <Switch size='small' style={{ marginTop: 26, marginLeft: 8 }} />
                                                                    </Form.Item>
                                                                    <span style={{ marginTop: 23, marginLeft: 4 }}>千分号</span>
                                                                </>
                                                            )
                                                        }
                                                    </div>

                                                )
                                            }
                                        </ProFormDependency>


                                        <ProFormSelect
                                            name="dataSource"
                                            label="取数类型："
                                            placeholder="请选择"
                                            options={[
                                                { label: '计算公式', value: 1 },
                                                { label: '自定义SQL', value: 2 }
                                            ]}
                                            rules={[{ required: true, message: '取数类型不能为空!' }]}
                                        />
                                    </div>
                                    <div className='right' style={{ width: 'calc(880px - 288px)' }}>
                                        <ProFormDependency name={['dataSource']}>
                                            {
                                                ({ dataSource }) => dataSource == 1 && (
                                                    <>
                                                        <ProFormTextArea
                                                            name="formula"
                                                            label={<>计算公式：</>}
                                                            // colProps={{ span: 16 }}
                                                            placeholder="例：([1]+[2])/[3]"
                                                            rules={[{ required: true, message: '计算公式不能为空!' }]}
                                                        />
                                                        <div style={{ padding: '0 4px' }}>
                                                            <div className='toolBar' style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                                                                <div>计算公式插入列：</div>
                                                                <div>
                                                                    <div className='filter' style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                                                                        <div className='filterItem' style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }} >
                                                                            <ProFormSelect noStyle placeholder={'列类型'}
                                                                                width={160}
                                                                                request={async () => {
                                                                                    const resp = await getReportListType();
                                                                                    if (resp) {
                                                                                        return resp.map((a: any) => ({ label: a.name, value: a.code }));
                                                                                    }
                                                                                    return []
                                                                                }}
                                                                                fieldProps={{
                                                                                    onChange(value, option) {
                                                                                        set_tableDataFilterParams_form({
                                                                                            ...tableDataFilterParams_form,
                                                                                            columnType: value
                                                                                        });
                                                                                    },
                                                                                }}
                                                                            />
                                                                        </div>
                                                                        <div className='filterItem' style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', marginLeft: 8 }} >
                                                                            <Input placeholder={'列标题'} allowClear width={160}
                                                                                suffix={
                                                                                    <IconFont type="iconsousuo" style={{ color: '#99A6BF' }} onClick={() => tableDataSearchHandle_form('columnName')} />
                                                                                }
                                                                                onChange={(e) => {
                                                                                    set_tableDataSearchKeywords_form(e.target.value);
                                                                                    if (e.target.value.length == 0) {
                                                                                        set_tableDataFilterParams_form({
                                                                                            ...tableDataFilterParams_form,
                                                                                            columnName: ''
                                                                                        });
                                                                                    }
                                                                                }}
                                                                                onPressEnter={(e) => {

                                                                                    set_tableDataFilterParams_form({
                                                                                        ...tableDataFilterParams_form,
                                                                                        columnName: (e.target as HTMLInputElement).value
                                                                                    });
                                                                                }}

                                                                            />
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>

                                                            <KCIMTable pagination={{ simple: true, pageSize: 7 }} columns={columnsTwo as ProColumns[]} rowKey='id' params={tableDataFilterParams_form} request={(params) => getTableData_form(params)} />
                                                        </div>
                                                    </>
                                                )
                                            }
                                        </ProFormDependency>
                                        <ProFormDependency name={['dataSource']}>
                                            {
                                                ({ dataSource }) => dataSource == 2 && (
                                                    <SQLEditor
                                                        name="sql"
                                                        label="SQL："
                                                        rules={[{ required: true, message: 'SQL不能为空!' }]}
                                                        form={formRef}
                                                        height={'500px'}
                                                    />
                                                    // <ProFormTextArea name={'sql'} label='取数来源：' rules={[{ required: true, message: '取数来源不能为空!' }]} />
                                                )
                                            }
                                        </ProFormDependency>
                                    </div>
                                </div>
                            )
                        }

                    </ModalForm>
                )
            }
        </>
    );
};

export default UpDateActBtn;


