import React, { useState, useEffect, useRef } from 'react';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import { Form, Input, Select, InputNumber, message, Button, Modal, Drawer, Upload, Switch, Table, notification } from 'antd';
import quickAPI from "../../service";
import indexStyles from "../../index.less";
import axios from 'axios';

const key = 'message';

const GoodsConfig = (props) => {
    const { Option, OptGroup } = Select;
    const [url, setUrl] = useState();
    //商品单位
    const [goodsUnit, setGoodsUnit] = useState([]);
    //商品大类
    const [goodsBigTypes, setGoodsBigTypes] = useState([]);
    //商品小类
    const [goodsSmallTypes, setGoodsSmallTypes] = useState([]);
    //编辑商品信息 form实例
    const [editGoodsForm] = Form.useForm();
    //新建商品单位弹窗
    const [createUnitModal, setCreateUnitModal] = useState(false);
    //新建商品大类弹窗
    const [createBigTypeModal, setCreateBigTypeModal] = useState(false);
    //新建商品大类 form实例
    const [editBigTypeForm] = Form.useForm();
    //新建商品小类弹窗
    const [createSmallTypeModal, setCreateSmallTypeModal] = useState(false);

    const [currentPage, setCurrentPage] = useState(0);
    const [pageSize, setPageSize] = useState(10);

    /**
     * 获取商品单位
     */
    const onFetchGoodsUnit = async () => {
        const response = await quickAPI.GetUnitList({
            current: 1,
            pageSize: 200
        });
        if (response.statusCode === 200) {
            setGoodsUnit(response.data.data);
        }
    }

    /**
     * 获取商品大类
     */
    const onFetchGoodsBigTypeList = async () => {
        const response = await quickAPI.GetGoodsbigType({
            current: 1,
            status: 0,
            pageSize: 1000
        });
        if (response.statusCode === 200) {
            setGoodsBigTypes(response.data.data);
        }
    }

    /**
     * 获取商品小类
     */
    const onFetchGoodsSmallTypeList = async () => {
        const response = await quickAPI.GetGoodsSmallType({
            current: 1,
            status: 0,
            pageSize: 1000
        });
        if (response.statusCode === 200) {
            setGoodsSmallTypes(response.data.data);
        }
    }


    const uploadProp = {
        name: 'file',
        showUploadList: false,
        multiple: false,
        accept: '.png, .jpg, .jpeg, .gif',
        // 这里需要指定文件上传的content-type
        headers: {
            'Content-Type': 'application/octet-stream',
        },
        customRequest({
            action,
            file,
            headers,
            onError,
            onProgress,
            onSuccess,
            withCredentials,
        }) {

            console.log("上传图片", file);
            //覆盖action 上传之前获取上传地址
            var index = file.name.lastIndexOf(".");
            var ext = file.name.substr(index + 1);

            let fileData = null;
            quickAPI.GetCosRequestURL({ directory: "goods", fileExtension: ext, method: "PUT" }).then((r) => {
                action = r.allUrl;
                const reader = new FileReader();
                reader.readAsArrayBuffer(file);
                reader.onload = (e) => {
                    // 在文件读取结束后执行的操作
                    fileData = e.target.result;
                    // 使用 axios 进行文件上传的请求
                    axios.put(action, fileData, {
                        withCredentials,
                        headers,
                        onUploadProgress: ({ total, loaded }) => {
                            // 进行上传进度输出，更加直观
                            onProgress({ percent: Math.round(loaded / total * 100).toFixed(2) }, file);
                        },
                    }).then(response => {
                        if (response.status == 200 || response.statusText == 'OK') {
                            setUrl(r.seeUrl);
                            const tempForm = editGoodsForm.getFieldsValue();
                            tempForm.imgUrl = r.seeUrl;
                            editGoodsForm.setFieldsValue(tempForm);
                        }
                    })
                        .catch(onError);
                };
            });
            return {
                abort() {
                    console.log('upload progress is aborted.');
                },
            };
        },
    };

    const onFinish = async (formValues) => {
        delete formValues.imgUrl1;
        message.loading('正在配置', key);
        if (formValues.id) {
            const response = await quickAPI.UpdateGoods(formValues);
            if (response.succeeded) {
                message.success('修改成功');
                setIsShowModal(false);
                actionRef.current.reload();
            } else {
                message.error(response.errors || '修改出错');
            }
        } else {
            const response = await quickAPI.AddGoods(formValues);
            if (response.data) {
                message.success('添加成功');
                actionRef.current.reload();
                setIsShowModal(false);
            } else {
                message.error(response.errors || '添加成出错');
            }
        }
        message.destroy(key);
    }

    const columns = [
        {
            title: '主键',
            dataIndex: 'id',
            hideInTable: true,
            hideInSearch: true,

        },
        {
            title: '图片地址',
            dataIndex: 'imgUrl',
            hideInTable: true,
            hideInSearch: true,
        },
        {
            title: '编码',
            dataIndex: 'code',
            valueType: 'textarea',
        },
        {
            title: '名称',
            dataIndex: 'name',
            valueType: 'textarea',
        },
        {
            title: '基础价格',
            dataIndex: 'price',
            hideInForm: true,
            renderText: (val) => `${val}¥`,
            hideInSearch: true,
        },
        {
            title: '会员价',
            dataIndex: 'vipPrice',
            hideInForm: true,
            renderText: (val) => `${val}¥`,
            hideInSearch: true,
        },
        {
            title: '商品小类',
            dataIndex: 'goodsTypeName',
            hideInForm: true,
            hideInSearch: true,
        },
        {
            title: '商品类型',
            dataIndex: 'goodsTypeId',
            hideInForm: true,
            hideInTable: true,
        },
        {
            title: '商品属性',
            dataIndex: 'goodsAttribute',
            hideInForm: true,
            valueEnum: {
                0: {
                    text: '单品',
                },
                1: {
                    text: '套餐',
                }
            },

        },
        {
            title: '状态',
            dataIndex: 'status',
            hideInForm: true,
            valueEnum: {
                0: {
                    text: '正常',
                    status: 'Processing',
                },
                1: {
                    text: '停用',
                    status: 'Error',
                },
                2: {
                    text: '删除',
                    status: 'Error',
                },
            },

        },
        {
            title: '创建时间',
            dataIndex: 'createAt',
            valueType: 'date',
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    key="config"
                    onClick={() => {
                        setCurrentOption(record);
                        setIsShowModal(true);
                        editGoodsForm.setFieldsValue(record);
                    }}>更新</a>
            ]
        }
    ];

    const columnsChoose = [
        {
            title: '名称',
            dataIndex: 'name',
            valueType: 'textarea',
        }
    ];

    //当前操作的门店对象
    const [currentOption, setCurrentOption] = useState({ id: '' });
    //是否显示 新增/编辑 菜谱弹窗
    const [isShowModal, setIsShowModal] = useState(false);
    const actionRef = useRef();

    const [selectedRowKeys, setSelectRowKeys] = useState([]);
    const [selectedRows, setSetSelectedRows] = useState([]);


    //商品绑定菜谱弹窗
    const [showMenuDrawer, setShowMenuDrawer] = useState(false);
    const [menuFoodList, setMenuFoodList] = useState([]);
    //当前菜谱
    const [currentFoodMenu, setCurrentFoodMenu] = useState(props.foodMenuConfig[0].id);
    const menuFoodsColumns = [
        {
            title: '名称',
            dataIndex: 'name',
            valueType: 'textarea',
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a onClick={() => {
                    props.onAddGoodsToFoodMenu(currentFoodMenu, record, false);
                }}>
                    移出菜谱
                </a>
            ]
        }
    ]

    /**
     * 将商品添加到菜谱
     * @param {*} goods 
     */
    const addGoodsToFoodMenu = () => {
        if (selectedRows.length === 0) {
            notification.error({
                message: '商品添加到菜谱出错',
                description: '请选择商品',
                placement: 'topRight'
            });
            return;
        }
        props.onAddGoodsToFoodMenu(currentFoodMenu, selectedRows);
        setSelectRowKeys([]);
        setSetSelectedRows([]);
    }

    useEffect(() => {
        onFetchGoodsUnit();
        onFetchGoodsBigTypeList();
        onFetchGoodsSmallTypeList();
    }, []);

    useEffect(() => {
        const findFoodMenu = props.foodMenuConfig.find(item => item.id === currentFoodMenu);
        if (findFoodMenu) {
            setMenuFoodList(findFoodMenu.goodsConfig);
        } else {
            setMenuFoodList([]);
        }
    }, [props.foodMenuConfig, currentFoodMenu]);

    return <>
        <Modal width={600} title={currentOption.id ? '编辑商品' : '新增商品'} visible={isShowModal} footer={false} onCancel={() => setIsShowModal(false)}>
            <Form
                labelCol={{ span: 4 }}
                layout="horizontal"
                preserve={false}
                onFinish={onFinish}
                form={editGoodsForm}
            >
                <Form.Item name="id" hidden={true}>
                    <Input />
                </Form.Item>

                <Form.Item name="code" label="商品编码" hidden={true}   >
                    <Input disabled />
                </Form.Item>

                <Form.Item name="name" label="商品名称" rules={[{ required: true }]}>
                    <Input />
                </Form.Item>

                <div className={indexStyles.add_row_content}>
                    <Form.Item name="goodsUintId" label="商品单位" rules={[{ required: true }]}>
                        <Select style={{ width: '75%' }}  >
                            {
                                goodsUnit.map((item, index) => {
                                    return (
                                        <Select.Option index={index} value={item.id} key={item.id}>
                                            {item.name}
                                        </Select.Option>
                                    );
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Button type="primary" className={indexStyles.add_row_btn} onClick={() => setCreateUnitModal(true)}>添加单位</Button>
                </div>

                <div className={indexStyles.add_row_content}>
                    <Form.Item name="parentTypeID" label="商品大类" rules={[{ required: true }]}>
                        <Select style={{ width: '75%' }}>
                            {
                                goodsBigTypes.map((item, index) => {
                                    return (
                                        <Select.Option index={index} value={item.id} key={item.id}>
                                            {item.name}
                                        </Select.Option>
                                    );
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Button type="primary" className={indexStyles.add_row_btn} onClick={() => setCreateBigTypeModal(true)}>添加大类</Button>
                </div>

                <div className={indexStyles.add_row_content}>
                    <Form.Item name="goodsTypeId" label="商品小类" rules={[{ required: true }]}>
                        <Select style={{ width: '75%' }} >
                            {
                                goodsSmallTypes.map((item, index) => {
                                    return (
                                        <Select.Option index={index} value={item.id} key={item.id}>
                                            {item.goodsType_Name}
                                        </Select.Option>
                                    );
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Button type="primary" className={indexStyles.add_row_btn} onClick={() => setCreateSmallTypeModal(true)}>添加小类</Button>
                </div>

                <Form.Item name="price" label="商品价格" rules={[{ required: true }]}>
                    <InputNumber placeholder="价格" min={0} style={{ width: '100%' }} />
                </Form.Item>

                <Form.Item name="vipPrice" label="会员价格">
                    <InputNumber placeholder="会员价" min={0} style={{ width: '100%' }} />
                </Form.Item>

                <Form.Item
                    name="goodsAttribute"
                    label="商品属性"
                    defaultValue={0}
                    rules={[{ required: true, message: '请选择商品属性' }]}
                >
                    <Select placeholder="请选择商品属性"  >
                        <OptGroup>
                            <Select.Option value={0}>单品</Select.Option>
                            <Select.Option value={1}>套餐</Select.Option>
                        </OptGroup>
                    </Select>
                </Form.Item>

                <Form.Item
                    name="status"
                    label="状态"
                    defaultValue={0}
                    rules={[{ required: true, message: '请选择状态' }]}
                >
                    <Select placeholder="请选择状态"  >
                        <OptGroup>
                            <Select.Option value={0}>正常</Select.Option>
                            <Select.Option value={1}>停用</Select.Option>
                        </OptGroup>
                    </Select>
                </Form.Item>

                <Form.Item name="remark" label="备注">
                    <Input />
                </Form.Item>

                <Form.Item name="imgUrl" hidden={true}  >
                    <Input />
                </Form.Item>

                <Form.Item name="imgUrl1" label="商品图片地址"
                >
                    <Upload
                        {...uploadProp}
                    >

                        {currentOption.imgUrl ? <img src={currentOption.imgUrl} alt="avatar" style={{ width: '100%' }} /> : <Button icon={<UploadOutlined />}>上传</Button>}

                    </Upload>
                </Form.Item>

                <Form.Item label="是否称重" name="isWeigh" valuePropName="checked" initialValue='false' >
                    <Switch checkedChildren="是" unCheckedChildren="否" defaultChecked='false' />
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        确定
                    </Button>
                </Form.Item>
            </Form>
        </Modal>

        <ProTable
            actionRef={actionRef}
            style={{ width: '100%' }}
            headerTitle="商品列表"
            rowKey="id"
            search={{
                labelWidth: 120,
            }}
            pagination={{
                current: currentPage,
                pageSize: pageSize,
                onChange: (page, pageSize) => {
                    setCurrentPage(page);
                    setPageSize(pageSize);
                }
            }}
            request={async (params) => {
                var goodsData = [];
                var total = 0;
                await quickAPI.GetgoodsList(params).then((r) => {
                    goodsData = r.data.data;
                    total = r.data.total;
                });
                return {
                    data: goodsData,
                    success: true,
                    total: total,
                };
            }}
            columns={columns}
            toolBarRender={() => [
                <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => {
                    editGoodsForm.resetFields();
                    setCurrentOption({ id: '' });
                    setIsShowModal(true);
                }}>
                    新建
                </Button>,
                <Button key="button" type="primary" onClick={() => {
                    setShowMenuDrawer(true);
                }}>
                    关联菜谱
                </Button>,
            ]}
        />

        <Modal
            title='新建商品单位'
            width={640}
            visible={createUnitModal}
            bodyStyle={{ padding: '32px 40px 48px' }}
            footer={null}
            onCancel={() => {
                setCreateUnitModal(false)
            }}
            destroyOnClose
            maskClosable={false}
        >
            <Form
                layout="vertical"
                preserve={false}
                onFinish={async (values) => {
                    const response = await quickAPI.CreateUnit(values);
                    if (response.data) {
                        message.success('商品单位添加成功');
                        setCreateUnitModal(false);
                        onFetchGoodsUnit();
                    } else {
                        message.error(response.errors || '商品单位添加失败');
                    }
                }}
            >
                <Form.Item name="id" hidden={true}>
                    <Input />
                </Form.Item>
                <Form.Item name="name" label="商品单位名称" rules={[{ required: true, max: 64 }]}>
                    <Input placeholder="商品单位名称" />
                </Form.Item>
                <Form.Item
                    name="status"
                    label="状态"
                    rules={[{ required: true, message: '请选择状态' }]}
                >
                    <Select placeholder="请选择状态">
                        <OptGroup>
                            <Select.Option value="0">正常</Select.Option>
                            <Select.Option value="1">停用</Select.Option>
                        </OptGroup>
                    </Select>
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        保存
                    </Button>
                </Form.Item>
            </Form>
        </Modal>

        <Modal
            title="新建商品大类"
            width={640}
            visible={createBigTypeModal}
            bodyStyle={{ padding: '32px 40px 48px' }}
            footer={null}
            onCancel={() => {
                setCreateBigTypeModal(false)
            }}
            destroyOnClose
        >
            <Form
                form={editBigTypeForm}
                labelCol={{ span: 6 }}
                layout="horizontal"
                preserve={false}
                onFinish={async (values) => {
                    const response = await quickAPI.AddGoodsTypeListNew(values);
                    if (response.data) {
                        message.success('商品大类添加成功');
                        setCreateBigTypeModal(false);
                        onFetchGoodsBigTypeList();
                    } else {
                        message.error(response.errors || '商品大类添加失败');
                    }
                }}
            >
                <Form.Item name="id" hidden={true}>
                    <Input />
                </Form.Item>

                <Form.Item name="name" label="商品大类名称" rules={[{ required: true, max: 50 }]}>
                    <Input />
                </Form.Item>

                <Form.Item
                    name="status"
                    label="状态"
                    rules={[{ required: true, message: '请选择状态' }]}
                >
                    <Select placeholder="请选择状态">
                        <OptGroup>
                            <Select.Option value="0">正常</Select.Option>
                            <Select.Option value="1">停用</Select.Option>
                        </OptGroup>
                    </Select>
                </Form.Item>
                <Form.Item name="remark" label="备注">
                    <Input />
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        保存
                    </Button>
                </Form.Item>
            </Form>
        </Modal>

        <Modal
            title="新建商品小类"
            width={640}
            visible={createSmallTypeModal}
            bodyStyle={{ padding: '32px 40px 48px' }}
            footer={null}
            onCancel={() => {
                setCreateSmallTypeModal(false);
            }}
            destroyOnClose
        >
            <Form
                labelCol={{ span: 6 }}
                layout="horizontal"
                preserve={false}
                onFinish={async (values) => {
                    const response = await quickAPI.AddGoodsSmallType(values);
                    if (response.data) {
                        message.success('商品小类添加成功');
                        setCreateSmallTypeModal(false);
                        onFetchGoodsSmallTypeList();
                    } else {
                        message.error(response.errors || '商品小类添加失败');
                    }
                }}
            >
                <Form.Item name="id" hidden={true}>
                    <Input />
                </Form.Item>
                <Form.Item name="goodsType_Name" label="商品小类名称" rules={[{ required: true, max: 50 }]}>
                    <Input />
                </Form.Item>
                <Form.Item
                    name="status"
                    label="状态"
                    rules={[{ required: true, message: '请选择状态' }]}
                >
                    <Select placeholder="请选择状态">
                        <OptGroup>
                            <Select.Option value="0">正常</Select.Option>
                            <Select.Option value="1">停用</Select.Option>
                        </OptGroup>
                    </Select>
                </Form.Item>
                <Form.Item name="remark" label="备注" >
                    <Input />
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        保存
                    </Button>
                </Form.Item>
            </Form>
        </Modal>

        <Drawer width={800} title="商品添加到菜谱" placement="right" onClose={() => setShowMenuDrawer(false)} visible={showMenuDrawer}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '10px' }}>
                <div className={indexStyles.current_selected_obj}>
                    当前菜谱：
                </div>
                <Select
                    className={indexStyles.current_selected_cmp}
                    onChange={(item) => {
                        setCurrentFoodMenu(item);
                    }}
                    placeholder="请选择菜谱"
                    value={currentFoodMenu}
                    size="large"
                >
                    {
                        props.foodMenuConfig.map(item => {
                            return <Option key={item.id} value={item.id}>{item.name}</Option>
                        })
                    }
                </Select>
            </div>
            <div className={indexStyles.add_to_some_box}>
                <ProTable
                    actionRef={actionRef}
                    className={indexStyles.wait_add_list}
                    headerTitle="待添加商品列表"
                    rowKey="id"
                    search={false}
                    pagination={{
                        current: currentPage,
                        pageSize: pageSize,
                        onChange: (page, pageSize) => {
                            setCurrentPage(page);
                            setPageSize(pageSize);
                        }
                    }}
                    request={async (params) => {
                        var goodsData = [];
                        if (params.goodsTypeId != undefined) {
                            params.goodsTypeId = goodsTypes[params.goodsTypeId].goodsTypeId;
                        }
                        var total = 0;
                        await quickAPI.GetgoodsList(params).then((r) => {
                            goodsData = r.data.data;
                            total = r.data.total;
                        });
                        return {
                            data: goodsData,
                            success: true,
                            total: total,
                        };
                    }}
                    columns={columnsChoose}
                    rowSelection={{
                        type: 'checkbox',
                        onSelect: (record, selected) => {
                            const currentSelectedRows = JSON.parse(JSON.stringify(selectedRows));
                            const currentSelectedRowKeys = JSON.parse(JSON.stringify(selectedRowKeys));
                            const findRowIndex = currentSelectedRows.findIndex(item => item.id === record.id);
                            const findKeysIndex = currentSelectedRowKeys.findIndex(item => item === record.id);
                            if (selected) {
                                if (findRowIndex < 0) {
                                    currentSelectedRows.push(record);
                                }
                                if (findKeysIndex < 0) {
                                    currentSelectedRowKeys.push(record.id);
                                }
                            } else {
                                if (findRowIndex > -1) {
                                    currentSelectedRows.splice(findRowIndex, 1);
                                }
                                if (findKeysIndex > -1) {
                                    currentSelectedRowKeys.splice(findKeysIndex, 1);
                                }
                            }
                            setSetSelectedRows(currentSelectedRows);
                            setSelectRowKeys(currentSelectedRowKeys);
                        },
                        onChange: (selectedRowKeys, selectedRows) => {
                            if (selectedRowKeys.length === 0) {
                                setSelectRowKeys([]);
                            }
                            if (selectedRows.length === 0) {
                                setSetSelectedRows([]);
                            }
                        },
                        selectedRowKeys: selectedRowKeys
                    }}
                />
                <Table className={indexStyles.success_add_list} rowKey="id" columns={menuFoodsColumns} dataSource={menuFoodList} />
            </div>
            <Button className={indexStyles.sure_add_btn} type='primary' onClick={addGoodsToFoodMenu}>确定添加</Button>
        </Drawer>
    </>
}

export default GoodsConfig;