import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useRef, useState } from "react";
import LeftSelectTree from "@/pages/reports/settlementAccount/component/leftSelectTree";
import ServerpartInfo from "./components/serverpartInfo";
import ProCard from "@ant-design/pro-card";
import { ExclamationCircleOutlined, MenuFoldOutlined } from "@ant-design/icons";
import { Button, Col, FormInstance, message, Modal, Row, Tree, Image, Menu, Avatar, Tabs } from "antd";
import LoadingBox from "@/pages/reports/Finance/businessAnalysis/components/loading";
import session from "@/utils/session";
import moment from 'moment'
import { handleSynchroSERVERPART } from "@/pages/newDataAnalysis/service";
import useRequest from "@ahooksjs/use-request";
import { getServerpartTree } from "@/services/options";
import { handleSynchroNOTICEINFO } from "@/pages/basicManage/highwayHeadlines/service";
import ProForm, { ProFormText, ProFormUploadButton } from "@ant-design/pro-form";
import { deletePicture, getPictureList, uploadPicture } from "@/services/picture";
import { handeGetPictureList } from "../service";
import SubMenu from "antd/lib/menu/SubMenu";
import Draggable from "react-draggable";
import searchIcon from '@/assets/ai/searchIcon.png'
import close from '@/assets/ai/close.png'
import './style.less'
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 < 5;
    if (!isLt2M) {
        message.error('图片大小不超过 5MB!');
    }
    return isJpgOrPng && isLt2M;
}

