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

/**
 * 配方配置
 * @returns 
 */
const BomConfig = (props) => {

    const [editBomForm] = Form.useForm();

    const onFinish = async (values) => {
        if (values.id) {
            quickAPI.UpdateBom(values).then((r) => {
                if (r.data) {
                    message.success('修改成功');
                } else {
                    message.error('修改失败请重试！');
                }
                //刷新数据
                actionRef.current.reload();
                setIsShowModal(false);
            });
        } else {
            quickAPI.AddBom(values).then((r) => {
                if (r.data) {
                    message.success('添加成功');
                    //刷新数据
                    actionRef.current.reload();
                    setIsShowModal(false);
                } else {
                    message.error('添加失败请重试！');
                }
            });
        }
    }

    const columns = [
        {
            title: '主键',
            dataIndex: 'id',
            hideInTable: true,
            hideInSearch: true,
        },
        {
            title: '配方编码',
            dataIndex: 'code',
            hideInForm: true,
            hideInSearch: true,
        },
        {
            title: '配方名称',
            dataIndex: 'name',
            hideInForm: true,
            hideInSearch: true,
        },
        {
            title: '排序',
            dataIndex: 'sort',
            hideInForm: true,
            hideInSearch: true,
        },
        {
            title: '配方分类',
            dataIndex: 'bomTypeList',
            search: false,
            width: 450,
            render: (_, record) => (
                <Space>
                    {
                        bomtype.filter(x => {
                            let findId = record.bomTypeList.find(findItem => findItem === x.id);
                            let findBomType = bomtype.find(bomItem => bomItem.id === findId);
                            return findBomType != null || undefined;
                        }).map(item => (
                            <Tag color="#87d068" key={item.id}>
                                {item.name}
                            </Tag>
                        ))
                    }
                </Space>
            ),
        },
        {
            title: '配方类型',
            dataIndex: 'isMain',
            hideInForm: true,
            valueEnum: {
                false: {
                    text: '辅料配方',
                    status: 'Processing',
                },
                true: {
                    text: '主料配方',
                    status: 'Success',
                },
            },
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    key="primary3"
                    type="primary"
                    onClick={() => {
                        setIsShowModal(true);
                        setCurrentOption(record);
                        editBomForm.setFieldsValue(record);
                    }}
                >
                    更新
                </a>
            ],
        },
    ];

    const columnsChoose = [
        {
            title: '配方名称',
            dataIndex: 'name',
            hideInForm: true,
            hideInSearch: true,
        }
    ];

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

    const [selectedRows, setSetSelectedRows] = useState([]);
    const [selectedRowKeys, setSelectRowKeys] = useState([]);
    //配方类型
    const [bomtype, setBomtype] = useState([]);
    //是否展示配方弹窗
    const [isShowBomModal, setIsShowBomModal] = useState(false);

    /**
     * 获取配方分类
     */
    const onFetchBomType = async () => {
        const response = await quickAPI.GetBomTypePage({
            current: 1,
            pagesize: 1000
        });
        if (response.statusCode === 200) {
            setBomtype(response.data.data);
        }
    }

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

    //商品绑定菜谱弹窗
    const [showMenuDrawer, setShowMenuDrawer] = useState(false);
    //当前选中的商品
    const [currentSelectedFood, setCurrentSelectedFood] = useState('');
    //商品下拉列表
    const [foodDropDown, setFoodDropDown] = useState([]);
    //某商品下面的配方列表
    const [bomBelongToGoods, setBomBelongToGoods] = useState([]);

    const goodsBomColumns = [
        {
            title: '配方名称',
            dataIndex: 'name',
            hideInForm: true,
            hideInSearch: true,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    key="primary3"
                    type="primary"
                    onClick={() => {
                        props.onBomRelationGoods(record.goodsId, record, false);
                    }}
                >
                    移除配方
                </a>
            ],
        }
    ]

    /**
     * 初始化商品下拉列表
     */
    const initFoodDropDown = () => {
        const goodsArray = [];
        props.foodMenuConfig.forEach(menuItem => {
            const foodMenuId = menuItem.id;
            if (menuItem.goodsConfig) {
                menuItem.goodsConfig.forEach(goodsItem => {
                    goodsItem.foodMenuId = foodMenuId;
                    const findRepet = goodsArray.find(item => item.id === goodsItem.id);
                    if (!findRepet) {
                        goodsArray.push(goodsItem);
                    }
                });
            }
        });
        if (!currentSelectedFood) {
            setCurrentSelectedFood(goodsArray[0].id);
        }
        setFoodDropDown(goodsArray);
    }

    //根据商品ID渲染配方列表
    const initGoodsBom = () => {
        const findGoods = foodDropDown.find(item => item.id === currentSelectedFood);
        if (findGoods && findGoods.bomConfig) {
            setBomBelongToGoods(findGoods.bomConfig);
        } else {
            setBomBelongToGoods([]);
        }
    }

    /**
     * 配方关联商品
     */
    const bomRelationGoods = () => {
        if (selectedRows.length === 0) {
            notification.error({
                message: '配方关联商品出错',
                description: '请选择配方',
                placement: 'topRight'
            });
            return;
        }
        const findGoods = foodDropDown.find(item => item.id === currentSelectedFood);
        if (findGoods) {
            selectedRows.forEach(item => {
                item.foodMenuId = findGoods.foodMenuId;
                item.goodsId = findGoods.id;
            });
            props.onBomRelationGoods(findGoods.id, selectedRows);
            setSelectRowKeys([]);
            setSetSelectedRows([]);
        }
    }

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

    useEffect(() => {
        initFoodDropDown();
    }, [props.foodMenuConfig]);

    useEffect(() => {
        initGoodsBom();
    }, [foodDropDown, currentSelectedFood]);

    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={editBomForm}
            >
                <Form.Item name="id" hidden={true}>
                    <Input />
                </Form.Item>

                <Form.Item name="code" label="配方编码" rules={[{ required: true }]} >
                    <Input disabled placeholder="配方编码" />
                </Form.Item>

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

                <div className={indexStyles.add_row_content}>
                    <Form.Item name="bomTypeList" label="配方类型" rules={[{ required: true }]}>
                        <Select
                            style={{ width: '70%' }}
                            mode="multiple"
                            allowClear
                        >
                            {bomtype.map((item, index) => {
                                return (
                                    <Select.Option index={item.id} value={item.id} key={item.id}>
                                        {item.name}
                                    </Select.Option>
                                );
                            })}
                        </Select>
                    </Form.Item>
                    <Button type="primary" className={indexStyles.add_row_btn} onClick={() => setIsShowBomModal(true)} >添加配方类型</Button>
                </div>

                <Form.Item name="isMain" label="配方类型" >
                    <Switch checkedChildren="主料" unCheckedChildren="辅料" />
                </Form.Item>

                <Form.Item name="sort" label="排序" rules={[{ required: true }]}>
                    <InputNumber placeholder="排序" min={1} />
                </Form.Item>

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

        <Modal
            title="新建配方类型"
            width={640}
            bodyStyle={{ padding: '32px 40px 48px' }}
            visible={isShowBomModal}
            footer={null}
            onCancel={() => {
                setIsShowBomModal(false);
            }}
            destroyOnClose
            maskClosable={false}
        >
            <Form
                layout="vertical"
                preserve={false}
                initialValues={props?.values}
                onFinish={async (values) => {
                    const response = await quickAPI.CreateBomType(values);
                    if (response.data) {
                        message.success('配方类别添加成功');
                        setIsShowBomModal(false);
                        onFetchBomType();
                    } else {
                        message.error(response.errors || '配方类别添加失败');
                    }
                }}
            >
                <Form.Item name="id" hidden={true}>
                    <Input />
                </Form.Item>
                <Form.Item name="name" label="配方类型名称" rules={[{ required: true, max: 64, whitespace: true }]}>
                    <Input placeholder="请输入配方类型名称" />
                </Form.Item>
                <Form.Item
                    name="pertain"
                    label="归属"
                    defaultValue={props?.values?.pertain}
                    rules={[{ required: true, message: '请选择类型归属' }]}  >
                    <Select placeholder="请选择类型归属">
                        <Option value="1">无</Option>
                        <Option value="2">TMC </Option>
                    </Select>
                </Form.Item>
                <Form.Item
                    name="status"
                    label="状态"
                    defaultValue={props?.values?.status}
                    rules={[{ required: true, message: '请选择状态' }]}
                >
                    <Select placeholder="请选择状态">
                        <Option value="0">正常</Option>
                        <Option value="1">停用</Option>
                    </Select>
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        保存
                    </Button>
                </Form.Item>
            </Form>
        </Modal>

        <ProTable
            actionRef={actionRef}
            style={{ width: '100%' }}
            headerTitle="配方列表"
            rowKey="id"
            pagination={{
                current: currentPage,
                pageSize: pageSize,
                onChange: (page, pageSize) => {
                    setCurrentPage(page);
                    setPageSize(pageSize);
                }
            }}
            search={false}
            //数据绑定
            request={async (params) => {
                var goodsBomsData = [];
                var total = 0;
                await quickAPI.GetBomPage(params).then((r) => {
                    goodsBomsData = r.data.data;
                    total = r.data.total;
                });
                return {
                    data: goodsBomsData,
                    success: true,
                    total: total,
                };
            }}
            columns={columns}
            toolBarRender={() => [
                <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => {
                    editBomForm.resetFields();
                    const temp = editBomForm.getFieldsValue();
                    temp.code = nanoid().substring(0, 20);
                    editBomForm.setFieldsValue(temp);
                    setCurrentOption({ id: '' });
                    setIsShowModal(true);
                }}>
                    新建
                </Button>,
                <Button key="button" type="primary" onClick={() => {
                    setShowMenuDrawer(true);
                }}>
                    关联商品
                </Button>,
            ]}
        />

        <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) => {
                        setCurrentSelectedFood(item);
                    }}
                    placeholder="请选择商品"
                    value={currentSelectedFood}
                    size="large"
                >
                    {
                        foodDropDown.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"
                    pagination={{
                        current: currentPage,
                        pageSize: pageSize,
                        onChange: (page, pageSize) => {
                            setCurrentPage(page);
                            setPageSize(pageSize);
                        }
                    }}
                    search={false}
                    //数据绑定
                    request={async (params) => {
                        var goodsBomsData = [];
                        var total = 0;
                        await quickAPI.GetBomPage(params).then((r) => {
                            goodsBomsData = r.data.data;
                            total = r.data.total;
                        });
                        return {
                            data: goodsBomsData,
                            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={goodsBomColumns} dataSource={bomBelongToGoods} />
            </div>
            <Button className={indexStyles.sure_add_btn} type='primary' onClick={bomRelationGoods}>确定关联</Button>
        </Drawer>
    </>
}

export default BomConfig;