import { useState, useEffect,useMemo } from "react";
import { Row, Col, Button, Flex, Table, Space, Modal, Form, Input, Radio, message, Popconfirm, InputNumber, Select } from "antd";
import { deleteReportTemplate, getReportTemplateList, saveReportTemplate, setupStandardTemplate, getTemplateComponentList, saveTemplateComponent, deleteComponent, getSystemComponentList } from '@/apis/report';
import { logger} from '@/apis/auth';
import styles from "./index.less";

const { TextArea } = Input;
const TemplatePage = () => {


    const [dataSource, setDataSource] = useState([]);
    const [loading, setLoading] = useState(false);

    const [open, setOpen] = useState(false);
    const [title, setTitle] = useState('');

    const [form] = Form.useForm();
    const [confirmLoading, setConfirmLoading] = useState(false);

    const [id, setId] = useState('');

    const [open2, setOpen2] = useState(false);
    const [loading2, setLoading2] = useState(false);


    const [dataSource2, setDataSource2] = useState([]);

    const [title2, setTitle2] = useState('');

    const [form2] = Form.useForm();

    const [title3, setTitle3] = useState('');

    const [open3, setOpen3] = useState(false);

    const [componentId, setComponentId] = useState('');


    const [componentList, setComponentList] = useState([]);

    const [open4, setOpen4] = useState(false);


    const [form3] = Form.useForm();

    const [originData, setOriginData] = useState({});

    const [showChart, setShowChart] = useState(false);
    const [showTable, setShowTable] = useState(false);





    const isAddComponent = useMemo(() => {
        
        let sum = 0;
        dataSource2?.forEach(item=>{
            sum +=  item?.pageQuantity
        });
        return sum > 34 ? true : false;
    }, [dataSource2]);


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

    useEffect(() => {
        if (open2) {
            getSystemComponentListInit();
        }
    }, [open2])

    useEffect(() => {
        if (!open4) {
            setShowChart(false);
            setShowTable(false);
        }
    }, [open4]);



    const init = async () => {
        setLoading(true);
        try {
            const res = await getReportTemplateList();
            setLoading(false);
            if (res.code === 200) {
                setDataSource(res?.data || [])

            }
        } catch (error) {
            setLoading(false);
            console.log(error, 'template-init-error');

        }
    };


    const getSystemComponentListInit = async () => {
        try {
            const res = await getSystemComponentList();
            if (res.code === 200) {
                setComponentList(res?.data || []);

            }
        } catch (error) {
            console.log(error, 'template-init-error');

        }
    };


    const handleAddTemplate = () => {
        setOpen(true);
        setTitle('添加模板');
        form.resetFields();
        setId('');

    };
    const handleEditTemplate = (record) => {
        setOpen(true);
        setTitle('编辑模板');
        setId(record?.id);
        form.setFieldsValue({
            ...record
        });
    };

    const handleOk = async () => {
        form.validateFields().then(async () => {
            try {
                setConfirmLoading(true);
                const res = await saveReportTemplate({ ...form.getFieldsValue(), id });
                if (res.code === 200) {
                    if(id){
                        await logger({description:"编辑模板"})
                    }else{
                        await logger({description:"添加模板"})
                    }
                    setConfirmLoading(false);
                    setOpen(false);
                    init();
                    message.success('操作成功');
    
                }
            } catch (error) {
                setConfirmLoading(false);
                console.log(error, 'save-template-error');
            }
            
        }).catch(error => {
            console.log(error,'error');
            
        });

    };


    const handleDelete = async (record) => {
        try {
            const res = await deleteReportTemplate({ id: record.id });
            if (res.code === 200) {
                await logger({description:"删除模板"});
                message.success('删除成功');
                init();
            }
        } catch (error) {
            console.log(error, 'delete-error');

        }
    };


    const handleSetupTemplate = async (record) => {
        try {
            const res = await setupStandardTemplate({ id: record.id });
            if (res.code === 200) {
                await logger({description:"设为标准模版"})
                message.success('操作成功');
                init();
            }
        } catch (error) {
            console.log(error, 'setup-error');

        }
    };

    const handleAllocation = async (record) => {
        setTitle2(`${record?.title}配置`);
        setId(record?.id);
        setOpen2(true);
        try {
            setLoading2(true);
            const res = await getTemplateComponentList({ id: record?.id });
            if (res?.code === 200) {
                setLoading2(false);
                setDataSource2(res?.data || []);
                return;
            }
            setLoading2(false);

        } catch (error) {
            setLoading2(false);
            console.log(error, 'get-components-error');

        }
    };

    const handleAddComponent = () => {
        setOpen4(true);
        form3.resetFields();
    };


    const handleOk2 = async () => {
        if(isAddComponent){
            Modal.confirm({
                title: '温馨提示',
                content: '配置组件中的页面数量已超过34页。为了您的报告展示效果，请合理配置组件。',
                okText: '确定',
                cancelText: '取消',
                centered:true,
                
            });
            return;
        }

        form2?.validateFields().then(async()=>{
            try {
                setConfirmLoading(true);
                const res = await saveTemplateComponent({ ...form2.getFieldsValue(), reportId: id, id: componentId });
            if (res.code === 200) {
                await logger({description:"编辑组件"})
                setConfirmLoading(false);
                setOpen3(false);
                componentsInit();
                setComponentId('');
                message.success('操作成功');

            }
            setConfirmLoading(false);

            } catch (error) {
                setConfirmLoading(false);
                console.log(error, 'save-template-error');
            }
        })

    };


    const componentsInit = async () => {
        try {
            const res = await getTemplateComponentList({ id, });
            if (res?.code === 200) {
                setDataSource2(res?.data || []);
                return;
            }
        } catch (error) {
            console.log(error, 'components-init-error');

        }
    };


    const handleDeleteComponent = async (record) => {
        try {
            const res = await deleteComponent({ id: record.id });
            if (res.code === 200) {
                await logger({description:"删除组件"})
                message.success('删除成功');
                componentsInit();
            }
        } catch (error) {
            console.log(error, 'delete-component-error');

        }

    };

    const handleEditComponent = (record) => {
        setTitle3('编辑组件');
        setComponentId(record?.id);
        setOriginData(record?.reportItemModel || {})
        form2.setFieldsValue({
            ...record
        });
        setOpen3(true);
    };


    const handleOk3 = async () => {

        form3.validateFields().then(async () => {
            try {
                setConfirmLoading(true);
                if(isAddComponent){
                    setConfirmLoading(false);
                    Modal.confirm({
                        title: '温馨提示',
                        content: '配置组件中的页面数量已超过34页。为了您的报告展示效果，请合理配置组件。',
                        okText: '确定',
                        cancelText: '取消',
                        centered:true,

                    });
                    return;
                }
                const id2 = form3.getFieldsValue()?.id;
                const element = componentList.find(item => item.id === id2);
                const data = {
                    title: form3.getFieldsValue()?.title,
                    reportId: id,
                    hrefModelId: element?.id,
                    type: element?.type,
                    showTable: form3.getFieldsValue()?.showTable,
                    showChart: form3.getFieldsValue()?.showChart,
                    showContent: form3.getFieldsValue()?.showContent,
                    sort: form3.getFieldsValue()?.sort,
                }
                const res = await saveTemplateComponent(data);
                if (res.code === 200) {
                    await logger({description:"添加组件"})
                    setConfirmLoading(false);
                    setOpen4(false);
                    componentsInit();
                    message.success('操作成功');
                    return;
    
                }
                setConfirmLoading(false);
    
            } catch (error) {
                setConfirmLoading(false);
                console.log(error, 'add-component-error');
    
            }
        }).catch(error=>{
            console.log(error,'fom3-validate-error');
            
        });
    };

    const columns = [
        {
            title: "模板名称",
            align: "center",
            dataIndex: "title",
            width: 220,
        },
        {
            title: "排序",
            align: "center",
            dataIndex: "sort",
            width: 100,
        },
        {
            title: "模板类型",
            align: "center",
            dataIndex: "reportType",
            width: 120,
            render(value) {
                if (value === 0) {
                    return '整体报告'
                }
                if (value === 1) {
                    return '教研报告'
                }
                return '-';
            }

        },
        {
            title: "是否为标准模板",
            align: "center",
            dataIndex: "isDefault",
            width: 140,
            render(value) {
                if (value === 0) {
                    return '否'
                }
                if (value === 1) {
                    return '是'
                }
                return '-';
            }

        },
        {
            title: "报告组件",
            align: "center",
            dataIndex: 'reportItemList',
            ellipsis:true,
            render(value) {
                if (!value.length) {
                    return '-';
                }
                return value?.map(item => item?.title)?.join(',')
            }

        },
        {
            title: "操作",
            align: "center",
            render: (_, record) => {
                return (
                    <Space>
                        <Button type="link" onClick={() => handleAllocation(record)}  >配置</Button>
                        <Popconfirm
                            title="温馨提示"
                            description="确定要设置为标准模板吗？"
                            onConfirm={() => handleSetupTemplate(record)}
                            okText="是"
                            cancelText="否"
                        >
                            <Button type="link" disabled={record?.isDefault === 1}>设为标准模板</Button>
                        </Popconfirm>

                        <Button type="link" onClick={() => handleEditTemplate(record)}>编辑</Button>
                        <Popconfirm
                            title="温馨提示"
                            description="确定要删除该报告吗？"
                            onConfirm={() => handleDelete(record)}
                            okText="是"
                            cancelText="否"
                        >
                            <Button type="link" danger>删除</Button>
                        </Popconfirm>

                    </Space>
                )
            }

        }
    ];

    const columns2 = [
        {
            title: "组件名称",
            align: "center",
            dataIndex: "title",
        },
        {
            title: "排序",
            align: "center",
            dataIndex: "sort",
        },
        {
            title: "内容",
            align: "center",
            dataIndex: "content",
        },
        {
            title: "页面数量",
            align: "center",
            dataIndex: "pageQuantity",
        },
        {
            title: "是否展示富文本",
            align: "center",
            dataIndex: "showContent",
            render(value) {
                if (value === 0) {
                    return '不展示';
                }
                if (value === 1) {
                    return '展示';

                }
                return '-'
            }
        },
        {
            title: "类型",
            align: "center",
            dataIndex: "type",
            render(value) {
                if (value === 0) {
                    return '首页';
                }
                if (value === 1) {
                    return '纯文本';
                }
                if (value === 2) {
                    return '表格图表';
                }
                if (value === 3) {
                    return '目录';
                }
                return '-';
            }
        },
        {
            title: "是否展示表格",
            align: "center",
            dataIndex: "showTable",
            render(value) {
                if (value === 0) {
                    return '不展示';
                }
                if (value === 1) {
                    return '展示';
                }
                return '-';
            }
        },
        {
            title: "是否展示图表",
            align: "center",
            dataIndex: "showChart",
            render(value) {
                if (value === 0) {
                    return '不展示';
                }
                if (value === 1) {
                    return '展示';
                }
                return '-';
            }
        },
        {
            title: "操作",
            align: "center",
            render: (_, record) => {
                return (
                    <Space>
                        <Button type="link" onClick={() => handleEditComponent(record)}>编辑</Button>
                        <Popconfirm
                            title="温馨提示"
                            description="确定要删除该报告吗？"
                            onConfirm={() => handleDeleteComponent(record)}
                            okText="是"
                            cancelText="否"
                        >
                            <Button type="link" danger>删除</Button>
                        </Popconfirm>

                    </Space>
                )
            }

        }
    ];

    return (
        <div className={styles.template}>
            <header className={styles.template_header}>
                <Button type="primary" onClick={handleAddTemplate}>添加模板</Button>
            </header>
            <main className={styles.template_main}>
                <Table
                    columns={columns}
                    dataSource={dataSource}
                    pagination={false}
                    loading={loading}
                    rowKey='id'
                />
            </main>
            <Modal
                title={title}
                open={open}
                maskClosable={false}
                centered
                destroyOnClose
                width={600}
                onOk={handleOk}
                confirmLoading={confirmLoading}
                onCancel={() => {
                    setOpen(false);
                    form.resetFields();
                }}
            >
                <Form
                    form={form}
                >
                    <Form.Item label="模板标题" name="title" rules={[
                        {
                            required: true,
                            message: '请填写标题',
                        },
                    ]}>
                        <Input placeholder="请输入标题" />
                    </Form.Item>
                    <Form.Item label="标准模板" name='isDefault'  rules={[
                        {
                            required: true,
                            message:"请选择"
                        },
                    ]}>
                        <Radio.Group
                            options={[
                                { value: 0, label: '否' },
                                { value: 1, label: '是' },
                            ]}
                        />
                    </Form.Item>
                    <Form.Item label="是否编辑" name='canEdit' rules={[
                        {
                            required: true,
                            message:"请选择"
                        },
                    ]}>
                        <Radio.Group
                            options={[
                                { value: 0, label: '否' },
                                { value: 1, label: '是' },
                            ]}
                        />
                    </Form.Item>
                    <Form.Item label="报告类型" name='reportType' rules={[
                        {
                            required: true,
                            message:"请选择"
                        },
                    ]}>
                        <Radio.Group
                            options={[
                                { value: 0, label: '整体报告' },
                                { value: 1, label: '教研报告' },
                            ]}
                        />
                    </Form.Item>
                    <Form.Item label="排序" name='sort'  rules={[
                        {
                            required: true,
                            message:"请填写排序"
                        },
                    ]}>
                        <InputNumber placeholder="请输入排序" style={{ width: '100%' }} />
                    </Form.Item>
                </Form>

            </Modal>

            <Modal
                title={title2}
                open={open2}
                maskClosable={false}
                centered
                destroyOnClose
                width={1200}
                styles={{ body: { height: "80vh", overflowY: "scroll" } }}
                onOk={() => {
                    setOpen2(false);
                    init();
                }}
                loading={loading2}
                onCancel={() => {
                    setOpen2(false);
                    init();
                }}
            >
                <header className={styles.template_header}>
                    <Space>
                        <Button type="primary" onClick={handleAddComponent} >添加组件</Button>
                    </Space>
                </header>
                <div>
                    <Table columns={columns2} dataSource={dataSource2} pagination={false} rowKey='id'/>
                </div>
            </Modal>

            <Modal
                title={title3}
                open={open3}
                maskClosable={false}
                centered
                destroyOnClose
                width={600}
                onOk={handleOk2}
                confirmLoading={confirmLoading}
                onCancel={() => {
                    setOpen3(false);
                    form2.resetFields();
                    setComponentId('');
                }}
            >
                <Form
                    layout="vertical"
                    form={form2}
                >
                    <Form.Item label="组件名称" name="title"  rules={[
                        {
                            required: true,
                            message: '请填写组件名称',
                        },
                    ]}>
                        <Input placeholder="请输入组件名称" />
                    </Form.Item>
                    <Form.Item label="是否展示富文本" name='showContent'  rules={[
                        {
                            required: true,
                            message:"请选择"
                        },
                    ]}>
                        <Radio.Group
                            options={[
                                { value: 0, label: '否' },
                                { value: 1, label: '是' },
                            ]}
                        />
                    </Form.Item>
                    <Form.Item label="页面数量(页面数量应根据具体表格数量、图标表数量、文本等总和)" name='pageQuantity' rules={[
                        {
                            required: true,
                            message:"请输入页面数量"
                        },
                    ]}>
                            <InputNumber placeholder="请输入页面数量" style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item label="内容" name='content'>
                        <TextArea
                            placeholder="请输入内容"
                            autoSize={{
                                minRows: 2,
                                maxRows: 6,
                            }}
                        />
                    </Form.Item>
                    <Form.Item label="参数" name='params'>
                        <TextArea
                            placeholder="请输入参数"
                            autoSize={{
                                minRows: 2,
                                maxRows: 6,
                            }}
                        />
                    </Form.Item>

                    <Form.Item label="类型" name='type'  rules={[
                        {
                            required: true,
                            message:"请选择"
                        },
                    ]}>
                        <Radio.Group
                            options={[
                                { value: 0, label: '首页' },
                                { value: 1, label: '纯文本' },
                                { value: 2, label: '表格图表' },
                                { value: 3, label: '目录' },
                            ]}
                        />
                    </Form.Item>
                    {originData?.hasTable ? (<Form.Item label="是否展示表格" name='showTable'  rules={[
                        {
                            required: true,
                            message:"请选择"
                        },
                    ]}>
                        <Radio.Group
                            options={[
                                { value: 0, label: '否' },
                                { value: 1, label: '是' },
                            ]}
                        />
                    </Form.Item>) : null}
                    {originData?.hasChart ? (<Form.Item label="是否展示图表" name='showChart'  rules={[
                        {
                            required: true,
                            message:"请选择"
                        },
                    ]}>
                        <Radio.Group
                            options={[
                                { value: 0, label: '否' },
                                { value: 1, label: '是' },
                            ]}
                        />
                    </Form.Item>) : null}
                    <Form.Item label="排序" name='sort'  rules={[
                        {
                            required: true,
                            message:"请填写排序"
                        },
                    ]}>
                        <InputNumber placeholder="请输入排序" style={{ width: '100%' }} />
                    </Form.Item>
                </Form>
            </Modal>

            <Modal
                title='添加组件'
                open={open4}
                maskClosable={false}
                centered
                destroyOnClose
                width={600}
                onOk={handleOk3}
                confirmLoading={confirmLoading}
                onCancel={() => {
                    setOpen4(false);
                    form3.resetFields();
                }}
            >
                <Form
                    layout="vertical"
                    form={form3}
                >
                    <Form.Item label="组件名称" name="title"  rules={[
                        {
                            required: true,
                            message: '请填写组件名称',
                        },
                    ]}>
                        <Input placeholder="请输入组件名称" />
                    </Form.Item>
                    <Form.Item label="绑定组件" name="id"  rules={[
                        {
                            required: true,
                            message:"请选择绑定组件"
                        },
                    ]}>
                        <Select placeholder="请选择绑定组件" allowClear onChange={(value) => {
                            const element = componentList.find(item => item.id === value);
                            form3.setFieldValue('showTable', element?.hasTable);
                            form3.setFieldValue('showChart', element?.hasChart);
                            setShowTable(!!element?.hasTable);
                            setShowChart(!!element?.hasChart);
                        }} options={componentList?.map(item => {
                            return {
                                value: item.id,
                                label: item.name
                            }
                        })} style={{ width: '100%' }} />
                    </Form.Item>
                    {showTable ? (<Form.Item label="是否展示表格" name='showTable'  rules={[
                        {
                            required: true,
                            message:"请选择"
                        },
                    ]}>
                        <Radio.Group
                            options={[
                                { value: 0, label: '否' },
                                { value: 1, label: '是' },
                            ]}
                        />
                    </Form.Item>) : null}
                    {showChart ? (<Form.Item label="是否展示图表" name='showChart'
                    rules={[
                        {
                            required: true,
                            message:"请选择"
                        },
                    ]}
                    >
                        <Radio.Group
                            options={[
                                { value: 0, label: '否' },
                                { value: 1, label: '是' },
                            ]}
                        />
                    </Form.Item>) : null}
                    <Form.Item label="页面数量(页面数量应根据具体表格数量、图标表数量、文本等总和)"  name='pageQuantity' rules={[
                        {
                            required: true,
                            message:"请输入页面数量"
                        },
                    ]}>
                            <InputNumber placeholder="请输入页面数量" style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item label="是否展示富文本" name='showContent'
                        rules={[
                        {
                            required: true,
                            message:"请选择"
                        },
                    ]}
                    >
                        <Radio.Group
                            options={[
                                { value: 0, label: '否' },
                                { value: 1, label: '是' },
                            ]}
                        />
                    </Form.Item>
                    <Form.Item label="排序" name='sort'
                        rules={[
                        {
                            required: true,
                            message: '请填写排序',
                        },
                    ]}
                    >
                        <InputNumber placeholder="请输入排序" style={{ width: '100%' }} />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default TemplatePage;
