import { contentUpdate, contentPage, contentAdd, contentDelete } from '@/services/note/note';


import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage, useAccess } from '@umijs/max';
import { Button, message, Modal, Image } from 'antd';
import { ActionType, FooterToolbar, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { PlusOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import UpdateForm from './edit';
import { DataNode } from 'antd/es/tree';


/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');
    try {
        fields.status = fields.status ? 0 : 1
        await contentAdd({ ...fields });
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.System.Menu) => {
    const hide = message.loading('正在修改');
    try {
        await contentUpdate(fields);
        hide();
        message.success('修改成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};

const handleRemoveOne = async (selectedRow: API.System.Menu) => {
    const hide = message.loading('正在删除');
    if (!selectedRow) return true;
    try {
        const params = [selectedRow.id];
        await contentDelete(params);
        hide();
        message.success('删除成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};


const MenuTableList: React.FC = () => {

    const [modalVisible, setModalVisible] = useState<boolean>(false);

    const intRow = {
        "id": 1,
        "imageUrl": "",
        "sortOrder": 0,
        "status": 0,
        "title": "",
        "jumpUrl": ""
    }


    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState(intRow);
    const access = useAccess();

    /** 国际化配置 */
    const intl = useIntl();

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

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            valueType: 'text',
            search: false,
        },
        {
            title: '标题',
            dataIndex: 'title',
            valueType: 'text',
            search: true,
        },
        {
            title: '封面图',
            dataIndex: 'cover',
            valueType: 'image',
            search: false,
            render: (_: any, record: any) => {
                return <Image src={record.cover} width={45} height={45}></Image>
            }
        },
        // {
        //     title: '视频地址',
        //     dataIndex: 'video',
        //     valueType: 'text',
        //     search: false,
        // },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'text',
            search: false,
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: '220px',
            valueType: 'option',
            render: (_, record) => [
                <Button
                    type="link"
                    size="small"
                    hidden={!access.hasPerms('/api/content/update')}
                    onClick={() => {
                        setModalVisible(true);
                        setCurrentRow(record);
                    }}
                >
                    编辑
                </Button>,
                <Button
                    type="link"
                    size="small"
                    danger
                    hidden={!access.hasPerms('/api/content/deleteBatchByIds')}
                    onClick={async () => {
                        Modal.confirm({
                            title: '删除',
                            content: '确定删除该项吗？',
                            okText: '确认',
                            cancelText: '取消',
                            onOk: async () => {
                                const success = await handleRemoveOne(record);
                                if (success) {
                                    if (actionRef.current) {
                                        actionRef.current.reload();
                                    }
                                }
                            },
                        });
                    }}
                >
                    删除
                </Button>,
            ],
        },

    ];

    return (
        <PageContainer>
            <div style={{ width: '100%', float: 'right' }}>
                <ProTable<API.System.Menu>
                    actionRef={actionRef}
                    rowKey="id"
                    key="menuList"
                    search={{
                        labelWidth: 120,
                    }}
                    toolBarRender={() => [
                        <Button
                            type="primary"
                            key="add"
                            hidden={!access.hasPerms('/api/content/add')}
                            onClick={async () => {
                                setCurrentRow(undefined);
                                setModalVisible(true);
                            }}
                        >
                            <PlusOutlined /> 新建
                        </Button>
                    ]}
                    request={async (params, sorter, filter) => {
                        let { data } = await contentPage(params)
                        return {
                            data: data?.records || [],
                            total: data?.total,
                        };
                    }}
                    columns={columns}
                />
            </div>
            <UpdateForm
                onSubmit={async (values) => {
                    let success = false;
                    if (values.id) {
                        success = await handleUpdate({ ...values });
                    } else {
                        success = await handleAdd({ ...values });
                    }
                    if (success) {
                        setModalVisible(false);
                        setCurrentRow(undefined);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={() => {
                    setModalVisible(false);
                    setCurrentRow(undefined);
                }}
                open={modalVisible}
                values={currentRow || {}}
            />
        </PageContainer>
    );
};

export default MenuTableList;
