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

import { useParams } from '@umijs/max';
import FilesManager from '@/components/FilesManage/index';
import { ContentUtils } from 'braft-utils'
import TableTransfer from '@/components/TableTransfer';



import { goodspackagesAdd, goodspackagesPage } from '@/services/goods/setMeal';
import { goodsPage } 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 [goodsList, setGoodsList] = useState([])
    const [goodsNum, setGoodsNum] = useState([])

    const actionRef = useRef();

    const initRow = {
        "packagesName": "",
        "salePrice": '',
        "profit": '',
        "picture": "",
        "details": "",
        "goodsDataList": [],
        "isUp": 1
    };


    // const TableTransfer = (props) => {
    //     const { leftColumns, rightColumns, ...restProps } = props;
    //     return (
    //         <Transfer
    //             style={{
    //                 width: '100%',
    //             }}
    //             {...restProps}
    //         >
    //             {({
    //                 direction,
    //                 filteredItems,
    //                 onItemSelect,
    //                 onItemSelectAll,
    //                 selectedKeys: listSelectedKeys,
    //                 disabled: listDisabled,
    //             }) => {
    //                 const columns = direction === 'left' ? leftColumns : rightColumns;
    //                 const rowSelection = {
    //                     getCheckboxProps: () => ({
    //                         disabled: listDisabled,
    //                     }),
    //                     onChange(selectedRowKeys, selectedRows) {
    //                         onItemSelectAll(selectedRowKeys, 'replace');

    //                     },
    //                     selectedRowKeys: listSelectedKeys,
    //                     selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT, Table.SELECTION_NONE],
    //                 };
    //                 return (
    //                     <Table
    //                         rowSelection={rowSelection}
    //                         columns={columns}
    //                         dataSource={filteredItems}
    //                         size="small"
    //                         style={{
    //                             pointerEvents: listDisabled ? 'none' : undefined,
    //                         }}
    //                         rowKey={'id'}
    //                         onRow={({ key, disabled: itemDisabled }) => ({
    //                             onClick: () => {
    //                                 if (itemDisabled || listDisabled) {
    //                                     return;
    //                                 }
    //                                 onItemSelect(key, !listSelectedKeys.includes(key));
    //                             },
    //                         })}
    //                     />
    //                 );
    //             }}
    //         </Transfer>
    //     );
    // };


    const columns = [
        {
            title: '商品名称',
            dataIndex: 'goodsName',
            valueType: 'text',
            search: false,
        },
        {
            title: '销售价格',
            dataIndex: 'salePrice',
            valueType: 'text',
            search: false,
        },
        {
            title: '利润',
            dataIndex: 'profit',
            valueType: 'text',
            search: false,
        },
        {
            title: '商品主图',
            dataIndex: 'picture',
            valueType: 'text',
            search: false,
            render: (_, record) => {
                let _Img = record.picture ? JSON.parse(record.picture)[0] : ''
                return _Img ? <Image src={_Img} width={50}></Image> : ''
            }
        },
        {
            title: '数量',
            dataIndex: 'goodsNum',
            valueType: 'text',
            search: false,
            render: (_, record, index) => {
                record.goodsNum = 123
                let onNum = (e) => {
                    let list = JSON.parse(JSON.stringify(goodsList))
                    let find = list.find((val) => val.id == record.id)
                    find.goodsNum = e
                    setGoodsList(list)
                }
                return <InputNumber value={goodsList.find((val) => val.id == record.id).goodsNum} style={{ width: 200 }} onChange={onNum} />
            }
        },
    ];



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

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


    const handleCreate = async (fields) => {
        setRow(fields);
        let data = JSON.parse(JSON.stringify(fields))
        data.goodsDataList = data.goodsDataList.map((item) => {
            let find = goodsList.find((val) => val.id == item)
            return {
                goodsId: item,
                goodsNum: find.goodsNum
            }
        })
        data.isUp = data.isUp ? 1 : 0
        // data.details = editorState.toHTML()
        data.picture = JSON.stringify(data.picture)
        data.details = JSON.stringify(data.details)
        const { success } = await goodspackagesAdd({ ...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!');
        //     },
        // }
    ]

    const filterOption = (input, item) => item.id == input.id;

    const [targetKeys, setTargetKeys] = useState([]);
    const [disabled, setDisabled] = useState(false);
    const onChangeCs = (nextTargetKeys) => {
        console.log(nextTargetKeys, 'nextTargetKeys');
        console.log(goodsList.find((val) => val.id == nextTargetKeys[0]));

        setTargetKeys(nextTargetKeys);
    };
    const toggleDisabled = (checked) => {
        setDisabled(checked);
    };

    const mockData = async () => {
        let { data } = await goodsPage({})
        setGoodsList(data?.records)
    }


    return (
        <PageContainer
            header={{
                title: '商品添加',
            }}
            ghost
        >
            <>
                <ProForm
                    initialValues={row}
                    onFinish={(values) => {
                        handleCreate(values)
                    }}
                >
                    <ProFormTextArea
                        rules={[{ required: true, message: '请输入' }]}
                        width="md"
                        name="packagesName"
                        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
                            label="主图"
                            name="picture"
                            tooltip="商品的封面图"
                        >
                            <FilesManager
                                fileType="image"
                                defaultValue={row?.picture}
                                count={9}
                                mode=""
                            />
                        </ProForm.Item>
                    </ProForm.Group>
                    <ProFormSwitch
                        rules={[{ required: true, message: '请输入' }]}
                        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.Group>
                        <ProForm.Item
                            label="选择商品"
                            name="goodsDataList"
                            tooltip="商品的封面图"
                        >
                            <TableTransfer
                                style={{ width: 1200 }}
                                dataSource={goodsList}
                                targetKeys={targetKeys}
                                disabled={disabled}
                                showSelectAll={false}
                                onChange={onChangeCs}
                                leftColumns={columns}
                                rightColumns={columns}
                                rowKey={(record) => record.id}
                            ></TableTransfer>

                            {/* <TableTransfer
                                dataSource={goodsList}
                                targetKeys={targetKeys}
                                disabled={disabled}
                                showSelectAll={false}
                                onChange={onChangeCs}
                                filterOption={filterOption}
                                leftColumns={columns}
                                rightColumns={columns}
                            /> */}
                        </ProForm.Item>
                    </ProForm.Group>
                </ProForm>
            </>
        </PageContainer>
    );
};
