// 点餐商品管理
import React, { useRef, useState, Suspense, Children, useEffect } from 'react';
import moment from 'moment'; // 时间相关引用，没有使用可以删除
import numeral from "numeral"; // 数字相关引用，没有使用可以删除
import { connect } from 'umi';

import useRequest from '@ahooksjs/use-request'; // 请求数据的引用
import Draggable from 'react-draggable';
import SubMenu from "antd/lib/menu/SubMenu";
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import ProForm, { ProFormDatePicker, ProFormDateRangePicker, ProFormDateTimePicker, ProFormDateTimeRangePicker, ProFormDigit, ProFormMoney, ProFormSelect, ProFormText, ProFormTextArea, ProFormTreeSelect, ProFormUploadButton } from '@ant-design/pro-form';
import { MenuFoldOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Col, Drawer, message, Row, Popconfirm, Space, Image, Modal, Form, Switch, Upload, Tooltip, Descriptions, TreeSelect } from 'antd';

import type { CurrentUser } from "umi";
import type { ConnectState } from '@/models/connect';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import type { FormInstance } from 'antd';

import { getFieldEnumTree, getFieldEnumName } from "@/services/options"; // 枚举的引用，没有使用可以删除
import { handeDeleteCOMMODITY, handeGetBusinessCommodityList, handeGetCOMMODITYList, handeGetSellerCommodityList, handeSynchroCOMMODITY, handeSyncSellerCommodityInfo, handlDeleteUSERDEFINEDTYPE, handlGetUSERDEFINEDTYPEList, handlSynchroUSERDEFINEDTYPE } from '../service';
import PageTitleBox from '@/components/PageTitleBox';
import { deletePicture, SavePicture, uploadPicture } from '@/services/picture';
import defaultIcon from '../../../assets/brand/defaultIcon.png'
import OrderCategoryTree from './components/OrderCategoryTree';
import OrderCategoryManage from '../OrderCategoryManage';
import session from '@/utils/session';
import OrderCategoryTreeMultiple from './components/OrderCategoryTreeMultiple';
import Item from 'antd/lib/list/Item';
import { handleSetlogSave } from '@/utils/format';


const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('请上传JPEG、jpg、png格式的图片文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片大小不超过 2MB!');
    }
    return isJpgOrPng && isLt2M;
}


