import { Modal, message, Space, Popconfirm,Button } from 'antd';
import { useEffect, useRef, useState } from "react";
import { GetAllGoodsMenuPage, getpage_v2, EditFoodMenuGoods } from '../services';
import ProTable from '@ant-design/pro-table';

const columns = [
    {
        title: '商品id',
        dataIndex: 'id',
        tip: '规则名称是唯一的 key',
        hideInSearch: true,
        hideInTable: true,
    },
    {
        title: '商品名称',
        dataIndex: 'name',
    },
];

/**
 * 菜谱关联加盟商商品
 * @param {*} props 
 * @returns 
 */
const MenuGoods = (props) => {
    const actionRef = useRef();

    // 当前选中的商品
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);

    const handleOk = async () => {
        if (!props.foodMenu?.id) return;
        const jsonData = {
            goodsIds: [],
            foodMenuId: props.foodMenu.id
        }
        selectedRowKeys.forEach(item => {
            jsonData.goodsIds.push({
                goodsId: item
            });
        });
        const response = await EditFoodMenuGoods(jsonData);
        if (response.statusCode === 200) {
            message.success("更新菜谱商品成功！");
            props.onOk();
        } else {
            message.error(JSON.stringify(response.errors) || '更新菜谱商品出错')
        }
    }

    /**
     * 根据菜谱ID 查询菜品信息
     */
    const onFetchMenuGoods = async () => {
        if (props.foodMenu.id) {
            const response = await getpage_v2({
                current: 1,
                pageSize: 999,
                FoodMenuId: props.foodMenu.id
            });
            if (response.statusCode === 200) {
                const selectedIds = [];
                response.data?.data?.forEach(item => {
                    selectedIds.push(item.goodid);
                });
                setSelectedRowKeys(selectedIds);
            }
        }
    }

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

    return <Modal width={800} footer={null} bodyStyle={{ padding: '32px 40px 1px 48px',height: '912px'}} title={props.foodMenu.name} visible={props.open} onOk={handleOk} onCancel={props.onCancel}>
        <ProTable
            columns={columns}
            actionRef={actionRef}
            pagination={{
                pageSize: 10
            }}
            rowSelection={{
                type: 'checkbox',
                selectedRowKeys,
                onSelect: (record, selected) => {
                    const tempArray = [...selectedRowKeys];
                    const findIndex = tempArray.findIndex(item => item === record.id);
                    if (selected) {
                        findIndex < 0 && tempArray.push(record.id);
                    } else {
                        findIndex > -1 && tempArray.splice(findIndex, 1);
                    }
                    setSelectedRowKeys(tempArray);
                },
                onSelectAll: (selected, selectedRows, changeRows) => {
                    const tempArray = [...selectedRowKeys];
                    if (selected) {
                        console.log('11111111')
                        console.log(tempArray)
                        selectedRows.forEach(item => {
                            if (!item) return;
                            const findIndex = tempArray.findIndex(fItem => fItem === item.id);
                            if (findIndex < 0) {
                                tempArray.push(item.id);
                            }
                        });
                    } else {
                        changeRows.forEach(item => {
                            const findIndex = tempArray.findIndex(fItem => fItem === item.id);
                            if (findIndex > -1) {
                                tempArray.splice(findIndex, 1);
                            }
                        });
                    }
                    setSelectedRowKeys(tempArray);
                }
            }}
            tableAlertOptionRender={() => {
                return (
                    <Space size={16}>
                        <Popconfirm
                            title="此操作会取消所有选中项，确定要取消吗？"
                            onConfirm={() => setSelectedRowKeys([])}
                            okText="确定"
                            cancelText="取消"
                        >
                            <a>取消选择</a>
                        </Popconfirm>
                    </Space>
                );
            }}
            request={async (params = {}, sort, filter) => {
                params.FoodMenuId=props.foodMenu.id
                const response = await GetAllGoodsMenuPage(params);
                if (response.statusCode === 200) {
                    return {
                        data: response.data.data,
                        success: true,
                        total: response.data.total,
                    };
                } else {
                    return []
                }
            }}
            rowKey="id"
            headerTitle="商品列表"
        />
        <Button  htmlType="button" style={{float:'right',left:10}} onClick={props.onCancel}>
                        取消
                    </Button>
        <Button type="primary" htmlType="submit" style={{float:'right'}} onClick={()=> handleOk()}>保存</Button>
    </Modal>
}

export default MenuGoods;