import { PlusOutlined } from '@ant-design/icons';
import { Tabs, message, Button,Popconfirm } from 'antd';
const { TabPane } = Tabs;
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { GetShopFoodMenuPage, GetStoreInfoPage,AddFoodMenu,UpdateFoodMenu,DelShopFoodMenu } from "./services"
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import LogForm from './components/Logs';
import { UnorderedListOutlined } from '@ant-design/icons';
import { history } from 'umi';
const key = 'message';
import MenuGoods from "./components/MenuGoods";
import FranchiseeMenu from "./components/FranchiseeMenu";
import CreateFoodMeun from './components/CreateFoodMeun';
import FoodMenuGoods from './components/foodMenuGoods';

const storeGoodsInfo = (props) => {

	const actionRef = useRef();
	// 门店列表
	const [storeLsit, setStoreLsit] = useState([]);
	// 当前选中的门店
	const [currStore, setCurrStore] = useState();
	// 是否展示菜品弹窗
	const [showModal, setShowModal] = useState(false);
	//当前选中的菜谱
	const [currFoodMenu, setCurrFoodMenu] = useState();
	//是否展示 关联加盟商菜谱弹窗
	const [franchiseeMenuModal, setFranchiseeMenuModal] = useState(false);


	const [currentRow, setCurrentRow] = useState();
	const [createModalVisible, handleModalVisible] = useState(false);
	// 是否展示 关联加盟商商品 弹窗
	const [menuGoodsModal, setMenuGoodsModal] = useState(false);

	/**
	 * 获取店铺列表
	 * @param {*} page 
	 */
	const getStoreInfoPageInfo = async () => {
		const response = await GetStoreInfoPage({ current: 1, pageSize: 999 });
		if (response.statusCode === 200) {
			response.data?.forEach(item => {
				item.value = item.id;
				item.label = item.name;
			});
			if (response.data.length > 0) {
				setCurrStore(response.data[0].id);
			}
			setStoreLsit(response.data);
		} else {
			message.error(JSON.stringify(response.errors) || '获取门店列表失败！');
		}
	}

	const columns = [
		{
			title: '店铺',
			dataIndex: 'storeId',
			valueType: 'select',
			hideInTable: true,
			fieldProps: {
				options: storeLsit,
				value: currStore,
				onChange: (value) => {
					setCurrStore(value);
				}
			}
		},
		{
			title: '菜谱名称',
			dataIndex: 'name',
			hideInSearch: true
		},
		{
			title: '操作',
			dataIndex: 'option',
			valueType: 'option',
			fixed: 'right',
			width: 300,
			render: (_, record) => [
				<a key="food-menu-list"
					onClick={() => {
						handleModalVisible(true);
						setCurrentRow(record);
					}}
				>
					更新
				</a>,
				<a key="food-menu-list"
				onClick={() => {
					setCurrentRow(record);
					setMenuGoodsModal(true);
				}}
			>
				菜谱关联商品
			</a>,
				<a key="food-menu-list"
					onClick={() => {
						setCurrFoodMenu(record);
						setShowModal(true);
					}}
				>
					菜谱商品
				</a>,
				 <Popconfirm
				 key="delete"
				 title={`确定要删除吗？`}
				 onConfirm={ () => {
				     DelShopFoodMenu(record.id).then((re) => {
						if(re.statusCode==200){
							actionRef.current.reloadAndRest();
							message.success('删除成功');
						}else{
							message.error(re.errors || '删除失败');
						}
					  });
					  
					  
				 }}
				 okText="确定"
				 cancelText="取消"
			   >
				 <a href="#">删除</a>
			   </Popconfirm>,
			],
		},
	];


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

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

	return <PageContainer header={{
        title: '',
        breadcrumb: {},
    }}>
		<ProTable
			columns={columns}
			actionRef={actionRef}
			scroll={{
				x: 1300,
			}}
			pagination={{
				pageSize: 10
			}}
			request={async (params = {}, sort, filter) => {
				if (!currStore) return [];
				const response = await GetShopFoodMenuPage({
					...params,
					storeId: currStore
				});
				if (response.statusCode === 200) {
					return {
						data: response.data.data,
						success: true,
						total: response.data.total,
					};
				}
				return []
			}}
			rowKey="id"
			headerTitle="菜谱列表"
			toolBarRender={() => [
				// <Button
				// 	key="button"
				// 	icon={<PlusOutlined />}
				// 	onClick={() => {
				// 		setFranchiseeMenuModal(true);
				// 	}}
				// 	type="primary"
				// >
				// 	关联加盟商菜谱
				// </Button>
				<Button
					key="button"
					icon={<PlusOutlined />}
					onClick={() => {
						handleModalVisible(true);
					}}
					type="primary"
				>
					添加菜谱
				</Button>


			]}
		/>

		{/* 菜谱商品 */}
		{
			showModal && currStore && currFoodMenu && <MenuGoods
				foodMenu={currFoodMenu}
				open={showModal}
				storeId={currStore}
				onCancel={() => setShowModal(false)}
				onOk={() => setShowModal(false)}
			>

			</MenuGoods>
		}

		{
			franchiseeMenuModal && currStore && <FranchiseeMenu
				open={franchiseeMenuModal}
				storeId={currStore}
				onCancel={() => setFranchiseeMenuModal(false)}
				onOk={() => {
					setFranchiseeMenuModal(false);
					actionRef.current?.reload();
				}}
			>

			</FranchiseeMenu>
		}

		{/* 创建菜谱 */}
		<CreateFoodMeun
			onFinish={async (value) => {
				let success = false;
				if (value.id) {
					try {
						await UpdateFoodMenu(JSON.stringify(value)).then((r) => {
							if (r.data) {
								message.success('修改成功',);
								success = true;
							} else {
								message.error(r.errors || '修改失败');
								success = false;
							}
						});
					} catch (error) {
						message.error('修改失败请重试！');
						success = false;
					}
				} else {
					try {
						value.storeId=currStore;
						await AddFoodMenu(JSON.stringify(value)).then((r) => {
							if (r.data) {
								message.success('添加成功');
								success = true;
							} else {
								message.error(r.errors || '添加失败');
								success = false;
							}
						});
					} catch (error) {
						message.error('添加失败请重试！',error);
						success = false;
					}
				}
				console.log('success', success);
				if (success) {
					handleModalVisible(false);
					setCurrentRow(undefined);
				}
				actionRef.current?.reload();
			}}
			onCancel={() => {
				handleModalVisible(false);
				setCurrentRow(undefined);
			}}
			createModalVisible={createModalVisible}
			values={currentRow || {}}
		/>

		{/* 菜谱关联菜品 */}
		{
			currStore&&currentRow && menuGoodsModal && <FoodMenuGoods 
			foodMenu={currentRow} 
			open={menuGoodsModal}
			storeId={currStore}
			onOk={()=>{setMenuGoodsModal(false)}} 
			onCancel={() => setMenuGoodsModal(false)}></FoodMenuGoods>
		}


	</PageContainer>;
};

export default storeGoodsInfo;
