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 { useParams } from '@umijs/max';
import FilesManager from '@/components/FilesManage/index';
import { ContentUtils } from 'braft-utils'


import { goodsAdd } from '@/services/goods/index';


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




// 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 = {
        "goodsName": "",
        "itemType": "",
        "salePrice": '',
        "profit": '',
        "picture": "",
        "details": "",
        "stock": '',
        "sales": '',
        "isUp": 1
    };

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

    useEffect(() => {
        // articleItem(params).then(({ data }) => {
        //     if (data) {
        //         setRow(data);
        //     }
        // });
    }, []);


    const handleCreate = async (fields) => {
        setRow(fields);
        let data = JSON.parse(JSON.stringify(fields))
        // data.details = editorState.toHTML()
        data.isUp = data.isUp ? 1 : 0
        data.picture = JSON.stringify(data.picture)
        data.details = JSON.stringify(data.details)
        const { success } = await goodsAdd({ ...data });
        if (success) {
            message.success('添加成功')
            setRow(initRow);
            //history.push('article/0/create');
            history.back();
        }
    };

    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 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}
                    onFinish={(values) => {
                        handleCreate(values)
                    }}
                >
                    <ProFormTextArea
                        rules={[{ required: true, message: '请输入' }]}
                        width="md"
                        name="goodsName"
                        label="商品名称"
                        placeholder="请输入"
                    />
                    <ProFormText
                        rules={[{ required: true, message: '请输入!' }]}
                        width={300}
                        name="itemType"
                        label="功率"
                        placeholder="功率"
                    />
                    <ProForm.Group>
                        <ProForm.Item
                            rules={[{ required: true, message: '请输入!' }]}
                            label="销售价格"
                            name={'salePrice'}
                        >
                            <InputNumber style={{ width: 200 }} />
                        </ProForm.Item>
                        <ProForm.Item
                            rules={[{ required: true, message: '请输入!' }]}
                            label="商品利润"
                            name={'profit'}
                        >
                            <InputNumber style={{ width: 200 }} />
                        </ProForm.Item>
                    </ProForm.Group>
                    <ProForm.Group>
                        <ProForm.Item
                            rules={[{ required: true, message: '请输入!' }]}
                            label="库存"
                            name={'stock'}
                        >
                            <InputNumber style={{ width: 200 }} />
                        </ProForm.Item>
                        <ProForm.Item
                            rules={[{ required: true, message: '请输入!' }]}
                            label="销量"
                            name={'sales'}
                        >
                            <InputNumber style={{ width: 200 }} />
                        </ProForm.Item>
                    </ProForm.Group>


                    <ProForm.Group>
                        <ProForm.Item
                            label="主图"
                            name="picture"
                            tooltip="商品的封面图"
                        >
                            <FilesManager
                                fileType="image"
                                defaultValue={row?.picture}
                                count={9}
                                mode=""
                            />
                        </ProForm.Item>
                    </ProForm.Group>
                    <ProFormSwitch
                        checkedChildren="上架"
                        unCheckedChildren="下架"
                        name="isUp"
                        label="是否上架"
                    />
                    <ProForm.Group>
                        <ProForm.Item
                            label="详情图"
                            name="details"
                            tooltip="商品的详情图"
                        >
                            <FilesManager
                                fileType="image"
                                defaultValue={row?.details}
                                count={9}
                                mode=""
                            />
                        </ProForm.Item>
                    </ProForm.Group>
                    {/* <ProForm.Item
                        label="富文本"
                        name="details"
                        tooltip="自定义详情内容，可插入图片、文本样式"
                    >
                        <div className="border-solid border-2 border-indigo-600">
                            <BraftEditor value={editorState} controls={controls} extendControls={extendControls} onChange={(val) => {
                                setEditorState(val)
                            }} />
                        </div>
                    </ProForm.Item> */}
                </ProForm>
            </>
        </PageContainer>
    );
};
