import React, { useState, useEffect, useRef } from 'react';
import ProTable from '@ant-design/pro-table';
import { Form, Input, Select, Drawer, message, Button, Modal, Row, Col, Table, notification } from 'antd';
import ProForm, { ProFormSelect, ProFormText, ProFormDigit } from '@ant-design/pro-form';
import quickAPI from "../../service";
import indexStyles from "../../index.less";
import { PlusOutlined } from '@ant-design/icons';

const { Option, OptGroup } = Select;

const fieldLabels = {
    name: '物料名称',
    stockUint: '库存单位',
    specs: '物料规格',
    code: '物料编码',
    aittribute: '物料属性',
    typeID: '物料类别',
    status: '物料状态',
    price: '成本价',
    netrecovery: '净料率(%)',
    OutstockUint: '出库单位',
    proportion: '换算比例(%)',
};

const MaterialConfig = (props) => {

    const [materialForm] = Form.useForm();

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

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

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

    const columns = [
        {
            title: '物料名称',
            dataIndex: 'name',
            ellipsis: true,
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '名称为必填项',
                    },
                ],
            },
        },
        {
            title: '物料属性',
            dataIndex: 'aittribute',
            valueEnum: {
                0: {
                    text: '成品',
                },
                1: {
                    text: '半成品',
                },
                2: {
                    text: '易耗品',
                },
            },
        },
        {
            title: '状态',
            dataIndex: 'status',
            hideInForm: true,
            valueEnum: {
                0: {
                    text: '正常',
                    status: 'Processing',
                },
                1: {
                    text: '停用',
                    status: 'Success',
                },
            },
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    key="primary3"
                    type="primary"
                    onClick={() => {
                        setIsShowModal(true);
                        setCurrentOption(record);
                        materialForm.setFieldsValue(record);
                    }}
                >
                    更新
                </a>
            ],
        },
    ];

    const columnsChoose = [
        {
            title: '物料名称',
            dataIndex: 'name',
            ellipsis: true,
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '名称为必填项',
                    },
                ],
            },
        }
    ];

    const [materialTypeList, setMaterialTypeList] = useState([]);
    const [materialUnitList, setMaterialUnitList] = useState([]);

    /**
     * 获取物料类别
     */
    const onFetchMaterialTypeList = async () => {
        const response = await quickAPI.GetMaterialTypeList();
        if (response.statusCode === 200) {
            response.data.forEach(item => {
                item.value = item.id,
                    item.label = item.name;
            })
            setMaterialTypeList(response.data);
        } else {
            message.error(response.errors || '获取物料类别出错');
        }
    }

    /**
     * 获取物料单位
     */
    const onFetchMaterialUnit = async () => {
        const response = await quickAPI.GetMaterialUintList();
        if (response.statusCode === 200) {
            response.data.forEach(item => {
                item.value = item.id,
                    item.label = item.name;
            })
            setMaterialUnitList(response.data);
        } else {
            message.error(response.errors || '获取物料类别出错');
        }
    }

    const [showMaterialTypeModal, setShowMaterialTypeModal] = useState(false);
    const [showMaterialUnitModal, setShowMaterialUnitModal] = useState(false);

    //当前操作的物料对象
    const [currentOption, setCurrentOption] = useState({ id: '' });
    //是否显示 新增/编辑 物料弹窗
    const [isShowModal, setIsShowModal] = useState(false);
    //物料绑定配方弹窗
    const [showMenuDrawer, setShowMenuDrawer] = useState(false);
    //当前选中的配方
    const [currentSelectedBom, setCurrentSelectedBom] = useState('');
    //配方下拉列表
    const [bomDropDown, setBomDropDown] = useState([]);
    //某配方下面的物料列表
    const [materialBelongToBom, setMaterialBelongToBom] = useState([]);

    const materialColumns = [
        {
            title: '物料名称',
            dataIndex: 'name',
            ellipsis: true,
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '名称为必填项',
                    },
                ],
            },
        },
        {
            title: '物料数量',
            dataIndex: 'BomQty',
            width: 50
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    key="primary3"
                    type="primary"
                    onClick={() => {
                        const findBom = bomDropDown.find(item => item.id === currentSelectedBom);
                        if (findBom) {
                            props.onMaterialRelationBom(findBom.id, record, false);
                        }
                    }}
                >
                    移除物料
                </a>,
                <a key="primary3"
                    type="primary" style={{ marginLeft: '10px' }} onClick={() => {
                        editMaterialForm.setFieldsValue(record);
                        setIsModalEditMaterial(true);
                    }}>
                    设置数量
                </a>
            ],
        },
    ];

    /**
     * 初始化配方列表
     */
    const initBomList = () => {
        const bomList = [];
        props.foodMenuConfig?.forEach(foodMenuItem => {
            foodMenuItem.goodsConfig?.forEach(goodsItem => {
                goodsItem.bomConfig?.forEach(bomItem => {
                    const findBom = bomList.find(item => item.id === bomItem.id);
                    if (!findBom) {
                        bomItem.goodsId = goodsItem.id;
                        bomList.push(bomItem);
                    }
                });
            })
        });
        if (!currentSelectedBom) {
            setCurrentSelectedBom(bomList[0]?.id);
        }
        setBomDropDown(bomList);
    }

    const onMaterialRelationBom = () => {
        if (selectedRows.length === 0) {
            notification.error({
                message: '配方关联商品出错',
                description: '请选择配方',
                placement: 'topRight'
            });
            return;
        }
        const findBom = bomDropDown.find(item => item.id === currentSelectedBom);
        if (findBom) {
            const temp = JSON.parse(JSON.stringify(selectedRows));
            temp.forEach(item => {
                item.BomQty = 0;
            });
            props.onMaterialRelationBom(findBom.id, temp);
            setSelectRowKeys([]);
            setSetSelectedRows([]);
        }
    }

    const initBomMaterial = () => {
        const findMaterial = bomDropDown.find(item => item.id === currentSelectedBom);
        if (findMaterial && findMaterial.materialConfig) {
            setMaterialBelongToBom(findMaterial.materialConfig);
        } else {
            setMaterialBelongToBom([]);
        }
    }

    /**
     * 更新物料信息
     */
    const [isModalEditMaterial, setIsModalEditMaterial] = useState(false);
    const [editMaterialForm] = Form.useForm();

    useEffect(() => {
        onFetchMaterialTypeList();
        onFetchMaterialUnit();
    }, []);

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

    useEffect(() => {
        initBomMaterial();
    }, [bomDropDown, currentSelectedBom]);

    return <>
        <Modal width={800} title={currentOption.id ? '编辑物料' : '新增物料'} visible={isShowModal} footer={false} onCancel={() => setIsShowModal(false)}>
            <ProForm
                form={materialForm}
                labelCol={{ span: 6 }}
                layout="horizontal"
                hideRequiredMark
                initialValues={props.materialConfig}
                onFinish={onFinish}
                submitter={false}
            >
                <Row gutter={16}>
                    <Col lg={12} md={12} sm={24}>
                        <ProFormText

                            label={fieldLabels.code}
                            name="code"
                            rules={[
                                {
                                    required: true,
                                    max: 50,
                                },
                            ]}
                            placeholder="请输入原料编码"
                        />
                    </Col>
                    <Col lg={12} md={12} sm={24}>
                        <ProFormText name="id" hidden={true} />
                        <ProFormText
                            label={fieldLabels.name}
                            name="name"
                            rules={[
                                {
                                    required: true,
                                    max: 50,
                                },
                            ]}
                            placeholder="请输入原料名称"
                        />
                    </Col>
                    <Col lg={12} md={12} sm={24}>
                        <ProFormText
                            label={fieldLabels.specs}
                            name="specs"
                            rules={[
                                {
                                    required: true,
                                    max: 500,
                                },
                            ]}
                            placeholder="请输入规格型号"
                        />
                    </Col>
                    <Col lg={12} md={12} sm={24}>
                        <ProFormSelect
                            label={fieldLabels.aittribute}
                            name="aittribute"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择物料属性',
                                },
                            ]}
                            options={[
                                {
                                    value: '0',
                                    label: '成品',
                                },
                                {
                                    value: '1',
                                    label: '半成品',
                                },
                                {
                                    value: '2',
                                    label: '易耗品',
                                },
                            ]}
                            placeholder="请选择物料属性"
                        />
                    </Col>
                    <Col lg={12} md={12} sm={24}>
                        <ProFormDigit
                            label={fieldLabels.price}
                            name="price"
                            placeholder="请输入成本价"
                            min={1}
                        />
                    </Col>
                    <Col lg={12} md={12} sm={24}>
                        <ProFormDigit
                            label={fieldLabels.netrecovery}
                            name="netrecovery"
                            min={1}
                            max={100}
                            placeholder="请输入净料率"
                        />
                    </Col>
                    <Col lg={12} md={12} sm={24}>
                        <div className={indexStyles.add_row_content}>
                            <ProFormSelect
                                style={{ width: '65%' }}
                                label={fieldLabels.typeID}
                                name="typeID"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择物料类别',
                                    },
                                ]}
                                options={materialTypeList}
                                placeholder="请选择物料类别"
                            />
                            <Button onClick={() => setShowMaterialTypeModal(true)} type="primary" className={indexStyles.add_row_btn}>添加类别</Button>
                        </div>
                    </Col>
                    <Col lg={12} md={12} sm={24}>
                        <div className={indexStyles.add_row_content}>
                            <ProFormSelect
                                style={{ width: '65%' }}
                                label={fieldLabels.stockUint}
                                name="stockUint"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择单位',
                                    },
                                ]}
                                options={materialUnitList}
                                placeholder="请选择单位"
                            />
                            <Button onClick={() => setShowMaterialUnitModal(true)} type="primary" className={indexStyles.add_row_btn}>添加单位</Button>
                        </div>

                    </Col>
                    <Col lg={12} md={12} sm={24}>
                        <div className={indexStyles.add_row_content}>
                            <ProFormSelect
                                style={{ width: '65%' }}
                                label={fieldLabels.OutstockUint}
                                name="outstockUint"
                                options={materialUnitList}
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择出库单位',
                                    },
                                ]}
                                placeholder="请选择出库单位"
                            />
                            <Button onClick={() => setShowMaterialUnitModal(true)} type="primary" className={indexStyles.add_row_btn}>添加单位</Button>
                        </div>
                    </Col>
                    <Col lg={12} md={12} sm={24}>
                        <ProFormDigit
                            label={fieldLabels.proportion}
                            name="proportion"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入出入库换算比例',
                                },
                            ]}
                            placeholder="请输入换算比例"
                        />
                    </Col>
                    <Col lg={12} md={12} sm={24}>
                        <ProFormSelect
                            label={fieldLabels.status}
                            name="status"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择状态',
                                },
                            ]}
                            options={[
                                {
                                    value: '0',
                                    label: '正常',
                                },
                                {
                                    value: '1',
                                    label: '停用',
                                },
                            ]}
                            placeholder="请选择状态"
                        />
                    </Col>
                </Row>
                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        确定
                    </Button>
                </Form.Item>
            </ProForm>
        </Modal>

        <ProTable
            actionRef={actionRef}
            headerTitle="物料列表"
            rowKey="id"
            search={{
                labelWidth: 120,
            }}
            pagination={{
                current: currentPage,
                pageSize: pageSize,
                onChange: (page, pageSize) => {
                    setCurrentPage(page);
                    setPageSize(pageSize);
                }
            }}
            request={async (params) => {
                let UserData = [];
                let total = 0;
                await quickAPI.GetMaterialPage(params).then((r) => {
                    UserData = r.data.data;
                    total = r.data.total;
                });
                return {
                    data: UserData,
                    success: true,
                    total: total,
                };
            }}
            columns={columns}
            toolBarRender={() => [
                <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => {
                    materialForm.resetFields();
                    setCurrentOption({ id: '' });
                    setIsShowModal(true);
                }}>
                    新建
                </Button>,
                <Button key="button" type="primary" onClick={() => {
                    setShowMenuDrawer(true);
                }}>
                    关联配方
                </Button>,
            ]}
        />

        <Modal
            title="添加物料单位"
            width={640}
            visible={showMaterialUnitModal}
            bodyStyle={{ padding: '32px 40px 48px' }}
            footer={null}
            onCancel={() => {
                setShowMaterialUnitModal(false)
            }}
            destroyOnClose
            maskClosable={false}
        >
            <Form
                layout="vertical"
                preserve={false}
                onFinish={async (values) => {
                    const response = await quickAPI.AddMaterialUnit(values);
                    if (response.data) {
                        message.success('添加成功');
                        setShowMaterialUnitModal(false);
                        onFetchMaterialUnit();
                    } 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={showMaterialTypeModal}
            bodyStyle={{ padding: '32px 40px 48px' }}
            footer={null}
            onCancel={() => {
                setShowMaterialTypeModal(false);
            }}
            destroyOnClose
            maskClosable={false}
        >
            <Form
                layout="vertical"
                preserve={false}
                onFinish={async (values) => {
                    const response = await quickAPI.AddMaterialType(values);
                    if (response.data) {
                        message.success('添加成功');
                        setShowMaterialTypeModal(false);
                        onFetchMaterialTypeList();
                    } 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="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>

        <Drawer width={900} 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) => {
                        console.log('setCurrentSelectedBom', item);
                        setCurrentSelectedBom(item);
                    }}
                    placeholder="请选择配方"
                    value={currentSelectedBom}
                    size="large"
                >
                    {
                        bomDropDown.map(item => {
                            return <Option key={item.id} value={item.id}>{item.name}</Option>
                        })
                    }
                </Select>
            </div>
            <div className={indexStyles.add_to_some_box}>
                <ProTable
                    className={indexStyles.wait_add_list}
                    actionRef={actionRef}
                    headerTitle="物料列表"
                    rowKey="id"
                    search={false}
                    pagination={{
                        current: currentPage,
                        pageSize: pageSize,
                        onChange: (page, pageSize) => {
                            setCurrentPage(page);
                            setPageSize(pageSize);
                        }
                    }}
                    request={async (params) => {
                        let UserData = [];
                        let total = 0;
                        await quickAPI.GetMaterialPage(params).then((r) => {
                            UserData = r.data.data;
                            total = r.data.total;
                        });
                        return {
                            data: UserData,
                            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={materialColumns} dataSource={materialBelongToBom} />
            </div>
            <Button className={indexStyles.sure_add_btn} type='primary' onClick={onMaterialRelationBom}>确定关联</Button>
        </Drawer>
        <Modal title="设置物料数量" visible={isModalEditMaterial} footer={null} onCancel={() => setIsModalEditMaterial(false)}>
            <Form
                form={editMaterialForm}
                name="basic"
                labelCol={{
                    span: 8,
                }}
                wrapperCol={{
                    span: 16,
                }}
                initialValues={{
                    remember: true,
                }}
                onFinish={(values) => {
                    props.onUpdateMaterial(currentSelectedBom, values);
                    setIsModalEditMaterial(false);
                }}
                autoComplete="off"
            >
                <Form.Item name="id" hidden={true}>
                    <Input />
                </Form.Item>

                <Form.Item
                    label="物料名称"
                    name="name"
                    rules={[
                        {
                            required: true,
                            message: '请输入物料名称',
                        },
                    ]}
                >
                    <Input disabled />
                </Form.Item>

                <Form.Item
                    label="物料数量"
                    name="BomQty"
                    rules={[
                        {
                            required: true,
                            message: '请输入物料数量',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    wrapperCol={{
                        offset: 8,
                        span: 16,
                    }}
                >
                    <Button type="primary" htmlType="submit">
                        确定
                    </Button>
                </Form.Item>
            </Form>
        </Modal>
    </>
}

export default MaterialConfig;