import { Modal, message, Space, Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { AddDeviceGood, GetByDeviceGoods, getFoodMenuList } from '../services';

const DeviceFood = (props) => {
    const actionRef = useRef();
    /**
     * 当前选中的商品
     */
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [isFirst, setIsFirst] = useState(true);
    // 菜谱列表
    const [foodMenuList, setFoodMenuList] = useState([]);
    const [foodMenuId, setFoodMenuId] = useState('');

    const columns = [
        {
			title: '菜谱列表',
			dataIndex: 'foodMenuId',
			valueType: 'treeSelect',
			hideInTable: true,
			fieldProps: {
				options: foodMenuList,
				value: foodMenuId,
				onChange: (value) => {
					setFoodMenuId(value);
				}
			}
		},
        {
            title: '商品id',
            dataIndex: 'goodsId',
            tip: '规则名称是唯一的 key',
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '商品名称',
            dataIndex: 'goodsName',
        },
    ];

    /**
     * 为设备添加商品
     */
    const handleOk = async () => {
        if (!props.device?.id) return;
        const foodss = [];
        selectedRowKeys.forEach(item => {
            foodss.push({
                foodId: item
            });
        });
        const response = await AddDeviceGood({
            foodss,
            deviceId: props.device.id
        });
        if (response.data) {
            message.success("设备商品更新成功！");
            props.onOk();
        } else {
            message.error(JSON.stringify(response.errors) || "上架失败");
        }
    }

    /**
     * 获取菜谱列表
     */
    const onFetchFoodMenu = async () => {
        const response = await getFoodMenuList();
        if (response.statusCode === 200 && response.data.length > 0) {
            setFoodMenuId(response.data[0].value);
            setFoodMenuList(response.data);
        }
    }

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

    useEffect(() => {
        if (actionRef.current) {
            actionRef.current.reload();
        }
    }, [foodMenuId]);

    return (
        <Modal
            width={900}
            bodyStyle={{ padding: '32px 40px 48px' }}
            destroyOnClose
            title={`【${props.device.deviceName}】绑定商品`}
            visible={props.open}
            onCancel={() => props.onCancel()}
            onOk={handleOk}
            maskClosable={false}
        >
            <ProTable
                actionRef={actionRef}
                rowKey="goodsId"
                pagination={{ defaultPageSize: 10 }}
                toolBarRender={false}
                params={{
                    deviceId: props.device.id,
                }}
                //数据绑定
                request={async (params) => {
                    if (!foodMenuId) return [];
                    const response = await GetByDeviceGoods({
                        ...params,
                        foolMenuId: foodMenuId,
                        storeId: props.device.orgId,
                        foodName: params.goodsName || ""
                    });
                    if (response.statusCode === 200) {
                        if (isFirst) {
                            const set = new Set([...selectedRowKeys, ...response.data.data.checkedIds]);
                            const setArray = [];
                            set.forEach(item => {
                                setArray.push(item);
                            });
                            setSelectedRowKeys(setArray);
                            setIsFirst(false);
                        }
                        return {
                            data: response.data?.data?.data || [],
                            success: true,
                            total: response.data.total,
                        };
                    } else {
                        return []
                    }
                }}
                columns={columns}
                rowSelection={{
                    type: 'checkbox',
                    selectedRowKeys,
                    onSelect: (record, selected) => {
                        const tempArray = [...selectedRowKeys];
                        const findIndex = tempArray.findIndex(item => item === record.goodsId);
                        if (selected) {
                            findIndex < 0 && tempArray.push(record.goodsId);
                        } 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.goodsId);
                                if (findIndex < 0) {
                                    tempArray.push(item.goodsId);
                                }
                            });
                        } else {
                            changeRows.forEach(item => {
                                const findIndex = tempArray.findIndex(fItem => fItem === item.goodsId);
                                if (findIndex > -1) {
                                    tempArray.splice(findIndex, 1);
                                }
                            });
                        }
                        setSelectedRowKeys(tempArray);
                    }
                }}
                tableAlertOptionRender={() => {
                    return (
                        <Space size={16}>
                            <Popconfirm
                                title="此操作会取消所有选中项，确定要取消吗？"
                                onConfirm={() => setSelectedRowKeys([])}
                                okText="确定"
                                cancelText="取消"
                            >
                                <a>取消选择</a>
                            </Popconfirm>
                        </Space>
                    );
                }}
            />
        </Modal>
    );
};

export default DeviceFood;
