import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { GetStoreInfos, GetPrinter, SetPrinterHost, DelPrinter, GetPrinterTemplater, GetStoreFoodMenu } from './service';
import React, { useState, useRef, useEffect } from 'react';
import { message, Button, Tag, Popconfirm } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import PrinterFormModal from "./components/PrinterFormModal";

const Printer = () => {
    const actionRef = useRef();
    //当前选中的店铺
    const [currentStore, setCurrentStore] = useState(null);
    //店铺列表
    const [storeInfoList, setStoreInfoList] = useState([]);
    //打印机模板列表
    const [printerTemplaterList, setPrinterTemplaterList] = useState([]);
    //创建/更新打印机弹窗
    const [showModal, setShowModal] = useState(false);
    //当前选中的打印机
    const [currentPrinter, setCurrentPrinter] = useState(null);
    //所有商品信息
    const [storeFoodMenuAll, setStoreFoodMenuAll] = useState([]);


    //获取店铺
    const GetStoreInfoList = async () => {
        try {
            const response = await GetStoreInfos();
            if (response.statusCode === 200) {
                response.data?.forEach(item => {
                    item.value = item.id;
                    item.label = item.name;
                });
                setCurrentStore(response.data[0]?.id);
                setStoreInfoList(response.data);
            } else {
                message.error(response.errors || '获取店铺列表失败');
            }
        } catch {
            setStoreInfoList([]);
        }
    }

    /**
     * 获取打印机模板列表
     */
    const onFetchPrinterTempList = async () => {
        const response = await GetPrinterTemplater();
        if (response.statusCode === 200) {
            response.data?.forEach(item => {
                item.value = item.id;
                item.label = item.title;
            });
            setPrinterTemplaterList(response.data);
        } else {
            message.error(response.errors || '获取打印机模板列表失败');
        }
    }

    /**
     * 获取当前门店的所有商品
     */
    const onFetchFoods = async () => {
        const response = await GetStoreFoodMenu(currentStore);
        if (response.statusCode === 200) {
            setStoreFoodMenuAll(response.data);
        }
    }

    /**
     * 设置主打印机
     */
    const onSetHostPrinter = async (printerId) => {
        const response = await SetPrinterHost(currentStore, printerId);
        if (response.statusCode === 200) {
            message.success('设置主打印机成功！');
            actionRef.current?.reload();
        } else {
            message.error(response.errors || '设置主打印机出错');
        }
    }

    /**
     * 删除打印机
     */
    const onDeletePrinter = async (printerId) => {
        const response = await DelPrinter([printerId]);
        if (response.statusCode === 200) {
            message.success('删除成功！');
            actionRef.current?.reload();
        } else {
            message.error(message.error || '删除失败');
        }
    }

    const columns = [
        {
            title: '门店',
            valueType: 'select',
            hideInTable: true,
            dataIndex: 'storeId',
            fieldProps: {
                options: storeInfoList,
                value: currentStore,
                onChange: selectValue => {
                    setCurrentStore(selectValue);
                }
            }
        },
        {
            title: '打印机名称',
            dataIndex: 'name',
            key: 'name',
            render: (_, record) => [
                record.isHost ? (<div>{record.name}<Tag style={{ marginLeft: '5px' }} color="#87d068">主打印机</Tag></div>) : record.name
            ],
            hideInSearch: true
        },
        {
            title: '应用ID',
            dataIndex: 'applicationId',
            key: 'applicationId',
            hideInSearch: true
        },
        {
            title: '终端ID',
            dataIndex: 'terminalId',
            key: 'terminalId',
            hideInSearch: true
        },
        {
            title: '模板',
            dataIndex: 'templaterId',
            key: 'templaterId',
            valueType: 'select',
            hideInSearch: true,
            fieldProps: {
                options: printerTemplaterList
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createAt',
            key: 'createAt',
            hideInSearch: true
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            fixed: 'right',
            width: 200,
            render: (text, record, _, action) => [
                <a key="edit" onClick={() => {
                    setCurrentPrinter(record);
                    setShowModal(true);
                }}>更新</a>,
                <Popconfirm
                    key="confirm"
                    title={`确定要将【${record.name}】设为主打印机吗？`}
                    onConfirm={() => onSetHostPrinter(record.id)}
                    okText="确定"
                    cancelText="取消"
                >
                    <a href="#">主打印机</a>
                </Popconfirm>,
                <Popconfirm
                    key="delete"
                    title={`确定要将【${record.name}】删除吗？`}
                    onConfirm={() => onDeletePrinter(record.id)}
                    okText="确定"
                    cancelText="取消"
                >
                    <a href="#">删除</a>
                </Popconfirm>
            ],
        },
    ];

    useEffect(() => {
        GetStoreInfoList();
        onFetchPrinterTempList();
    }, []);

    useEffect(() => {
        actionRef.current?.reload();
        onFetchFoods();
    }, [currentStore]);

    return <PageContainer header={{
        title: '',
        breadcrumb: {},
    }}>
        <ProTable
            pagination={{
                pageSize: 10
            }}
            scroll={{
                x: 1300,
            }}
            columns={columns}
            actionRef={actionRef}
            cardBordered
            request={async (params = {}, sort, filter) => {
                if (currentStore) {
                    const response = await GetPrinter(currentStore);
                    if (response.statusCode === 200) {
                        return {
                            data: response.data,
                            success: true
                        }
                    } else {
                        message.error(response.errors || '获取打印机列表出错');
                    }
                } else {
                    return [];
                }
            }}
            rowKey="id"
            dateFormatter="string"
            headerTitle="打印机列表"
            toolBarRender={() => [
                <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => {
                    setCurrentPrinter(null);
                    setShowModal(true);
                }}>
                    新建
                </Button>
            ]}
        />

        {
            showModal && <PrinterFormModal
                storeFoodMenuAll={storeFoodMenuAll}
                currentStore={currentStore}
                isModalOpen={showModal}
                onOk={() => {
                    setShowModal(false);
                    actionRef.current?.reload();
                }}
                onCancel={() => {
                    setShowModal(false);
                    setCurrentPrinter(null);
                }}
                printerTemplaterList={printerTemplaterList}
                printer={currentPrinter}
            >

            </PrinterFormModal>
        }
    </PageContainer>
}

export default Printer;