import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import {
    ActionType,
    ModalForm,
    PageContainer,
    ProColumns,
    ProForm,
    ProFormSelect,
    ProFormText,
    ProFormUploadButton,
    ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, message, Space, Tag, Image, Modal, App } from 'antd';
import React, { useRef, useState } from 'react';
import type { ArticleItem, ArticleParams } from './data';
import { queryArticleList, addArticle, updateArticle, removeArticle } from '@/services/article';
import RichTextEditor from '@/components/RichTextEditor';
import styles from './index.module.css';

const ArticlePage: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<ArticleItem>();
    const intl = useIntl();

    const handleAdd = async (fields: Partial<ArticleItem>) => {
        const hide = message.loading(intl.formatMessage({ id: 'common.loading', defaultMessage: '正在添加' }));
        try {
            await addArticle({ ...fields });
            hide();
            message.success(intl.formatMessage({ id: 'common.success.add', defaultMessage: '添加成功' }));
            return true;
        } catch (error) {
            hide();
            message.error(intl.formatMessage({ id: 'common.error.add', defaultMessage: '添加失败' }));
            return false;
        }
    };

    const handleUpdate = async (fields: Partial<ArticleItem>) => {
        const hide = message.loading(intl.formatMessage({ id: 'common.loading', defaultMessage: '正在更新' }));
        try {
            if (currentRow?.id) {
                await updateArticle(currentRow.id, fields);
                hide();
                message.success(intl.formatMessage({ id: 'common.success.update', defaultMessage: '更新成功' }));
                return true;
            }
            return false;
        } catch (error) {
            hide();
            message.error(intl.formatMessage({ id: 'common.error.update', defaultMessage: '更新失败' }));
            return false;
        }
    };

    const handleRemove = async (selectedRows: ArticleItem[]) => {
        if (!selectedRows) return true;
        const hide = message.loading(intl.formatMessage({ id: 'common.loading', defaultMessage: '正在删除' }));
        try {
            await Promise.all(selectedRows.map((row) => removeArticle(row.id)));
            hide();
            message.success(intl.formatMessage({ id: 'common.success.delete', defaultMessage: '删除成功' }));
            return true;
        } catch (error) {
            hide();
            message.error(intl.formatMessage({ id: 'common.error.delete', defaultMessage: '删除失败' }));
            return false;
        }
    };

    const columns: ProColumns<ArticleItem>[] = [
        {
            title: <FormattedMessage id="pages.article.columns.title" defaultMessage="标题" />,
            dataIndex: 'title',
            width: 200,
            render: (dom, entity) => (
                <Space>
                    <Image src={entity.cover} width={40} height={40} style={{ borderRadius: 4, objectFit: 'cover' }} />
                    <span style={{ fontWeight: 500 }}>{dom}</span>
                </Space>
            ),
        },
        {
            title: <FormattedMessage id="pages.article.columns.category" defaultMessage="分类" />,
            dataIndex: 'category',
            width: 100,
        },
        {
            title: <FormattedMessage id="pages.article.columns.status" defaultMessage="状态" />,
            dataIndex: 'status',
            width: 100,
            valueEnum: {
                draft: {
                    text: <FormattedMessage id="pages.article.status.draft" />,
                    status: 'Default',
                },
                published: {
                    text: <FormattedMessage id="pages.article.status.published" />,
                    status: 'Success',
                },
                hidden: {
                    text: <FormattedMessage id="pages.article.status.hidden" />,
                    status: 'Error',
                },
            },
        },
        {
            title: <FormattedMessage id="pages.article.columns.publishTime" defaultMessage="发布时间" />,
            dataIndex: 'publishTime',
            valueType: 'dateTime',
            hideInSearch: true,
            width: 150,
        },
        {
            title: <FormattedMessage id="common.action" defaultMessage="操作" />,
            dataIndex: 'option',
            valueType: 'option',
            width: 150,
            render: (_, record) => [
                <a
                    key="edit"
                    onClick={() => {
                        handleModalVisible(true);
                        setCurrentRow(record);
                    }}
                >
                    <EditOutlined /> <FormattedMessage id="common.edit" />
                </a>,
                <a key="preview" onClick={() => Modal.info({ title: record.title, content: <div dangerouslySetInnerHTML={{ __html: record.htmlContent }} />, width: 800 })}>
                    <EyeOutlined /> <FormattedMessage id="common.preview" defaultMessage="预览" />
                </a>,
            ],
        },
    ];

    return (
        <App>
            <PageContainer>
                <ProTable<ArticleItem, ArticleParams>
                    headerTitle={intl.formatMessage({ id: 'pages.article.title', defaultMessage: '文章管理' })}
                    actionRef={actionRef}
                    rowKey="id"
                    search={{
                        labelWidth: 120,
                    }}
                    toolBarRender={() => [
                        <Button
                            type="primary"
                            key="primary"
                            onClick={() => {
                                handleModalVisible(true);
                                setCurrentRow(undefined);
                            }}
                        >
                            <PlusOutlined /> <FormattedMessage id="pages.article.form.new" />
                        </Button>,
                    ]}
                    request={queryArticleList}
                    columns={columns}
                    rowSelection={{
                        onChange: (_, selectedRows) => {
                            // console.log(selectedRows);
                        },
                    }}
                    className={styles.proTable}
                />

                <ModalForm
                    title={currentRow ? intl.formatMessage({ id: 'pages.article.form.edit', defaultMessage: '编辑文章' }) : intl.formatMessage({ id: 'pages.article.form.new', defaultMessage: '新建文章' })}
                    width="1000px"
                    open={createModalVisible}
                    onOpenChange={handleModalVisible}
                    autoFocusFirstInput={false}
                    onFinish={async (value) => {
                        const data = { ...value };
                        if (Array.isArray(value.cover)) {
                            data.cover = value.cover[0]?.url || value.cover[0]?.thumbUrl || value.cover[0]?.response?.url;
                        }
                        const success = currentRow ? await handleUpdate(data) : await handleAdd(data);
                        if (success) {
                            handleModalVisible(false);
                            if (actionRef.current) {
                                actionRef.current.reload();
                            }
                        }
                    }}
                    initialValues={currentRow ? {
                        ...currentRow,
                        cover: currentRow.cover ? [{ uid: '-1', url: currentRow.cover, status: 'done' }] : []
                    } : { status: 'draft' }}
                    modalProps={{
                        destroyOnHidden: true,
                        maskClosable: false,
                    }}
                >
                    <ProFormText
                        name="title"
                        label={intl.formatMessage({ id: 'pages.article.columns.title', defaultMessage: '标题' })}
                        rules={[{ required: true, message: intl.formatMessage({ id: 'pages.article.form.title.required', defaultMessage: '请输入标题' }) }]}
                    />
                    <Space align="start" style={{ display: 'flex' }}>
                        <ProFormSelect
                            name="category"
                            label={intl.formatMessage({ id: 'pages.article.columns.category', defaultMessage: '分类' })}
                            options={[
                                { label: '技术框架', value: '技术框架' },
                                { label: '设计规范', value: '设计规范' },
                                { label: '产品资讯', value: '产品资讯' },
                            ]}
                            width="sm"
                            rules={[{ required: true, message: intl.formatMessage({ id: 'pages.article.form.category.required', defaultMessage: '请选择分类' }) }]}
                        />
                        <ProFormSelect
                            name="status"
                            label={intl.formatMessage({ id: 'pages.article.columns.status', defaultMessage: '状态' })}
                            valueEnum={{
                                draft: intl.formatMessage({ id: 'pages.article.status.draft', defaultMessage: '草稿' }),
                                published: intl.formatMessage({ id: 'pages.article.status.published', defaultMessage: '已发布' }),
                                hidden: intl.formatMessage({ id: 'pages.article.status.hidden', defaultMessage: '隐藏' }),
                            }}
                            width="sm"
                        />
                    </Space>

                    <ProFormUploadButton
                        name="cover"
                        label={intl.formatMessage({ id: 'pages.article.columns.cover', defaultMessage: '封面' })}
                        max={1}
                        fieldProps={{
                            listType: 'picture-card'
                        }}
                    />

                    <div style={{ marginBottom: 16 }}>
                        <label style={{ display: 'block', marginBottom: 8, fontWeight: 'bold' }}>
                            {intl.formatMessage({ id: 'pages.article.form.content.label', defaultMessage: '文章内容' })}
                        </label>
                        <ProForm.Item name="htmlContent" noStyle>
                            <RichTextEditor />
                        </ProForm.Item>
                    </div>
                </ModalForm>
            </PageContainer>
        </App>
    );
};

export default ArticlePage;