const OrderProductManage: React.FC<{ currentUser: CurrentUser | undefined }> = (props) => {
    const { currentUser } = props
    const { confirm } = Modal;
    const actionRef = useRef<ActionType>();
    const selectMerchantActionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [currentRow, setCurrentRow] = useState<any>();
    const [showDetail, setShowDetail] = useState<boolean>();
    const [modalVisible, handleModalVisible] = useState<boolean>();
    const [confirmLoading, handleConfirmLoading] = useState<boolean>(false) // 弹出框的内容表单是否在提交
    const [searchParams, setSearchParams] = useState<any>();
    // 分类的树形结构数据
    const [typeTreeData, setTypeTreeData] = useState<any>()
    // 表单里面的是否预售
    const [formPRESALE_TYPE, setFormPRESALE_TYPE] = useState<boolean>(false)
    const serverpartObj = session.get('serverpartObj')

    // 弹出框拖动效果
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    const draggleRef = React.createRef<any>()
    const [collapsible, setCollapsible] = useState<boolean>(false)

    // 文件列表
    const [fileList, setFileList] = useState<any>([])
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片
    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    // 显示新增点餐分类的悬浮框
    const [showFoodTypeModal, setShowFoodTypeModal] = useState<boolean>(false)
    // 获取商品的悬浮框
    const [getProducts, setGetProducts] = useState<boolean>(false)
    // 判断是否是第一次进入到页面
    const [isFirst, setIsFirst] = useState<boolean>(true)
    // 选择要上架的商品
    const [selectListShop, setSelectListShop] = useState<any>()
    // 点击选择了的商品上架的加载效果
    const [selectListShopLoading, setSelectListShopLoading] = useState<boolean>(false)
    // 选择的当前商家
    const [selectMerchant, setSelectMerchant] = useState<any>()

    const onDraggaleStart = (event, uiData) => {
        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = draggleRef.current?.getBoundingClientRect();
        if (!targetRect) {
            return;
        }
        setBounds({
            left: -targetRect.left + uiData.x,
            right: clientWidth - (targetRect.right - uiData.x),
            top: -targetRect.top + uiData.y,
            bottom: clientHeight - (targetRect.bottom - uiData.y),
        });
    };
    // 定义列表字段内容
    const columns: any = [
        {
            dataIndex: 'searchText',
            title: '查询内容',
            hideInTable: true,
            fieldProp: {
                placeholder: "请输入商品名称"
            }
        },

        // {
        //     title: '查询时间',
        //     dataIndex: 'search_date',
        //     valueType: 'dateRange',
        //     hideInTable: true,
        //     hideInDescriptions: true,
        //     search: {
        //         transform: (value) => {
        //             return {
        //                 OPERATE_DATE_Start: value[0],
        //                 OPERATE_DATE_End: value[1],
        //             };
        //         },
        //     },
        //     // initialValue: [ moment().subtract(1, 'M').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
        // },
        // {
        //     title: '上级类别',
        //     align: 'center',
        //     width: 150,
        //     ellipsis: true,
        //     dataIndex: 'USERDEFINEDTYPE_PID',
        //     hideInSearch: true,
        //     hideInDescriptions: true,
        // },
        {
            title: '服务区',
            dataIndex: "SERVERPART_IDS",
            hideInTable: true,
            valueType: 'select',
            valueEnum: serverpartObj,
            fieldProps: {
                showSearch: true, // 支持输入文字搜索
                filterOption: (input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
            }
        },
        {
            dataIndex: 'USERDEFINEDTYPE_NAME',
            title: '商品类别',
            align: 'center',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
            hideInDescriptions: true,
        },
        {
            dataIndex: 'COMMODITY_NAME',
            title: '商品名称',
            align: 'center',
            width: 300,
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.COMMODITY_NAME ? <a onClick={() => {
                    console.log('recordrecordrecord', record);

                    setCurrentRow(record)
                    setShowDetail(true)
                }}>{record?.COMMODITY_NAME}</a> : ""
            }
        },
        {
            dataIndex: 'COMMODITY_RETAILPRICE',
            title: '零售价',
            align: 'center',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
            sorter: (a, b) => a.COMMODITY_RETAILPRICE - b.COMMODITY_RETAILPRICE,
        },
        {
            dataIndex: 'COMMODITY_UNIT',
            title: '商品单位',
            align: 'center',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'COMMODITY_RULE',
            title: '商品规格',
            align: 'center',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'UPPER_STATE',
            title: '上架状态',
            align: 'center',
            width: 120,
            ellipsis: true,
            valueType: "select",
            valueEnum: {
                "-1": "全部",
                "1": "上架",
                "0": "下架"
            },
            initialValue: '-1'
        },
        {
            dataIndex: 'OPERATE_DATE',
            title: '修改时间',
            align: 'center',
            width: 180,
            ellipsis: true,
            hideInSearch: true,
            sorter: (a, b) => new Date(a.OPERATE_DATE).getTime() - new Date(b.OPERATE_DATE).getTime(),
            defaultSortOrder: 'descend',
        },
        {
            dataIndex: 'SERVERPART_NAME',
            title: '服务区名称',
            align: 'center',
            width: 180,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'SHOPNAME',
            title: '门店名称',
            align: 'center',
            width: 180,
            ellipsis: true,
            hideInSearch: true,
        }
    ];
    // 新增商品的columns
    const getProductsColumns: any = [
        {
            title: '查询内容',
            dataIndex: 'SearchKeyValue',
            hideInTable: true,
        },
        {
            title: "序号",
            width: 70,
            dataIndex: "index",
            ellipsis: true,
            hideInSearch: true,
            align: 'center',
            valueType: "index"
        },
        {
            title: "商品名称",
            width: 300,
            dataIndex: "COMMODITY_NAME",
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: "商品条码",
            width: 200,
            dataIndex: "COMMODITY_BARCODE",
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: "零售价",
            width: 150,
            dataIndex: "COMMODITY_RETAILPRICE",
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: "商品单位",
            width: 150,
            dataIndex: "COMMODITY_UNIT",
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: "商品规格",
            width: 150,
            dataIndex: "COMMODITY_RULE",
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
    ]

    // 预览上传后的图片
    const handlePreview = async () => {
        setFileList(fileList)
        setImagePreviewVisible(true)
    };
    const handleChangePreview = (val: any) => {
        setImagePreviewVisible(val)
    }

    const handelDelete = async (commodityid: number) => {
        const result = await handeDeleteCOMMODITY({ COMMODITYId: commodityid });

        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Desc}` || `${result.Result_Code}:删除失败`);
        } else {
            message.success('删除成功！');
            actionRef.current?.reload()
        }
    };

    const handleAddUpdate = async (res: any) => {
        let req: any = {}
        console.log('resresresresresres', res);

        if (currentRow?.COMMODITY_ID) {
            req = {
                ...currentRow,
                ...res,
                // MERCHANTS_ID: selectedId,
                OWNERUNIT_ID: currentUser?.OwnerUnitId,
                OWNERUNIT_NAME: currentUser?.OwnerUnitName,
                PROVINCE_CODE: currentUser?.ProvinceCode,
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        } else {
            req = {
                ...res,
                // MERCHANTS_ID: selectedId,
                OWNERUNIT_ID: currentUser?.OwnerUnitId,
                OWNERUNIT_NAME: currentUser?.OwnerUnitName,
                PROVINCE_CODE: currentUser?.ProvinceCode,
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                OPERATE_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        }
        // const data = await handeSynchroCOMMODITY(req)
        if (res.ImageInfo && res.ImageInfo.length > 0) {
            let imageData = await handleUploadShopImg(res)
            console.log('imageData', imageData);
            let imgList: any = imageData.Result_Data
            req.ImageInfo = imgList
        }

        console.log('reqreqreqreqreq', req);


        const data = await handeSyncSellerCommodityInfo({ list: [req] })
        handleConfirmLoading(false)
        if (data.Result_Code === 100) {
            handleSetlogSave(`${currentRow?.COMMODITY_ID ? '更新' : '新增'}【${data.Result_Data?.COMMODITY_NAME}】成功`)
            message.success("同步成功！")
            setCurrentRow(undefined)
            formRef?.current?.resetFields()
            handleConfirmLoading(false)
            setShowDetail(false)
            setFileList([])
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    };

    // 上传商品图片
    const handleUploadShopImg = async (formRes: any) => {

        if (formRes.ImageInfo && formRes.ImageInfo.length > 0) {
            const formData = new FormData();
            formRes.ImageInfo.forEach((file: any) => {
                formData.append('files[]', file.originFileObj);
                formData.append('ImageName', typeof file !== 'string' ? file?.name : '');
            });
            formData.append('imageType', "1000");
            formData.append('TableType', "1207");

            console.log('formData', formData);
            let res = await SavePicture(formData)
            return res
        }

    }

    // 获取商品类别的树
    const handleGetCOMMODITYTYPE = async () => {
        const req = {
            OWNERUNIT_ID: currentUser?.OwnerUnitId,
            PROVINCE_CODE: "",
            GOODSTYPE: 3000,
            USERDEFINEDTYPE_STATE: 1
            // SearchKey: ""
        }
        let data = await handlGetUSERDEFINEDTYPEList(req);
        console.log('datadatadatadatadata2', data);
        if (data && data.length > 0) {
            // data.unshirft({ USERDEFINEDTYPE_NAME: "默认类别", USERDEFINEDTYPE_ID: -1 })

            setTypeTreeData(processTreeData(data))
        } else {
            setTypeTreeData([])
        }

    }
    const processTreeData = (data: any) => {
        return data.map((item: any) => {
            if (item.children && item.children.length > 0) {
                return {
                    ...item,
                    disabled: true,  // 有子节点的节点禁用
                    children: processTreeData(item.children)
                };
            }
            return item;
        });
    };
    useEffect(async () => {
        await handleGetCOMMODITYTYPE()
    }, [])

    return (
        <div>
            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                {/* 单选的 */}
                {/* <OrderCategoryTree setSelectedId={setSelectedId} selectedId={selectedId} setCollapsible={setCollapsible} collapsible={collapsible} /> */}
                {/* 多选的 */}
                <OrderCategoryTreeMultiple setSelectedId={setSelectedId} selectedId={selectedId} setCollapsible={setCollapsible} collapsible={collapsible} />

                <div style={{
                    width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        scroll={{ x: "100%", y: 'calc(100vh - 410px)' }}
                        rowKey={(record) => {
                            return `${record?.COMMODITY_ID}-${record?.OPERATE_DATE}`
                        }}
                        formRef={formRef}
                        headerTitle={<PageTitleBox props={props} />} // 列表表头
                        actionRef={actionRef}
                        search={{ span: 6, labelWidth: 'auto' }}
                        bordered
                        // 请求数据
                        request={async (params, sorter) => {
                            if (isFirst) {
                                setIsFirst(false)
                                return []
                            }

                            console.log('selectedId', selectedId);


                            const req = {
                                searchParameter: {
                                    // OWNERUNIT_ID: currentUser?.OwnerUnitId,
                                    PROVINCE_CODE: currentUser?.ProvinceCode,
                                    SERVERPART_IDS: params?.SERVERPART_IDS || "",
                                    SELLER_IDS: selectedId || "",
                                    UPPER_STATE: params?.UPPER_STATE === "-1" ? "" : params?.UPPER_STATE,

                                    // OPERATE_DATE_Start: params?.OPERATE_DATE_Start || "",
                                    // OPERATE_DATE_End: params?.OPERATE_DATE_End || "",
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                                SortStr: "OPERATE_DATE desc",
                                keyWord: {
                                    Key: "COMMODITY_NAME",
                                    Value: params?.searchText || ""
                                },

                            }
                            console.log('reqreqreqreq', req);

                            const data = await handeGetSellerCommodityList(req);
                            handleSetlogSave(`点击查询按钮`)
                            // const data = await handeGetCOMMODITYList(req);
                            console.log('datadatadatadatadata', data);
                            if (data.List && data.List.length > 0) {
                                return { data: data.List, success: true, total: data.TotalCount }
                            }
                            return { data: [], success: true }
                        }}
                        columns={columns}
                        toolbar={{
                            actions: [
                                <>
                                    <Button type={"primary"} onClick={() => {
                                        setGetProducts(true)
                                    }}>获取商品</Button>
                                    {/* < Button type={"primary"} onClick={() => {
                                            setShowDetail(true)
                                        }}>新增商品</Button> */}
                                </>
                            ],
                        }}
                    />
                </div>
            </div>
            {/* 图片预览组件 */}
            {
                fileList && fileList.length > 0 && <div style={{ display: 'none' }}>
                    <Image.PreviewGroup
                        preview={{
                            visible: imagePreviewVisible,
                            onVisibleChange: vis => {
                                handleChangePreview(vis)
                            }
                        }}>
                        {
                            fileList.map((n) => <Image src={n.url} key={n.url} />)
                        }
                    </Image.PreviewGroup>
                </div>
            }


            <Modal
                title={
                    <div
                        className="modal-drag-title"
                        style={{
                            width: '100%',
                            cursor: 'move',
                        }}
                        onMouseOver={() => {
                            if (disabled) {
                                setDraggleDisabled(false)
                            }
                        }}
                        onMouseOut={() => {
                            setDraggleDisabled(true)
                        }}

                        onFocus={() => { }}
                        onBlur={() => { }}
                    >
                        {currentRow?.COMMODITY_ID ? '编辑商品详情' : '新增商品'}
                    </div>
                }
                destroyOnClose={true}
                width={1200}
                visible={showDetail}
                confirmLoading={confirmLoading}
                afterClose={() => {
                    formRef.current?.resetFields();
                    setCurrentRow(undefined);
                }}
                onCancel={() => {
                    handleConfirmLoading(false)
                    setShowDetail(false)
                    setCurrentRow(undefined)
                    setFileList([])
                }}

                onOk={async () => { // 提交框内的数据
                    formRef?.current?.validateFields().then(() => {
                        handleConfirmLoading(true)
                        formRef?.current?.submit()
                    })
                }}
                bodyStyle={{
                    maxHeight: '700px', // 你可以根据需要调整高度
                    overflowY: 'auto',
                }}
                modalRender={(modal) => {
                    return <Draggable
                        disabled={disabled}
                        bounds={bounds}
                        onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                        handle=".modal-drag-title"
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >
                <ProForm
                    layout={'horizontal'}
                    formRef={formRef}
                    autoFocusFirstInput
                    submitter={false}
                    labelCol={{ style: { width: 80 } }}
                    preserve={false}
                    request={async () => {
                        if (currentRow) {
                            if (currentRow?.ImageInfo && currentRow?.ImageInfo.length > 0) {
                                let list: any = []
                                currentRow?.ImageInfo.forEach((item: any) => {
                                    let obj = JSON.parse(JSON.stringify(item))
                                    obj.url = obj.ImageUrl
                                    obj.name = obj.ImageName
                                    obj.uid = item.ImageId
                                    obj.status = 'done'
                                    list.push(obj)
                                })
                                setFileList(list)
                            }

                            return {
                                ...currentRow,
                                OPERATE_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
                            }
                        } else {
                            return {
                                OPERATE_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
                                OPERATE_PERSON: currentUser?.Name,
                                UPPER_STATE: 1
                            }
                        }
                    }}
                    // initialValues={currentRow ? {
                    //     ...currentRow,
                    //     OPERATE_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
                    // } : {
                    //     OPERATE_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
                    //     OPERATE_PERSON: currentUser?.Name,
                    //     UPPER_STATE: 1
                    // }}
                    onFinish={async (values) => {
                        let newValue = { ...values };
                        if (currentRow) {
                            // 编辑数据
                            newValue = { ...values };
                        }
                        console.log('currentRowcurrentRowcurrentRow', currentRow);

                        // 如果有开关，要把开关的代码写进去
                        await handleAddUpdate(newValue);

                        handleConfirmLoading(false)
                        setFormPRESALE_TYPE(false)
                    }}
                >
                    <Row gutter={8}>
                        <Col span={8}>
                            <Row gutter={8}>
                                <Col span={18}>
                                    <ProFormTreeSelect
                                        name="USERDEFINEDTYPE_ID"
                                        label="商品类别"
                                        request={async () => {
                                            const req = {
                                                OWNERUNIT_ID: currentUser?.OwnerUnitId,
                                                PROVINCE_CODE: "",
                                                GOODSTYPE: 3000,
                                                USERDEFINEDTYPE_STATE: 1
                                                // SearchKey: ""
                                            }
                                            let data = await handlGetUSERDEFINEDTYPEList(req);
                                            console.log('datadatadatadatadata2', data);
                                            if (data && data.length > 0) {
                                                // data.unshirft({ USERDEFINEDTYPE_NAME: "默认类别", USERDEFINEDTYPE_ID: -1 })
                                                return processTreeData(data)
                                            } else {
                                                return []
                                            }
                                        }}
                                        fieldProps={{
                                            fieldNames: {
                                                label: 'USERDEFINEDTYPE_NAME',
                                                value: 'USERDEFINEDTYPE_ID',
                                                children: 'children'
                                            },
                                            showSearch: true,
                                            treeDefaultExpandAll: true,
                                            filterTreeNode: (input, node) =>
                                                (node.USERDEFINEDTYPE_NAME || '').toLowerCase().includes(input.toLowerCase()),
                                            onChange: (value, label) => {
                                                console.log('value', value);
                                                console.log('label', label);

                                                formRef.current?.setFieldsValue({
                                                    USERDEFINEDTYPE_NAME: label.toString(),
                                                    USERDEFINEDTYPE_ID: value
                                                });
                                            }
                                        }}
                                        rules={[
                                            {
                                                required: true,
                                                message: "请选择上级类别"
                                            }
                                        ]}
                                    />
                                </Col>
                                <Col span={4}>
                                    <Button type='primary' onClick={() => {
                                        setShowFoodTypeModal(true)
                                    }}>新增</Button>
                                </Col>
                            </Row>
                        </Col>
                        <Col style={{ display: 'none' }}>
                            <ProFormText
                                name="USERDEFINEDTYPE_NAME"
                                label=""
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormText
                                name="COMMODITY_NAME"
                                label="商品名称"
                                rules={[
                                    {
                                        required: true,
                                        message: "请输入商品名称"
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormDigit
                                name="COMMODITY_BARCODE"
                                label="商品条码"
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormText
                                name="COMMODITY_STOCK"
                                label="每日可售"
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormDatePicker
                                width={'lg'}
                                name="UPPER_DATE"
                                label="生效时间"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择生效时间'
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormDatePicker
                                width={'lg'}
                                name="OFF_DATE"
                                label="下架时间"
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormText
                                name="COMMODITY_UNIT"
                                label="商品单位"
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormText
                                name="COMMODITY_RULE"
                                label="商品规格"
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormDigit
                                name="COMMODITY_RETAILPRICE"
                                label="零售价格"
                                rules={[
                                    {
                                        required: true,
                                        message: "请输入零售价格"
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormDigit
                                name="COMMODITY_PURCHASEPRICE"
                                label="进货价格"
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormDigit
                                name="COMMODITY_MEMBERPRICE"
                                label="会员价格"
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormSelect
                                name="UPPER_STATE"
                                label="上架状态"
                                options={[{ label: "已上架", value: 1 }, { label: "未上架", value: 0 }]}
                                rules={[
                                    {
                                        required: true,
                                        message: "请选择上架状态"
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormText
                                name="STAFF_NAME"
                                label="操作人员"
                                disabled
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormText
                                name="OPERATE_DATE"
                                label="操作时间"
                                disabled
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormText
                                name="COMMODITY_EN"
                                label="商品简介"
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormUploadButton
                                name="ImageInfo"
                                label="商品图片"
                                listType="picture-card"
                                accept="image/*"
                                fieldProps={{
                                    beforeUpload,
                                    maxCount: 1,
                                    onPreview: handlePreview,
                                    fileList: fileList, // 绑定 fileList
                                    onChange: async (info: any) => {
                                        if (info.file.status === 'removed') {
                                            const index = fileList.findIndex(n => n.uid === info.file.uid);
                                            confirm({
                                                title: '确认删除该文件吗？',
                                                icon: <ExclamationCircleOutlined />,
                                                async onOk() {
                                                    if (info.file.ImageId) {
                                                        const deleteLoading = message.loading('正在删除...')
                                                        const success = await deletePicture(info.file?.ImagePath, info.file?.uid, '', '6000')
                                                        await handeSyncSellerCommodityInfo({
                                                            list: [{
                                                                ...currentRow,
                                                                ImageInfo: null
                                                            }]
                                                        })
                                                        deleteLoading()

                                                        if (success) {
                                                            const files = [...fileList]
                                                            files.splice(index, 1)
                                                            setFileList(files)
                                                            message.success("删除成功")
                                                            actionRef.current?.reload()
                                                        }
                                                        else {
                                                            message.error("删除失败")
                                                        }
                                                    } else {
                                                        const files = [...fileList];
                                                        files.splice(index, 1);
                                                        setFileList(files);
                                                    }
                                                },
                                                onCancel() {
                                                },
                                            });
                                        } else {
                                            setFileList(info.fileList)
                                        }
                                    }
                                }}
                            />
                        </Col>
                    </Row>
                </ProForm>
            </Modal>

            <Modal
                title={"新增点餐分类"}
                destroyOnClose={true}
                width={1400}
                visible={showFoodTypeModal}
                footer={false}
                onCancel={() => {
                    setShowFoodTypeModal(false)
                }}
                bodyStyle={{
                    maxHeight: '700px', // 你可以根据需要调整高度
                    overflowY: 'auto',
                }}
            >
                <OrderCategoryManage />
            </Modal>


            {/* 获取商品的悬浮框 */}
            <Modal
                title={"获取商品"}
                destroyOnClose={true}
                width={1200}
                bodyStyle={{
                    height: '700px', // 你可以根据需要调整高度
                    overflowY: 'auto',
                }}
                visible={getProducts}
                footer={<div style={{ width: "100%", display: 'flex', justifyContent: 'flex-end', boxSizing: 'border-box', padding: '0 16px' }}>
                    <Button type={"primary"} loading={selectListShopLoading} onClick={async () => {
                        if (selectListShop && selectListShop.length > 0) {
                            setSelectListShopLoading(true)
                            console.log('selectListShopselectListShopselectListShop', selectListShop);

                            let idList: any = []

                            selectListShop.forEach((item: any) => {
                                if (idList.indexOf(item.SELLER_ID) === -1) {
                                    idList.push(item.SELLER_ID)
                                }
                            })
                            console.log('idList', idList);

                            let data: any = {}
                            for (let i = 0; i < idList.length; i++) {
                                let list: any = []
                                selectListShop.forEach((item: any) => {
                                    let obj: any = JSON.parse(JSON.stringify(item))
                                    // obj.MERCHANTS_ID = selectedId
                                    obj.MERCHANTS_ID = item.SELLER_ID
                                    obj.UPPER_STATE = 1
                                    obj.STAFF_ID = currentUser?.ID
                                    obj.STAFF_NAME = currentUser?.Name
                                    obj.OPERATE_DATE = moment().format('YYYY-MM-DD HH:mm:ss')
                                    obj.PROVINCE_CODE = currentUser?.ProvinceCode
                                    list.push(obj)
                                })

                                const req: any = {
                                    list: list
                                }
                                console.log('req', req);
                                data = await handeSyncSellerCommodityInfo(req)
                            }



                            // let list: any = []
                            // selectListShop.forEach((item: any) => {
                            //     let obj: any = JSON.parse(JSON.stringify(item))
                            //     // obj.MERCHANTS_ID = selectedId
                            //     obj.MERCHANTS_ID = item.SELLER_ID
                            //     obj.UPPER_STATE = 1
                            //     obj.STAFF_ID = currentUser?.ID
                            //     obj.STAFF_NAME = currentUser?.Name
                            //     obj.OPERATE_DATE = moment().format('YYYY-MM-DD HH:mm:ss')
                            //     obj.PROVINCE_CODE = currentUser?.ProvinceCode
                            //     list.push(obj)
                            // })

                            // const req: any = {
                            //     list: list
                            // }
                            // console.log('req', req);

                            // const data = await handeSyncSellerCommodityInfo(req)
                            // console.log('data', data);
                            if (data.Result_Code === 100) {
                                message.success("同步成功!")
                                setGetProducts(false)
                                setSelectListShop([])
                                setSelectListShopLoading(false)
                                actionRef.current?.reload()
                            } else {
                                message.error(data.Result_Desc)
                            }
                        } else {
                            message.error('请勾选需要上架的商品！')
                        }
                    }}>确认上架</Button>
                </div>}
                onCancel={() => {
                    setGetProducts(false)
                    setSelectListShop([])
                    setSelectListShopLoading(false)
                    setSelectMerchant([])
                }}
            >

                <div style={{ width: '100%', height: '100%', display: 'flex', justifyContent: 'space-between' }}>
                    {/* <div style={{ width: '300px', height: '100%' }}> */}
                    {/* <OrderCategoryTree setSelectedId={setSelectMerchant} selectedId={selectMerchant} reload={true} actionRef={selectMerchantActionRef} /> */}
                    {/* <OrderCategoryTreeMultiple setSelectedId={setSelectedId} selectedId={selectedId} setCollapsible={setCollapsible} collapsible={collapsible} /> */}
                    {/* </div> */}
                    <div style={{ width: '100%', height: '100%' }}>
                        <ProTable
                            actionRef={selectMerchantActionRef}
                            columns={getProductsColumns}
                            bordered
                            scroll={{ x: '100%', y: '450px' }}
                            rowKey={"COMMODITY_ID"}
                            options={false}
                            request={async (params) => {
                                console.log('selectedIdselectedIdselectedId', selectedId);

                                const req: any = {
                                    ProvinceCode: currentUser?.ProvinceCode,
                                    ServerpartShopId: "",
                                    // SellerId: selectMerchant?.toString(),
                                    SellerId: selectedId?.toString(),
                                    SearchKeyName: "COMMODITY_NAME",
                                    SearchKeyValue: params?.SearchKeyValue || "",
                                    PageIndex: 1,
                                    PageSize: 999999,
                                    SortStr: ""
                                }
                                console.log('reqreqreqreq', req);
                                const data = await handeGetBusinessCommodityList(req)
                                console.log('datadatadatadata', data);
                                if (data.List && data.List.length > 0) {
                                    return { data: data.List, success: true, total: data.TotalCount }
                                }
                                return { data: [], success: true }
                            }}
                            rowSelection={{
                                type: "checkbox",
                                onChange: (_, selectedRows) => {
                                    setSelectListShop(selectedRows)
                                }
                            }}
                        />
                    </div>
                </div>
            </Modal>
        </div >
    );
};
export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(OrderProductManage);