import { Modal, Space, Popconfirm, message } from 'antd';
import { useEffect, useRef, useState } from "react";
import { GetFoodMenuInfoPage, GetShopFoodMenuPage, StoreAddFoodMenuNew } from '../services';
import ProTable from '@ant-design/pro-table';

/**
 * 关联加盟商菜谱
 * @param {*} props 
 * @returns 
 */
const FranchiseeMenu = (props) => {
    const actionRef = useRef();
    /**
     * 当前选中的菜谱
     */
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const columns = [
        {
            title: '菜谱名称',
            dataIndex: 'name',
        },
        {
            title: '菜谱编码',
            dataIndex: 'code',
            hideInSearch: true,
        },
        {
            title: '菜谱排序',
            dataIndex: 'sort',
            hideInSearch: true
        },
    ];

    const handleOk = async () => {
        const response = await StoreAddFoodMenuNew({
			foodMenuIds: selectedRowKeys,
            storeId: props.storeId
		});
		if (response.statusCode === 200) {
			message.success("绑定成功！");
			props.onOk();
		} else {
			message.error(response.errors || '绑定菜谱失败');
		}
    }

    /**
     * 获取门店已绑定的菜谱
     */
    const onFetchStoreMenu = async () => {
        if (!props.storeId) return [];
        const response = await GetShopFoodMenuPage({
            current: 1,
            pageSize: 999,
            storeId: props.storeId
        });
        if (response.statusCode === 200) {
            const tempArray = [];
            response.data?.data?.forEach(item => {
                tempArray.push(item.id);
            });
            setSelectedRowKeys(tempArray);
        }
    }

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

    return <Modal destroyOnClose width={1200} title={`绑定菜谱`} visible={props.open} onOk={handleOk} onCancel={props.onCancel}>
        <ProTable
            columns={columns}
            actionRef={actionRef}
            pagination={{
                pageSize: 10
            }}
            request={async (params = {}, sort, filter) => {
                if (props.storeId) {
                    const response = await GetFoodMenuInfoPage({
                        ...params
                    });
                    if (response.statusCode === 200) {
                        return {
                            data: response.data.data,
                            success: true,
                            total: response.data.total,
                        };
                    } else {
                        return []
                    }
                }
                return []
            }}
            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) {
                        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>
                );
            }}
            rowKey="id"
            headerTitle="菜谱列表"
        />
    </Modal>
}

export default FranchiseeMenu;