import SQLEditor from "@/components/SQLEditor";
import { ModalForm, ProFormDependency, ProFormRadio, ProFormSelect, ProFormText } from "@ant-design/pro-components";
import { useEffect, useRef, useState } from "react";
import { message } from 'antd';
import { addData, editData, getManaIndic, getReportListTableData, getReportListTypeFromDic } from "./service";

export const ReportListManaUpDataActBtn = ({ record, type, onFinishedhandle }: { record: any, type: 'EDIT' | 'ADD' | 'EDIT_CHILD', onFinishedhandle: () => void }) => {

    const [expand, set_expand] = useState(false);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [initialValues, set_initialValues] = useState<any | undefined>(undefined);

    const formRef = useRef();

    const updateTable = async (formVal: any, type: 'EDIT' | "ADD" | 'EDIT_CHILD') => {
        if (type == 'ADD') {
            if (formVal.dataSource == 1) {
                //
                let result = {
                    name: formVal.name,
                    headerText: formVal.headerText,
                    dataSource: formVal.dataSource,
                    columnType: formVal.columnType,
                    dataType: formVal.dataType,
                    sql: '',
                    indicatorCode: formVal.indicatorCode.key,
                    indicatorCodeName: formVal.indicatorCode.label,
                }

                const resp = await addData({ ...result });
                if (resp) {
                    onFinishedhandle && onFinishedhandle()
                }

            }
            if (formVal.dataSource == 2) {
                //sql
                let result = {
                    name: formVal.name,
                    headerText: formVal.headerText,
                    dataSource: formVal.dataSource,
                    columnType: formVal.columnType,
                    dataType: formVal.dataType,
                    sql: formVal.sql,
                    indicatorCode: '',
                    indicatorCodeName: ''
                }

                const resp = await addData({ ...result });
                if (resp) {
                    onFinishedhandle && onFinishedhandle()
                }
            }



        }
        if (type == 'EDIT') {

            if (formVal.dataSource == 1) {
                //指标
                const result = {
                    id: formVal.id,
                    name: formVal.name,
                    headerText: formVal.headerText,
                    dataSource: formVal.dataSource,
                    columnType: formVal.columnType,
                    dataType: formVal.dataType,
                    sql: '',
                    indicatorCode: formVal.indicatorCode.key,
                    indicatorCodeName: formVal.indicatorCode.label,
                }
                const resp = await editData({ ...result });
                if (resp) {
                    onFinishedhandle && onFinishedhandle()
                }

            }

            if (formVal.dataSource == 2) {
                //sql
                const result = {
                    id: formVal.id,
                    name: formVal.name,
                    headerText: formVal.headerText,
                    dataSource: formVal.dataSource,
                    columnType: formVal.columnType,
                    dataType: formVal.dataType,
                    sql: formVal.sql,
                    indicatorCode: '',
                    indicatorCodeName: ''
                }
                const resp = await editData({ ...result });
                if (resp) {
                    onFinishedhandle && onFinishedhandle()
                }
            }


        }
        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 onOpenChangeHandle = (visible: boolean) => {
        setIsModalVisible(visible);
    }

    const openModal = async () => {
        console.log('openModal')
        if (record) {
            const { request } = record;
            if (request) {
                await setFormInit(record);
            } else {
                set_initialValues(type == 'EDIT' ? { ...record, indicatorCode: { label: record.indicatorCodeName, value: record.indicatorCode } } : {});
            }
        }

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


    useEffect(() => {
        if (initialValues) {
            set_expand(initialValues.dataSource == 2)
        }
    }, [initialValues]);

    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={expand ? 880 : 352}
                formRef={formRef}
                initialValues={initialValues}
                open={isModalVisible}
                onOpenChange={onOpenChangeHandle}
                // trigger={
                //     type == 'EDIT_CHILD' ? <a key="edit_child" >子列</a> : type == 'EDIT' ? <a key="edit" >编辑</a> : <span className='add'>新增</span>
                // }
                onFinish={(val) => {

                    return updateTable(type == 'EDIT' ? {...initialValues,...val, sql: val.sql ? val.sql : '', } : { ...val }, type);
                }}
                colProps={{ span: 24 }}

                modalProps={{
                    destroyOnClose: true,

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


                                <ProFormRadio.Group
                                    name="dataType"
                                    label="数据格式："
                                    options={[
                                        {
                                            label: '文本',
                                            value: 1,
                                        },
                                        {
                                            label: '金额',
                                            value: 2,
                                        },
                                        {
                                            label: '数值',
                                            value: 3,
                                        },
                                        {
                                            label: '百分比',
                                            value: 4,
                                        },
                                    ]}
                                    rules={[{ required: true, message: '取数格式不能为空!' }]}
                                />


                                <ProFormSelect
                                    name="dataSource"
                                    label="取数类型："
                                    placeholder="请选择"
                                    fieldProps={{
                                        onChange(value, option) {
                                            set_expand(value == 2)
                                        },
                                    }}
                                    options={[
                                        { label: '指标', value: 1 },
                                        { label: '自定义SQL', value: 2 }
                                    ]}
                                    rules={[{ required: true, message: '取数类型不能为空!' }]}
                                />
                                <ProFormDependency name={['dataSource']}>
                                    {
                                        ({ dataSource }) => dataSource == 1 && (
                                            <ProFormSelect
                                                name="indicatorCode"
                                                label="取数来源："
                                                placeholder="请选择"
                                                fieldProps={{
                                                    labelInValue: true
                                                }}
                                                request={async () => {
                                                    const resp = await getManaIndic();
                                                    if (resp) {
                                                        return resp.map((a: any) => ({ label: a.name, value: a.code }))
                                                    }
                                                }}
                                                rules={[{ required: true, message: '数据来源不能为空!' }]}
                                            />
                                        )
                                    }
                                </ProFormDependency>
                            </div>

                            <ProFormDependency name={['dataSource']}>
                                {
                                    ({ dataSource }) => dataSource == 2 && (
                                        <div className='right' style={{ width: 'calc(880px - 290px)' }}>
                                            <SQLEditor
                                                name="sql"
                                                label="SQL："
                                                rules={[{ required: true, message: 'SQL不能为空!' }]}
                                                form={formRef}
                                                height={'260px'}
                                            />
                                        </div>

                                    )
                                }
                            </ProFormDependency>
                        </div>
                    )
                }
                {/* {
                (type == 'EDIT_CHILD') && (
                    <>
                        <ProFormText
                            name="name"
                            label="列名称："
                            placeholder="请输入"
                            rules={[{ required: true, message: '列名称不能为空!' }]}
                        />
                        <ProFormText
                            name="headerText"
                            label="列标题："
                            placeholder="请输入"
                            rules={[{ required: true, message: '列标题不能为空!' }]}
                        />
                        <ProFormSelect
                            name="columnType"
                            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: '列类型不能为空!' }]}
                        />

                        <ProFormCheckbox.Group
                            name="checkbox"
                            layout="vertical"
                            label="取数格式："
                            options={['文本','金额','数值','百分比']}
                        />

                        <ProFormSelect
                            name="dataSource"
                            label="取数类型："
                            placeholder="请选择"
                            options={[
                                { label: '指标', value: 1 },
                                { label: '自定义SQL', value: 2 }
                            ]}
                            rules={[{ required: true, message: '取数类型不能为空!' }]}
                        />
                        <ProFormDependency name={['dataSource']}>
                            {
                                ({ dataSource }) => dataSource == 1 && (
                                    <ProFormSelect
                                        name="indicatorCode"
                                        label="取数来源："
                                        placeholder="请选择"
                                        fieldProps={{
                                            labelInValue: true
                                        }}
                                        request={async () => {
                                            const resp = await getManaIndic();
                                            if (resp) {
                                                return resp.map((a: any) => ({ label: a.name, value: a.code }))
                                            }
                                        }}
                                        rules={[{ required: true, message: '数据来源不能为空!' }]}
                                    />
                                )
                            }
                        </ProFormDependency>
                        <ProFormDependency name={['dataSource']}>
                            {
                                ({ dataSource }) => dataSource == 2 && (
                                    <ProFormTextArea name={'sql'} label='SQL：' rules={[{ required: true, message: 'SQL不能为空!' }]} />
                                )
                            }
                        </ProFormDependency>
                    </>
                )
            } */}



            </ModalForm>
        </>

    )
}