import React, { useEffect, useState } from 'react';
import { Modal, Select, message } from 'antd';
import { AddGoodDevice, GetDeviceInfoPage, GetGoodDevice } from '../services';
const key = 'message';

const ChooseDevice = (props) => {

	// 设备列表
	const [deviceList, setDeviceList] = useState([]);
	// 当前选中的设备
	const [choosedDevice, setChoosedDevice] = useState([]);

	/**
	 * 点击确定时触发
	 */
	const handleOk = async () => {
		const deviceIds = [];
		choosedDevice.forEach(item => {
			deviceIds.push({
				deviceId: item
			});
		});
		const response = await AddGoodDevice({
			foodMenuId: props.foodMenu.id,
			foods: props.goods.goodsId,
			isDevice:props.isDevice,
			deviceIds
		});
		if (response.statusCode === 200) {
			message.success("绑定成功！");
			props.onOk();
		} else {
			message.error(JSON.stringify(response.errors) || '商品绑定设备失败');
		}
	}

	/**
	 * 获取设备列表
	 */
	const onFetchDeviceList = async () => {
		const response = await GetDeviceInfoPage();
		if (response.statusCode === 200 && response.data) {
			response?.data?.forEach(item => {
				item.label = item.name;
				item.value = item.id;
			});
			setDeviceList(response.data);
		} else {
			message.error(JSON.stringify(response.errors) || '获取设备列表失败');
		}
	}

	/**
	 * 根据商品 查询当前绑定的设备
	 */
	const onFetchChoosedDevice = async () => {
		if (props.goods && props.storeId) {
			const response = await GetGoodDevice(props.goods.goodsId, props.storeId);
			if (response.statusCode === 200) {
				setChoosedDevice(response.data);
			}
		}
	}

	useEffect(() => {
		onFetchDeviceList();
		onFetchChoosedDevice();
	}, []);

	return (
		<Modal
			title={`【${props.goods.goods_Name}】绑定设备`}
			width={640}
			bodyStyle={{ height: '300px' }}
			visible={props.open}
			onOk={handleOk}
			onCancel={props.onCancel}
			destroyOnClose
		>
			<Select
				mode="multiple"
				allowClear
				style={{
					width: '100%',
				}}
				placeholder="请选择设备！"
				onChange={setChoosedDevice}
				options={deviceList}
				value={choosedDevice}
			/>
		</Modal>
	);
};

export default ChooseDevice;