const serverpartInfo: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { confirm } = Modal;
    const { currentUser } = props
    const searchTreeRef = useRef<FormInstance>();
    const modalRef = useRef<FormInstance>();
    const [collapsible, setCollapsible] = useState<boolean>(false)
    const [treeView, setTreeView] = useState<any>()
    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    // 显示右边的表单
    const [showRightForm, setShowRightForm] = useState<boolean>(true)
    const serverPartRef = useRef<any>()
    const shopregionObj = session.get('shopregionObj')
    // 显示上传图片的悬浮框
    const [showUploadImgModal, setShowUploadImgModal] = useState<boolean>(false)
    // 点击的按钮类型  1 服务区图片上传  2 母婴室图片上传  3  司机之家图片上传  4  住宿客房图片上传  5 便利店图片上传
    const [showType, setShowType] = useState<number>(0)
    // 悬浮框的点击确认的效果
    const [confirmLoading, setConfirmLoading] = useState<boolean>(false)
    // 文件列表
    const [fileList, setFileList] = useState<any>([])
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片
    const [currenRegion, setCurrenRegion] = useState<any>(); // 当前选中左侧菜单的片区节点
    const [currenMenu, setCurrenMenu] = useState<any>(); // 当前选中左侧菜单的服务区节点
    // 上传文件选择的tab
    const [selectActiveKey, setSelectActiveKey] = useState<string>('1')

    // 弹出框拖动效果
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    const draggleRef = React.createRef<any>()
    // 默认展开的菜单
    const [defaultOpenKeys, setDefaultOpenKeys] = useState<any>();
    // 显示服务区树搜索框
    const [showServiceSearchBox, setShowServiceSearchBox] = useState<boolean>(false)
    // 初始的最全的左侧菜单树 数据
    const [menuData, setMenuData] = useState<any>();
    // 判断左侧数据是否加载好了
    const [showLeftTreeData, setShowLeftTreeData] = useState<boolean>(false)

    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 { loading: treeLoading, data: treeViews } = useRequest(async () => {
        const data = await getServerpartTree(currentUser?.ProvinceCode, currentUser?.CityAuthority, true, true, true)

        let list: any = []
        data.forEach((item: any) => {
            if (item.value !== 424) {
                list.push(item)
            }
        })

        setTreeView(list)
        setMenuData(list)

        let obj: any = handleGetTreeFirst(list)
        if (obj && obj.length > 0) {
            let defaultKey: any = []
            if (obj && obj.length > 0) {
                obj.forEach((item: any) => {
                    defaultKey.push(item.key)
                })
            }
            setDefaultOpenKeys(defaultKey)
            let lastObj: any = obj[obj.length - 1]

            setCurrenMenu(lastObj.value)
            setSelectedId('')
            setCurrenRegion('')
            // 只有修改服务区的时候 触发刷新
            setShowRightForm(false)
            setTimeout(() => {
                setShowRightForm(true)
            }, 10)
        }
        setShowLeftTreeData(true)
        return data
    })
    // 根据左侧选中的菜单加载右侧数据
    const loadSelectedId = (item?: any) => {
        console.log('itemitemitem', item);

        // 选中的子菜单key
        const [type, value] = item.key.split('-')

        if (type === '1') {
            setCurrenMenu(value)
            setSelectedId('')
            setCurrenRegion('')


            console.log('value', value);
            let serverpartObj = session.get('serverpartObj')
            handleSetlogSave(`${serverpartObj && value && serverpartObj[value] ? `查看${serverpartObj[value]}基础信息` : ""}`)

            // 只有修改服务区的时候 触发刷新
            setShowRightForm(false)
            setTimeout(() => {
                setShowRightForm(true)
            }, 10)
        }
        else if (type === '2') {
            setSelectedId(value)
            setCurrenMenu('')
            setCurrenRegion('')
        }
        else {
            setCurrenRegion(value)
            setSelectedId('')
            setCurrenMenu('')
        }

    }

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

    // 保存方法
    const handleSubmitForm = async () => {
        let res: any = serverPartRef.current?.formRef.current?.getFieldsValue()
        console.log('res', res);
        // 表单查到的详情 更新里面的全部数据
        let detailObj: any = serverPartRef.current?.serverPartDetail
        console.log('detailObj', detailObj);
        let formDetailAll: any = serverPartRef.current?.formDetailAll
        console.log('formDetailAll', formDetailAll);


        // 把分区的数据取出来
        let objA: any = {
            SERVERPART_REGION: res?.currentArea,
            SERVERPART_REGIONNAME: res?.currentArea ? shopregionObj[res?.currentArea] : '',

        }
        let objB: any = {
            SERVERPART_REGION: res?.otherArea,
            SERVERPART_REGIONNAME: res?.otherArea ? shopregionObj[res?.otherArea] : ''
        }
        for (let key in res) {
            if (key.indexOf('_A') > 0) {
                let newKey: string = key.split('_A')[0]
                objA[newKey] = res[key]
            } else if (key.indexOf('_B') > 0) {
                let newKey: string = key.split('_B')[0]
                objB[newKey] = res[key]
            }
        }
        // 详情里面本身的服务区数组数据
        let detailServerPartList: any = detailObj?.ServerPartInfo
        if (detailServerPartList && detailServerPartList.length === 2) {
            detailServerPartList.forEach((item: any) => {
                if (Number(item.SERVERPART_REGION) === Number(objA.SERVERPART_REGION)) {
                    objA.SERVERPARTINFO_ID = item.SERVERPARTINFO_ID
                    objA.SERVERPART_ID = currenMenu
                    objA.GREENSPACEAREA = item.GREENSPACEAREA
                    objA.SCENICAREA = item.SCENICAREA
                }
                if (Number(item.SERVERPART_REGION) === Number(objB.SERVERPART_REGION)) {
                    objB.SERVERPARTINFO_ID = item.SERVERPARTINFO_ID
                    objB.SERVERPART_ID = currenMenu
                    objB.GREENSPACEAREA = item.GREENSPACEAREA
                    objB.SCENICAREA = item.SCENICAREA
                }
            })
        } else {
            if (objB.SERVERPART_REGION) {
                objB.SERVERPARTINFO_ID = detailServerPartList.length[0].SERVERPARTINFO_ID
                objB.SERVERPART_ID = currenMenu
                objB.GREENSPACEAREA = detailServerPartList.length[0].GREENSPACEAREA
                objB.SCENICAREA = detailServerPartList.length[0].SCENICAREA
            }
        }

        console.log('objA', objA);
        console.log('objB', objB);



        const req: any = {
            SERVERPART_ID: detailObj?.SERVERPART_ID,
            SERVERPART_NAME: res?.SERVERPART_NAME,
            SERVERPART_ADDRESS: res?.SERVERPART_ADDRESS,
            SERVERPART_INDEX: res?.SERVERPART_INDEX,
            EXPRESSWAY_NAME: res?.EXPRESSWAY_NAME,
            SELLERCOUNT: detailObj?.SELLERCOUNT,
            SERVERPART_AREA: res?.SERVERPART_AREA,
            SERVERPART_X: res?.SERVERPART_X,
            SERVERPART_Y: res?.SERVERPART_Y,
            SERVERPART_TEL: detailObj?.SERVERPART_TEL,
            SERVERPART_INFO: res?.SERVERPART_INFO,
            PROVINCE_CODE: detailObj?.PROVINCE_CODE,
            SERVERPART_CODE: res?.SERVERPART_CODE,
            SERVERPART_TYPE: res?.SERVERPART_TYPE,
            STARTDATE: res?.STARTDATE,
            OWNEDCOMPANY: res?.OWNEDCOMPANY,
            FLOORAREA: res?.FLOORAREA,
            BUSINESSAREA: detailObj?.BUSINESSAREA,
            SHAREAREA: res?.SHAREAREA,
            MANAGERCOMPANY: res?.MANAGERCOMPANY,
            SPREGIONTYPE_ID: detailObj?.SPREGIONTYPE_ID,
            SPREGIONTYPE_NAME: detailObj?.SPREGIONTYPE_NAME,
            SPREGIONTYPE_INDEX: detailObj?.SPREGIONTYPE_INDEX,
            STATISTICS_TYPE: detailObj?.STATISTICS_TYPE,
            FIELDENUM_ID: detailObj?.FIELDENUM_ID,
            CITY_CODE: detailObj?.CITY_CODE,
            COUNTY_CODE: detailObj?.COUNTY_CODE,
            SERVERPART_IPADDRESS: detailObj?.SERVERPART_IPADDRESS,
            DAYINCAR: detailObj?.DAYINCAR,
            HKBL: detailObj?.HKBL,
            TOTALPARKING: detailObj?.TOTALPARKING,
            SHORTNAME: detailObj?.SHORTNAME,
            REGIONTYPE_ID: detailObj?.REGIONTYPE_ID,
            STATISTIC_TYPE: detailObj?.STATISTIC_TYPE,
            PROVINCE_NAME: detailObj?.PROVINCE_NAME,
            REGIONTYPE_NAME: detailObj?.REGIONTYPE_NAME,
            STAFF_ID: currentUser?.ID,
            STAFF_NAME: currentUser?.Name,
            OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
            SERVERPART_DESC: detailObj?.SERVERPART_DESC,
            OWNERUNIT_ID: detailObj?.OWNERUNIT_ID,
            OWNERUNIT_NAME: detailObj?.OWNERUNIT_NAME,
            RtServerPart: {
                RTSERVERPART_ID: detailObj?.RtServerPart?.RTSERVERPART_ID,
                SERVERPART_ID: detailObj?.RtServerPart?.SERVERPART_ID,
                SERVERPART_ADDRESS: res?.SERVERPART_ADDRESS,
                EXPRESSWAY_NAME: res?.EXPRESSWAY_NAME,
                SELLERCOUNT: detailObj?.RtServerPart?.SELLERCOUNT,
                SERVERPART_X: res?.SERVERPART_X,
                SERVERPART_Y: res?.SERVERPART_Y,
                SERVERPART_TEL: detailObj?.RtServerPart?.SERVERPART_TEL,
                STARTDATE: res?.STARTDATE,
                SERVERPART_AREA: res?.SERVERPART_AREA,
                FLOORAREA: res?.FLOORAREA,
                BUSINESSAREA: detailObj?.RtServerPart?.BUSINESSAREA,
                SHAREAREA: res?.SHAREAREA,
                TOTALPARKING: detailObj?.RtServerPart?.TOTALPARKING,
                OWNEDCOMPANY: res?.OWNEDCOMPANY,
                MANAGERCOMPANY: res?.MANAGERCOMPANY,
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                SERVERPART_INFO: res?.SERVERPART_INFO,
                CENTERSTAKE_NUM: res?.CENTERSTAKE_NUM,
                TAXPAYER_IDENTIFYCODE: res?.TAXPAYER_IDENTIFYCODE,
                WATERINTAKE_TYPE: res?.WATERINTAKE_TYPE,
                SEWAGEDISPOSAL_TYPE: res?.SEWAGEDISPOSAL_TYPE,
                BUSINESS_REGION: detailObj?.RtServerPart?.BUSINESS_REGION,
            },
            ServerPartInfo: objB.SERVERPART_REGION ? [objA, objB] : [objA]
        }
        console.log('req', req);

        const data = await handleSynchroSERVERPART(req)

        let serverpartObj = session.get('serverpartObj')
        handleSetlogSave(`${serverpartObj && currenMenu && serverpartObj[currenMenu] ? `更新${serverpartObj[currenMenu]}的基础信息` : ""}`)

        if (res.carryingCapacity) {
            let carryReq: any = {}
            if (formDetailAll?.carryingCapacity) {
                carryReq = {
                    ...formDetailAll.carryingCapacityObj,
                    NOTICEINFO_TYPE: "3020",
                    SERVERPART_ID: currenMenu,
                    FEEDBACK_CONTENT: res.carryingCapacity
                }
            } else {
                carryReq = {
                    NOTICEINFO_TYPE: "3020",
                    SERVERPART_ID: currenMenu,
                    FEEDBACK_CONTENT: res.carryingCapacity
                }
            }
            console.log('carryReq', carryReq);
            const carryData = await handleSynchroNOTICEINFO(carryReq)
            console.log('carryData', carryData);
        } else {
            if (formDetailAll?.carryingCapacity) {
                let carryReq: any = {
                    ...formDetailAll.carryingCapacity,
                    FEEDBACK_CONTENT: ""
                }
                console.log('carryReq2', carryReq);
                const carryData = await handleSynchroNOTICEINFO(carryReq)
                console.log('carryData2', carryData);
            }
        }

        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            setShowRightForm(false)
            setTimeout(() => {
                setShowRightForm(true)
            }, 1000)
        } else {
            message.error(data.Result_Desc)
        }
    }

    // 生成左侧菜单
    const getMenuDom = (data: any[], callback: (item: any) => void) => {
        return (data.map((element: any) => {
            if (element.node) {
                // 绑定当前节点的子集
                if (element.node.children && element.node.children.length > 0) {
                    return (
                        <SubMenu title={element.node.desc !== '0' ? <><span>{element.node.label}</span>
                            {/* <span style={{ position: 'absolute', right: '10', top: '9px', lineHeight: '20px', padding: '2px 3px', color: 'red' }}>
                                    [{element.node.desc}]</span> */}
                        </> : element.node.label}
                            icon={element.node.ico ? <Avatar src={element.node.ico} size={16} style={{ marginRight: 4 }} shape="square" /> : null}
                            key={`${element.node.key || element.node.value}`}
                            onTitleClick={(item) => {
                                // 选中一级菜单
                                if (!currenMenu || item.key !== `${currenMenu?.key}`) {
                                    callback.call(callback, item)
                                }
                                item.domEvent.stopPropagation();
                            }}
                        >
                            {element.node.children && element.node.children.length > 0 && getMenuDom(element.node.children, callback)}
                        </SubMenu>
                    )
                }
                // 绑定嵌套树的子节点
                if (element.children && element.children.length > 0) {
                    return (
                        <SubMenu title={element.node.label}
                            icon={element.node.ico ? <Avatar src={element.node.ico} size={16} style={{ marginRight: 4 }} shape="square" /> : null}
                            key={`${element.node.key || element.node.value}`}
                            onTitleClick={(item) => {
                                // 选中一级菜单
                                if (!currenMenu || item.key !== `${currenMenu?.key}`) {
                                    callback.call(callback, item)
                                }
                                item.domEvent.stopPropagation();
                            }}
                        >
                            {element.children && element.children.length > 0 && getMenuDom(element.children, callback)}
                        </SubMenu>
                    )
                }
                return (<Menu.Item icon={element.node.ico ? <Avatar src={element.node.ico} size={16} shape="square" /> : null}
                    key={`${element.node.key || element.node.value}`}>
                    {element.node.desc !== '0' ? <><span>{element.node.label}</span>
                        {/* <span style={{ position: 'absolute', right: '10', top: '9px', lineHeight: '20px', padding: '2px 3px', color: 'red' }}>
                                [{element.node.desc}]</span> */}
                    </> : element.node.label}</Menu.Item>)
            }
            // 绑定嵌套树的子节点
            if (element.children && element.children.length > 0) {
                return (
                    <SubMenu title={element.desc !== '0' ? <><span>{element.label}</span>
                        {/* <span style={{ position: 'absolute', right: '10', top: '9px', lineHeight: '20px', padding: '2px 3px', color: 'red' }}>
                                [{element.desc}]</span> */}
                    </> : element.label}
                        icon={element.ico ? <Avatar src={element.ico} size={16} style={{ marginRight: 4 }} shape="square" /> : null}
                        key={`${element.key || element.value}`}
                        onTitleClick={(item) => {
                            // 选中一级菜单
                            if (!currenMenu || item.key !== `${currenMenu?.key}`) {
                                callback.call(callback, item)
                            }
                            item.domEvent.stopPropagation();
                        }}
                    >
                        {element.children && element.children.length > 0 && getMenuDom(element.children, callback)}
                    </SubMenu>
                )
            }
            return (<Menu.Item icon={element.ico ? <Avatar src={element.ico} size={16} shape="square" /> : null}
                key={`${element.key || element.value}`}>{element.desc !== '0' ? <><span>{element.label}</span>
                    {/* <span style={{ position: 'absolute', right: '10', top: '9px', lineHeight: '20px', padding: '2px 3px', color: 'red' }}>
                            [{element.desc}]</span> */}
                </> : element.label}</Menu.Item>)
        }))
    }

    // 拿到树形的第一个数据
    interface TreeNode {
        [key: string]: any;
        children?: TreeNode[];
    }
    type TreeData = TreeNode | TreeNode[] | any;
    const handleGetTreeFirst = (node: TreeData): TreeData[] => {
        // 处理数组情况
        if (Array.isArray(node)) {
            return node.length > 0 ? handleGetTreeFirst(node[0]) : [];
        }
        // 处理对象情况
        else if (typeof node === 'object' && node !== null) {
            // 如果没有children或者children为空，返回包含当前节点的数组
            if (!node.children || node.children.length === 0) {
                return [node];
            }
            // 否则递归处理第一个子节点，并将当前节点添加到结果数组前面
            const childResult = handleGetTreeFirst(node.children[0]);
            return [node, ...childResult];
        }
        // 基本数据类型直接返回包含该值的数组
        return [node];
    };

    // 筛选左侧的服务区树
    const handleFilterServiceTree = async (value?: string) => {
        if (value) {
            setShowLeftTreeData(false)
            setTreeView([])
            setTimeout(() => {
                let treeViewData: any = JSON.parse(JSON.stringify(menuData))
                let res = handleSearch(treeViewData, value)
                console.log('resresresres', res);
                let keyList: any = []
                if (res && res.length > 0) {
                    res.forEach((item: any) => {
                        keyList.push(item.key)
                    })
                    setDefaultOpenKeys(keyList)
                    setTreeView(res)
                    setCurrenMenu("")
                    setSelectedId('')
                    setCurrenRegion('')
                    setShowLeftTreeData(true)
                }
            }, 10)
        } else {
            setTreeView(menuData)
        }
        console.log('valuevaluevaluevalue', value);
        console.log('treeView', treeView);
        console.log('menuData', menuData);

    }


    // 搜索方法 
    const handleSearch = (tree: any, searchLabel: string): TreeNode[] => {
        const results: TreeNode[] = [];

        // 处理数组情况（遍历每棵树）
        if (Array.isArray(tree)) {
            for (const node of tree) {
                const nodeResults = handleSearch(node, searchLabel);
                if (nodeResults.length > 0) {
                    results.push(...nodeResults);
                }
            }
            return results;
        }

        // 检查当前节点是否是叶子节点且label匹配
        const isLeaf = !tree.children || tree.children.length === 0;
        if (isLeaf && tree.label.includes(searchLabel)) {
            return [{ ...tree }]; // 返回当前节点的副本（作为一条独立路径）
        }

        // 如果不是叶子节点，递归检查子节点
        if (tree.children && tree.children.length > 0) {
            const matchedChildren: TreeNode[] = [];

            for (const child of tree.children) {
                const childResults = handleSearch(child, searchLabel);
                if (childResults.length > 0) {
                    matchedChildren.push(...childResults);
                }
            }

            // 如果有匹配的子节点，构造当前节点 + 所有匹配的子路径
            if (matchedChildren.length > 0) {
                return [{
                    ...tree,
                    children: matchedChildren, // 保留所有匹配的子节点（不拆分）
                }];
            }
        }

        return results; // 默认返回空数组（无匹配）
    }


    return (
        <div >
            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <ProCard
                    style={{ width: !collapsible ? "300px" : "60px" }}
                    className="pageTable-leftnav"
                    bodyStyle={{ padding: 0, paddingTop: 20, paddingLeft: 20, width: !collapsible ? "300px" : "60px" }}
                    extra={<div className="leftSelectBox">
                        <img className="searchIcon" src={searchIcon} onClick={() => {
                            setShowServiceSearchBox(true)
                        }} />
                        <MenuFoldOutlined onClick={() => {
                            setCollapsible(!collapsible);
                        }} />
                        <div className="fixedBox" style={{ display: showServiceSearchBox ? 'flex' : 'none', width: '275px' }}>
                            <ProForm
                                formRef={searchTreeRef}
                                layout={'horizontal'}
                                submitter={{
                                    render: () => {
                                        return []
                                    }
                                }}
                                isKeyPressSubmit
                                onFinish={(values: any) => {
                                    return handleFilterServiceTree(values?.searchValue || '')
                                }}
                            >
                                <Row>
                                    <Col span={15} className={'noBottom'}>
                                        <ProFormText
                                            name={'searchValue'}
                                            fieldProps={{
                                                placeholder: '请输入服务区名称'
                                            }}
                                            allowClear
                                        />
                                    </Col>
                                    <Col span={2}></Col>
                                    <Col span={5}>
                                        <Button type={'primary'} onClick={() => {
                                            searchTreeRef.current?.submit()
                                        }}>查询</Button>
                                    </Col>
                                </Row>

                            </ProForm>
                            <img style={{ width: '20px', height: '20px', cursor: 'pointer', marginLeft: '5px' }} src={close} onClick={() => {
                                setShowServiceSearchBox(false)
                            }} />
                        </div>
                    </div>}
                    colSpan={!collapsible ? "300px" : "60px"}
                    title={!collapsible ? "请选择服务区" : ""}
                    headerBordered
                    collapsed={collapsible}
                >

                    {showLeftTreeData && <Menu
                        mode="inline"
                        style={{ height: 'calc(100vh - 220px)', overflowY: 'auto', overflowX: 'hidden' }}
                        selectedKeys={selectedId
                            ? [`2-${selectedId}`]
                            : currenMenu
                                ? [`1-${currenMenu}`]
                                : currenRegion
                                    ? [`0-${currenRegion}`]
                                    : []}
                        onSelect={(item, key, keyPath, selectedKeys, domEvent) => {
                            loadSelectedId(item)
                        }}
                        defaultOpenKeys={defaultOpenKeys}
                    >
                        {getMenuDom(treeView, loadSelectedId)}
                    </Menu>}
                    {/* {treeView && treeView.length > 0 ? <Tree
                        treeData={[{
                            label: '全部',
                            value: 0,
                            key: '0-0',
                            children: treeView
                        }]}
                        fieldNames={{
                            title: "label",
                            key: "key"
                        }}
                        blockNode
                        defaultExpandedKeys={['0-0']}
                        onSelect={(selectedKeys: any, info: any) => {
                            setShowRightForm(false)
                            const selectedIds = info.selectedNodes.filter((n: any) => n?.type === 1)
                            console.log('selectedIds', selectedIds);

                            setSelectedId(selectedIds.map(n => n?.value)?.toString() || '')
                            console.log('serverPartRef', serverPartRef.current?.formRef);
                            if (selectedIds && selectedIds.length > 0) {
                                setTimeout(() => {
                                    setShowRightForm(true)
                                }, 1000)
                            } else {
                                setTimeout(() => {
                                    setShowRightForm(true)
                                }, 1)
                                serverPartRef.current?.formRef.current?.setFieldsValue({})
                            }

                        }}
                    /> : ''} */}
                </ProCard>
                <div style={{
                    width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
                    height: "calc(100vh - 170px)",
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0,
                    overflowY: "auto"
                }}>
                    <div style={{ width: '100%', padding: '12px 18px 0 0', height: 'calc(100% - 60px)', overflowY: 'auto', boxSizing: "border-box" }}>
                        {
                            showRightForm ?
                                <ServerpartInfo pageType={2} onRef={serverPartRef} currentRow={{ SERVERPART_ID: currenMenu ? currenMenu : '' }} onShow={showRightForm} /> :
                                <LoadingBox />
                        }
                    </div>
                    <div style={{ height: '60px', width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center', boxSizing: "border-box", padding: "0 16px" }}>
                        {/* 上传设施图片 */}
                        {/* 点击的按钮类型  1 服务区图片上传  2 母婴室图片上传  3  司机之家图片上传  4  住宿客房图片上传  5 便利店图片上传 */}
                        {
                            currenMenu ? <div>
                                <Button type={'primary'} style={{ marginRight: '8px' }} onClick={() => {
                                    setShowType(0)
                                    setShowUploadImgModal(true)
                                    handleSetlogSave(`点击服务区设施图片上传`)
                                }}>服务区设施图片上传</Button>

                                {/* <Button type={'primary'} style={{ marginRight: '8px' }} onClick={() => {
                                    setShowType(1)
                                    setShowUploadImgModal(true)
                                }}>服务区图片上传</Button>

                                <Button type={'primary'} style={{ marginRight: '8px' }} onClick={() => {
                                    setShowType(2)
                                    setShowUploadImgModal(true)
                                }}>母婴室图片上传</Button>

                                <Button type={'primary'} style={{ marginRight: '8px' }} onClick={() => {
                                    setShowType(3)
                                    setShowUploadImgModal(true)
                                }}>司机之家图片上传</Button>

                                <Button type={'primary'} style={{ marginRight: '8px' }} onClick={() => {
                                    setShowType(4)
                                    setShowUploadImgModal(true)
                                }}>住宿客房图片上传</Button>

                                <Button type={'primary'} style={{ marginRight: '8px' }} onClick={() => {
                                    setShowType(5)
                                    setShowUploadImgModal(true)
                                }}>便利店图片上传</Button> */}
                            </div> : ""
                        }
                        {
                            currenMenu ?
                                <Button type="primary" onClick={() => {
                                    handleSubmitForm()
                                }}>保存</Button> : ''
                        }
                    </div>
                </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='scenicSpotConfig'
                        style={{
                            width: '100%',
                            cursor: 'move',
                        }}
                        onMouseOver={() => {
                            if (disabled) {
                                setDraggleDisabled(false)
                            }
                        }}
                        onMouseOut={() => {
                            setDraggleDisabled(true)
                        }}

                        onFocus={() => { }}
                        onBlur={() => { }}
                    >
                        服务区设施图片上传
                        {/* {showType === 1 ? '服务区图片' : showType === 2 ? '母婴室图片' : showType === 3 ? '司机之家图片' : showType === 4 ? '住宿客房图片' : showType === 5 ? '便利店图片' : ''} */}
                    </div>
                }
                destroyOnClose={true}
                width={900}
                bodyStyle={{
                    height: '700px', // 你可以根据需要调整高度
                    overflowY: 'auto',
                }}
                visible={showUploadImgModal}
                confirmLoading={confirmLoading}
                onCancel={() => {
                    setConfirmLoading(false)
                    setShowType(0)
                    setShowUploadImgModal(false);
                    setFileList([])
                    setSelectActiveKey('1')
                }}
                onOk={async () => {
                    console.log('file', fileList);
                    let form: any = await modalRef.current?.getFieldsValue({})
                    console.log('formDataformDataformData', form);
                    // 判断这次上传图片了没
                    if (form.SCENICAREA_Image && form.SCENICAREA_Image.length > 0) {
                        const formData = new FormData();
                        form.SCENICAREA_Image.forEach((file: any) => {
                            formData.append('files[]', file.originFileObj);
                            formData.append('ImageName', typeof file !== 'string' ? file?.name : '');
                        });
                        formData.append('TableId', currenMenu!);
                        formData.append('imageType', selectActiveKey === '1' ? '' : selectActiveKey === '2' ? '1001' : selectActiveKey === '3' ? '1002' : selectActiveKey === '4' ? '2001' : selectActiveKey === '5' ? '2002' : '');
                        formData.append('TableType', selectActiveKey === '1' ? '1123' : selectActiveKey === '2' ? '1131' : selectActiveKey === '3' ? '1131' : selectActiveKey === '4' ? '1131' : selectActiveKey === '5' ? '1131' : '');

                        console.log('formData', formData);
                        let res = await uploadPicture(formData)
                        console.log('resresresres', res);
                        let serverpartObj = session.get('serverpartObj')
                        if (res.Result_Code === 100) {
                            message.success("上传成功！")
                            handleSetlogSave(`更新【${serverpartObj && currenMenu && serverpartObj[currenMenu] ? `${serverpartObj[currenMenu]}基础信息` : ""}${selectActiveKey === '1' ? '服务区图片' : selectActiveKey === '2' ? '母婴室图片' : selectActiveKey === '3' ? '司机之家图片' : selectActiveKey === '4' ? '住宿客房图片' : selectActiveKey === '5' ? '便利店图片' : ''}】`)
                            setConfirmLoading(false)
                            setShowType(0)
                            setShowUploadImgModal(false);
                            setSelectActiveKey('1')
                            setFileList([])
                            setShowRightForm(false)
                            setTimeout(() => {
                                setShowRightForm(true)
                            }, 1000)
                        } else {
                            message.error(res.Result_Desc)
                        }
                    } else {
                        setConfirmLoading(false)
                        setShowType(0)
                        setShowUploadImgModal(false);
                        setFileList([])
                        setSelectActiveKey('1')
                    }
                }}
                modalRender={(modal) => {
                    return <Draggable
                        disabled={disabled}
                        bounds={bounds}
                        onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                        handle='.scenicSpotConfig'
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >

                <Tabs
                    onChange={(e: any) => {
                        setSelectActiveKey(e)
                    }}
                    activeKey={selectActiveKey}
                    items={[
                        {
                            label: `服务区`,
                            key: '1',
                        },
                        {
                            label: `母婴室`,
                            key: '2',
                        },
                        {
                            label: `司机之家`,
                            key: '3',
                        },
                        {
                            label: `住宿客房`,
                            key: '4',
                        },
                        {
                            label: `便利店`,
                            key: '5',
                        },
                    ]}
                />

                <ProForm
                    key={selectActiveKey}
                    layout={'horizontal'}
                    formRef={modalRef}
                    submitter={false}
                    preserve={false}
                    request={async () => {
                        console.log('selectActiveKey', selectActiveKey);

                        let req: any = {
                            TableId: currenMenu,
                            TableName: selectActiveKey === '1' ? 'SERVERPART' : selectActiveKey === '2' ? 'SERVERPARTINFO' : selectActiveKey === '3' ? 'SERVERPARTINFO' : selectActiveKey === '4' ? 'SERVERPARTINFO' : selectActiveKey === '5' ? 'SERVERPARTINFO' : '',
                            TableType: selectActiveKey === '1' ? '1123' : selectActiveKey === '2' ? '1131' : selectActiveKey === '3' ? '1131' : selectActiveKey === '4' ? '1131' : selectActiveKey === '5' ? '1131' : '',
                            ImageType: selectActiveKey === '1' ? '' : selectActiveKey === '2' ? '1001' : selectActiveKey === '3' ? '1002' : selectActiveKey === '4' ? '2001' : selectActiveKey === '5' ? '2002' : '',
                        }
                        const data = await handeGetPictureList(req)
                        console.log('datadatadatadata', data);
                        let list: any = []
                        if (data.List && data.List.length > 0) {
                            data.List.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 {
                            SCENICAREA_Image: list
                        }
                    }}
                >
                    <Row>
                        <Col span={24}>
                            <ProFormUploadButton
                                name="SCENICAREA_Image"
                                label={selectActiveKey === '1' ? '服务区图片' : selectActiveKey === '2' ? '母婴室图片' : selectActiveKey === '3' ? '司机之家图片' : selectActiveKey === '4' ? '住宿客房图片' : selectActiveKey === '5' ? '便利店图片' : ''}
                                listType="picture-card"
                                accept="image/*"
                                fieldProps={{
                                    beforeUpload,
                                    onPreview: handlePreview,
                                    fileList: fileList, // 绑定 fileList
                                    onChange: async (info: any) => {
                                        console.log('info', info);
                                        console.log('fileList', fileList);
                                        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, selectActiveKey === '1' ? 'SERVERPART' : selectActiveKey === '2' ? 'SERVERPARTINFO' : selectActiveKey === '3' ? 'SERVERPARTINFO' : selectActiveKey === '4' ? 'SERVERPARTINFO' : selectActiveKey === '5' ? 'SERVERPARTINFO' : '', selectActiveKey === '1' ? '1123' : selectActiveKey === '2' ? '1131' : selectActiveKey === '3' ? '1131' : selectActiveKey === '4' ? '1131' : selectActiveKey === '5' ? '1131' : '')
                                                        deleteLoading()

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


                </ProForm>
            </Modal>

        </div>
    )
}

export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(serverpartInfo);
