import React, { useRef, useEffect, useState } from 'react';
import { InputNumber, Space, message, Popconfirm } from 'antd';
import {
    PageContainer,
    ProForm,
    ProFormText,
    ProFormTextArea,
    ProFormSwitch,
    ProFormSelect,
    ProFormRadio
} from '@ant-design/pro-components';
import { ContentUtils } from 'braft-utils'



// 引入编辑器组件
import BraftEditor from 'braft-editor'
// 引入编辑器样式
import 'braft-editor/dist/index.css'


import { useParams } from 'umi';

import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

import AuthConsumer from '@/components/Authority';
import FilesManager from '@/components/FilesManage/index';


import services from '@/services/admin';

const { articleCreate, articleUpdate, articleItem } = services.ArticleController;
const { articleCategoryItems } = services.ArticleCategoryController;

export default () => {
    const params = useParams();
    const [editorState, setEditorState] = useState(BraftEditor.createEditorState(''))


    const actionRef = useRef();

    const initRow = {
        id: '',
        cid: 1,
        is_up: 1,
        title: '',
        cover: '',
        video: '',
        note: null
    };

    const [row, setRow] = useState(initRow);
    const [note, setNote] = useState('');

    const modules = {
        toolbar: [
            ['bold', 'italic', 'underline', 'strike'],        // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'],// 字体样式
            ['link', 'image'],// 上传图片、上传视频

            [{ 'header': 1 }, { 'header': 2 }],                // 标题
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],// 有序列表，无序列表
            [{ 'script': 'sub' }, { 'script': 'super' }],      // 下角标，上角标
            [{ 'indent': '-1' }, { 'indent': '+1' }],          // 缩进
            [{ 'direction': 'rtl' }],                         // 文字输入方向

            // [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],// 标题

            [{ 'color': [] }, { 'background': [] }],          // 文字颜色、背景颜色选择
            [{ 'font': [] }],// 自定义字体
            [{ 'align': [] }],// 居中

            ['clean']                                         // remove formatting button
        ]
    }


    const controls = [
        'undo', 'redo', 'separator',
        'font-size', 'line-height', 'letter-spacing', 'separator',
        'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator',
        'superscript', 'subscript', 'remove-styles', 'emoji', 'separator', 'text-indent', 'text-align', 'separator',
        'headings', 'list-ul', 'list-ol', 'blockquote', 'code', 'separator',
        'link', 'separator', 'hr', 'separator',
        'clear'
    ]

    const handleCreate = async (fields) => {
        setRow(fields);
        const { success } = await articleCreate({ ...fields });

        if (success) {
            setRow(initRow);
            //history.push('article/0/create');
            history.back();
        }
    };

    const handleUpdate = async (fields) => {
        fields.note = editorState.toHTML()
        const { success } = await articleUpdate(fields);

        if (success) {
            setRow(initRow);
            history.back();
        }
    };

    const onChange = async (e) => {
        const videoExtensions = ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.m4v', '.3gp', '.3g2'];
        // 将URL转换为小写，以便进行不区分大小写的比较
        const lowerCaseUrl = e.toLowerCase();
        // 检查链接是否以任何一个视频扩展名结尾
        if (videoExtensions.some(e => lowerCaseUrl.endsWith(e))) {
            setEditorState(ContentUtils.insertMedias(editorState, [{
                type: 'VIDEO',
                url: e
            }]));
        } else {
            setEditorState(ContentUtils.insertMedias(editorState, [{ type: 'IMAGE', url: e, },]))
        }
    }

    const extendControls = [
        'separator',
        {
            key: 'FilesManagerImage', // 控件唯一标识，必传
            title: '上传图片/视频', // 指定鼠标悬停提示文案
            html: null, // 指定在按钮中渲染的html字符串
            text: <FilesManager
                fileType="image"
                mode=""
                imagesShow={false}
                onChange={onChange}
                count={1}
            />, // 指定按钮文字，此处可传入jsx，若已指定html，则text不会显示
            onClick: () => {
                console.log('Hello World!');
            },
        },
        // 'separator',
        // {
        //     key: 'FilesManagerVideo', // 控件唯一标识，必传
        //     title: '上传视频', // 指定鼠标悬停提示文案
        //     html: null, // 指定在按钮中渲染的html字符串
        //     text: <FilesManager
        //         fileType="video"
        //         mode=""
        //         imagesShow={false}
        //         onChange={onChange}
        //         count={1}
        //     />, // 指定按钮文字，此处可传入jsx，若已指定html，则text不会显示
        //     onClick: () => {
        //         console.log('Hello World!');
        //     },
        // }
    ]



    return (
        <PageContainer
            header={{
                title: '文章编辑',
            }}
            ghost
        >
            <>
                <ProForm
                    initialValues={row}
                    request={async () => {
                        const { data, success } = await articleItem(params);
                        if (success) {
                            setRow(data);
                            setNote(data.note);
                            setEditorState(BraftEditor.createEditorState(data.note))
                            return data;
                        }
                    }}
                    onFinish={(values) => {
                        handleUpdate(values)
                    }}
                >
                    <ProFormText hidden={true} width="md" name="id" />
                    <ProFormSelect
                        rules={[{ required: true, message: '请输入' }]}
                        name="cid"
                        label="所属栏目"
                        fieldProps={{
                            fieldNames: {
                                label: "name",
                                value: "id"
                            },
                        }}
                        request={async (param) => {
                            const { success, data } = await articleCategoryItems();
                            return data;
                        }}
                        placeholder="请选择"
                    />

                    <ProFormTextArea
                        rules={[{ required: true, message: '请输入' }]}
                        width="md"
                        name="title"
                        label="标题"
                        placeholder="请输入"
                    />
                    <ProForm.Group>
                        <ProForm.Item
                            label="封面图"
                            name="cover"
                        >
                            <FilesManager
                                fileType="image"
                                defaultValue={row?.cover}
                                count={1}
                                mode=""
                            />
                        </ProForm.Item>

                        <ProForm.Item
                            label="视频"
                            name="video"
                        >
                            <FilesManager
                                fileType="video"
                                defaultValue={row?.video}
                                count={1}
                                mode=""
                            />
                        </ProForm.Item>

                    </ProForm.Group>
                    <ProFormSwitch
                        rules={[{ required: true, message: '请输入' }]}
                        checkedChildren="发布"
                        unCheckedChildren="不发布"
                        defaultChecked
                        name="is_up"
                        label="发布"
                    />
                    <ProFormText
                        tooltip="如果为图文形式，可填写公众号文章连接"
                        name="oa_url"
                        label="公众号链接"
                        placeholder="公众号链接"
                    />
                    <ProForm.Item
                        label="富文本"
                        name="note"
                        tooltip="自定义详情内容，可插入图片、文本样式"
                    >
                        <div className="border-solid border-2 border-indigo-600">
                            <BraftEditor value={editorState} controls={controls} extendControls={extendControls} onChange={(val) => {
                                setEditorState(val)
                            }} />
                        </div>
                        {/* <ReactQuill
                            theme="snow"
                            value={note}
                            modules={modules}
                            onChange={(val) => {
                                setNote(val)
                            }}
                        /> */}
                    </ProForm.Item>
                </ProForm>
            </>
        </PageContainer>
    );
};
