import React, { useState, useEffect, useRef } from "react";
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, Select, message, Col, Row, Drawer, Result } from 'antd';
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import axios from 'axios';
import cardAPI from "../service";
import { history } from 'umi';

const GateAdmin = () => {
    const actionRef = useRef();
    const [modalForm] = Form.useForm();
    const [storeList, setStoreList] = useState([]);
    const [currentStore, setCurrentStore] = useState('');
    const [TenantId, setTenantId] = useState('');
    const [current, setCurrent] = useState(1);
    const [pageSize, setPageSize] = useState(100);
    const [isModalOpen, setIsModalOpen] = useState(false);

    const columns = [
        {
            title: '档口名称',
            dataIndex: 'name',
            ellipsis: true,
        },
        {
            title: '归属门店',
            dataIndex: 'storeId',
            render: (_, record) => {
                const find = storeList.find(item => item.id === record.storeId);
                if (find) {
                    return <div>{find.store_Name}</div>
                }
            }
        },
        {
            title: '属性',
            dataIndex: 'mode',
            valueType: 'select',
            valueEnum: {
                1: {
                    text: '固定',
                    status: 'Success',
                },
                2: {
                    text: '自由设定',
                    status: 'Success',
                }
            },
        },
        {
            title: '金额',
            dataIndex: 'price',
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'select',
            valueEnum: {
                0: {
                    text: '正常',
                    status: 'Success',
                },
                1: {
                    text: '禁用',
                    status: 'Error',
                },
                2: {
                    text: '删除',
                    status: 'Error',
                }
            },
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (text, record, _, action) => [
                <a onClick={() => onEditTableRow(record)}>更新</a>
            ],
        },
    ];

    /**
     * 点击编辑按钮
     * @param {*} record
     */
    const onEditTableRow = (record) => {
        setIsModalOpen(true);
        setHtml(record.remaek);
        modalForm.setFieldsValue(record);
    }

    // editor 实例
    const [editor, setEditor] = useState(null);
    // 编辑器内容
    const [html, setHtml] = useState('');
    // 工具栏配置
    const toolbarConfig = {};
    // 编辑器配置
    const editorConfig = {
        placeholder: '请输入大屏横幅...',
        MENU_CONF: {
            fontSize: {
                fontSizeList: [
                    '10px', '20px', '40px', '60px', '80px', '100px', '150px', '180px', '200px',
                ]
            },
            uploadImage: {
                async customUpload(file, insertFn) {
                    let index = file.name.lastIndexOf(".");
                    let ext = file.name.substr(index + 1);
                    let fileData = null;
                    cardAPI.GetCosRequestURL({ directory: "kitchen", fileExtension: ext, method: "PUT" }).then((r) => {
                        const action = r.allUrl;
                        const reader = new FileReader();
                        reader.readAsArrayBuffer(file);
                        reader.onload = (e) => {
                            fileData = e.target.result;
                            axios.put(action, fileData).then(response => {
                                if (response.status == 200 || response.statusText == 'OK') {
                                    insertFn(r.seeUrl, r.seeUrl, r.seeUrl);
                                    message.success('上传成功！');
                                }
                            });
                        };
                    });

                }
            }
        }
    }

    /**
     * 获取店铺列表
     */
    const onFetchStoreList = async () => {
        const storeId = history.location.query.storeId;
        if (storeId) {
            const response = await cardAPI.GetAllStore();
            if (response.isSuccess) {
                setStoreList(response.data);
                const findStore = response.data.find(item => item.id === storeId);
                if (findStore) {
                    setTenantId(findStore.companyId);
                    setCurrentStore(findStore.id)
                }
            } else {
                message.error(response.msg || '获取店铺列表失败');
            }
        }
    }

    /**
     * 提交表单
     */
    const onFinish = async (values) => {
        if (values.id) {
            values.remaek = html;
            const response = await cardAPI.UpdateGateInfoNew(values, TenantId);
            if (response.statusCode === 200) {
                message.success('更新档口成功！');
                setIsModalOpen(false);
                actionRef.current?.reload();
            } else {
                message.error(response.errors || '更新档口失败');
            }
        }
    }

    // 及时销毁 editor ，重要！
    useEffect(() => {
        return () => {
            if (editor == null) return
            editor.destroy()
            setEditor(null)
        }
    }, [editor]);

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

    useEffect(() => {
        actionRef.current?.reload();
    }, [TenantId]);

    return <div>
        {
            currentStore ? <ProTable
                columns={columns}
                actionRef={actionRef}
                request={
                    async () => {
                        if (currentStore && TenantId) {
                            const response = await cardAPI.GetGateListByStorePageNew(currentStore, current, pageSize, TenantId);
                            if (response.statusCode === 200) {
                                return {
                                    data: response.data.data.data,
                                    success: true,
                                    total: response.data.total
                                }
                            }
                        }
                    }
                }
                cardBordered
                editable={{
                    type: 'multiple',
                }}
                rowKey="id"
                search={false}
                options={{
                    setting: {
                        listsHeight: 400,
                    },
                }}
                pagination={{
                    pageSize: pageSize,
                    onChange: (page) => setCurrent(page),
                }}
                dateFormatter="string"
                headerTitle="档口管理"
                toolBarRender={() => [
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <div>
                            当前门店：
                        </div>
                        <Select style={{ width: 300 }} value={currentStore} disabled>
                            {
                                storeList.map(item => {
                                    return <Option value={item.id} key={item.id}>{item.store_Name}</Option>
                                })
                            }
                        </Select>
                    </div>
                ]}
            /> : <Result
                status="404"
                title="门店ID错误"
                subTitle="请检查URL中 storeId是否正确"
            />
        }

        <Drawer destroyOnClose width='100%' title='编辑档口' visible={isModalOpen} onClose={() => setIsModalOpen(false)}>
            <Form
                name="basic"
                onFinish={onFinish}
                form={modalForm}
                labelCol={{ span: 4 }}
            >
                <Form.Item
                    label="id"
                    name="id"
                    hidden={true}
                >
                    <Input size="large" />
                </Form.Item>

                <div style={{ border: '1px solid #ccc', zIndex: 100, marginBottom: '10px' }}>
                    <Toolbar
                        editor={editor}
                        defaultConfig={toolbarConfig}
                        mode="default"
                        style={{ borderBottom: '1px solid #ccc' }}
                    />
                    <Editor
                        defaultConfig={editorConfig}
                        value={html}
                        onCreated={setEditor}
                        onChange={editor => setHtml(editor.getHtml())}
                        mode="default"
                        style={{ height: '700px' }}
                    />
                </div>

                <Row>
                    <Col xs={12} sm={12} md={12} lg={12} xl={12}>
                        <Form.Item
                            label="档口名称"
                            name="name"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入档口名称！',
                                },
                            ]}
                        >
                            <Input size="large" />
                        </Form.Item>
                    </Col>
                    <Col xs={12} sm={12} md={12} lg={12} xl={12}>
                        <Form.Item
                            label="归属门店"
                            name="storeId"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入归属门店！',
                                },
                            ]}
                        >
                            <Select size="large" disabled>
                                {
                                    storeList.map(store => {
                                        return (
                                            <Select.Option key={store.id} value={store.id}>{store.store_Name}</Select.Option>
                                        )
                                    })
                                }
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={12} sm={12} md={12} lg={12} xl={12}>
                        <Form.Item
                            label="属性"
                            name="mode"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入选择属性！',
                                },
                            ]}
                        >
                            <Select size="large">
                                <Select.Option value={1}>固定金额</Select.Option>
                                <Select.Option value={2}>自由设定</Select.Option>
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={12} sm={12} md={12} lg={12} xl={12}>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) =>
                                prevValues.mode !== currentValues.mode
                            }  >
                            {({ getFieldValue }) =>
                                (getFieldValue('mode') == '1') ? (
                                    <Form.Item
                                        label="金额"
                                        name="price"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入金额！',
                                            },
                                        ]}
                                    >
                                        <Input size="large" />
                                    </Form.Item>

                                ) : null
                            }
                        </Form.Item>
                    </Col>
                    <Col xs={12} sm={12} md={12} lg={12} xl={12}>
                        <Form.Item
                            label="状态"
                            name="status"
                        >
                            <Select size="large" defaultValue={1}>
                                <Option value={0}>正常</Option>
                                <Option value={1}>禁用</Option>
                            </Select>
                        </Form.Item>
                    </Col>
                </Row>

                <Form.Item>
                    <Button type="primary" htmlType="submit" style={{ marginTop: '10px', marginLeft: 'auto' }}>
                        确定
                    </Button>
                </Form.Item>

            </Form>
        </Drawer>
    </div>
}

export default GateAdmin;