import { PlusOutlined } from '@ant-design/icons';
import { Card, Tree, Button, message, Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import { add, getpage, gettree, DelStoreFoodMenu } from './service';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
	if (fields.FoodMenuId == undefined) {
		message.error('请选择菜谱');
		return false;
	}
	const hide = message.loading('正在添加');
	try {
		await add({ ...fields }).then((r) => {
			if (!r.succeeded) {
				message.error(r.errors);
				hide();
				return false;
			} else {
				hide();
				message.success('添加成功');
				return true;
			}
		});
		return true;
	} catch (error) {
		hide();
		message.error('添加失败请重试！');
		return false;
	}
};
/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows, FoodMenuId) => {
	try {
		const hide = message.loading('正在删除');
		let ids = [];
		selectedRows.forEach((item) => {
			ids.push(item.id);
		});
		await DelStoreFoodMenu({
			"storeIds": ids,
			"foodMenuId": FoodMenuId
		}).then((r) => {
			hide();
			if (r.data) {
				message.success('删除成功');
				return true;
			} else {
				message.error('删除失败');
				return false;
			}
		});
	} catch (error) {
		message.error('删除失败请重试！');
		return false;
	}
};
const TableList = () => {
	/** 新建窗口的弹窗 */
	const [createModalVisible, handleModalVisible] = useState();
	/*绑定数据 */
	const actionRef = useRef();
	const [treeData, setTreeData] = useState();
	/*选中*/
	const [selectedRowsState, setSelectedRows] = useState();

	const [FoodMenuId, setKey] = useState();
	const columns = [
		{
			title: '菜谱列表',
			dataIndex: 'menuList',
			valueType: 'treeSelect',
			hideInTable: true,
			fieldProps: {
				options: treeData,
				value: FoodMenuId,
				onChange: (value) => {
					setKey(value);
				}
			}
		},
		{
			title: '店铺名称',
			dataIndex: 'name',
			search: false
		},
		{
			title: '操作',
			dataIndex: 'option',
			valueType: 'option',
			render: (_, record) => [
				<Popconfirm
					title={`确定要将【${record.name}】移出此菜谱吗？`}
					onConfirm={() => handleRemoveStore(record)}
					okText="确定"
					cancelText="取消"
				>
					<a
						key="delete"
					>
						移除门店
					</a>
				</Popconfirm>,
			],
		},
	];
	/**
	 * 将门店移出当前菜谱
	 */
	const handleRemoveStore = async (store) => {
		await handleRemove([store], FoodMenuId);
		actionRef.current?.reloadAndRest?.();
	}

	useEffect(() => {
		function initfranchiseeType() {
			gettree().then((r) => {
				setKey(r.data[0]?.key);
				setTreeData(r.data);
			});
		}
		initfranchiseeType();
	}, []);

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

	return (
		<PageContainer>
			<ProTable
				headerTitle="店铺列表"
				actionRef={actionRef}
				rowKey="id"
				search={{
					labelWidth: 120,
				}}
				toolBarRender={() => [
					<Button
						type="primary"
						key="primary"
						onClick={() => {
							handleModalVisible(true);
						}}
					>
						<PlusOutlined /> 选择店铺
					</Button>,
				]}
				params={{
					FoodMenuId,
				}}
				request={async (params) => {
					if (!FoodMenuId) return;
					let UserData = [];
					var total = 0;

					await getpage(params).then((r) => {
						UserData = r.data.data;
						total = r.data.total;
					});
					return {
						data: UserData,
						success: true,
						total: total,
					};
				}}
				columns={columns}
			/>

			<CreateForm
				onSubmit={async (value) => {
					if (typeof (FoodMenuId) == undefined) {
						handleModalVisible(false);
					} else {
						const defaultData = [];
						value.map((data) => {
							defaultData.push({ StoreId: data.id });
						});
						const valuejson = { FoodMenuId: FoodMenuId, StoreIds: defaultData }
						var success = false;
						success = await handleAdd(valuejson);
						if (success) {
							handleModalVisible(false);
						}
						actionRef.current?.reload();
					}
				}}
				onCancel={() => {
					handleModalVisible(false);
				}}
				modalVisible={createModalVisible}
				values={FoodMenuId}
			/>
		</PageContainer>
	);
};

export default TableList;
