import { connect } from "umi";
// import type { ConnectState } from "@/models/connect";
import ProCard from "@ant-design/pro-card";
import searchIcon from '@/assets/ai/searchIcon.png'
import close from '@/assets/ai/close.png'
import { useRef, useState } from "react";
import { MenuFoldOutlined } from "@ant-design/icons";
import ProForm, { ProFormText } from "@ant-design/pro-form";
import { Button, Col, FormInstance, Row, Tree } from "antd";
// import { getServerpartTree } from "@/services/options";
import useRequest from "@ahooksjs/use-request";
import { getMerchantShopTree, getServerpartTree } from "./service";
import { handleGetPassportInfoById } from "@/pages/DigitalElectronics/service";
import './style.less'
// import { getMerchantShopTree } from "@/pages/Setting/Users/service";


type DetailProps = {
    setSelectedId: any; // 把选择的服务区 可以带给外层
    reload?: boolean; // 选择服务区 是否可以刷新组件之外的内容
    actionRef?: any; // 和reload配合使用 确认要刷新的内容
    currentUser: any; // 当前用户的信息
    width?: number; // 组件的宽度
    otherFun?: any; // 点击之后要进行的其他操作 多个操作可以写在一个方法里面传进来
    setCollapsible: any; // 是否收缩组件
    collapsible: boolean; // 收缩组件的判断依据
    haveTest?: boolean;// 是否有测试服务区
    handleGetLeftTreeData?: any // 拿到树数据的方法 必须要有输出值的
    noWj?: any // 把万佳商贸隐藏
    serverPartType?: any // 查询的服务区的类型
    ServerpartSiteType?: any
}
const LeftSelectTree = ({ setSelectedId, reload, actionRef, currentUser, width, otherFun, setCollapsible, collapsible, haveTest, handleGetLeftTreeData, noWj, serverPartType, ServerpartSiteType }: DetailProps) => {
    const searchTreeRef = useRef<FormInstance>();
    // 默认的服务区树
    const [allTreeViews, setAllTreeViews] = useState<any>()
    // 是否要显示全部
    const [isShowAllInTree, setIsShowAllInTree] = useState<boolean>(false)
    // 加载服务区树
    const { loading: treeLoading, data: treeViews } = useRequest(async () => {
        const search = window.location.search;
        const addressParams = Object.fromEntries(new URLSearchParams(search).entries());
        const req: any = {
            UserIdEncrypted: addressParams.UserIdEncrypted
        }
        const userInfo = await handleGetPassportInfoById(req)

        let data: any = []
        if (userInfo?.UserPattern === 2000) {
            data = await getMerchantShopTree({ BusinessManId: userInfo?.BusinessManID, ShowShop: false });
        } else {
            data = await getServerpartTree(userInfo?.ProvinceCode, userInfo?.CityAuthority, true, true, true, false, serverPartType ? serverPartType : '1000,4000', ServerpartSiteType)
        }

        // 判断是否有多个片区的权限
        if (data && data.length > 1) {
            // 那么就显示全部
            setIsShowAllInTree(true)
        }

        let list: any = []

        data.forEach((item: any) => {
            // 判断  item这一层已经是片区了 如果item.children 只有一个的话 那就说明 也只有一个服务区 那么就可以判断不显示全部和片区的树形选择层了
            if (item.children && item.children.length === 1) {
                list.push(item.children[0])
            } else {
                if (haveTest) {
                    if (item.value !== 424) {
                        list.push(item)
                    }
                } else {
                    if (item.value !== 424 && item.value !== 586) {
                        list.push(item)
                    }
                }
            }
        })

        if (noWj) {
            list = handleFilterList(list, 89)
        }
        if (handleGetLeftTreeData) {
            let newData: any = await handleGetLeftTreeData()
            setTreeView(newData)
        } else {
            setTreeView(list)
        }

        setAllTreeViews(list)
        return data
    })
    // 显示服务区树搜索框
    const [showServiceSearchBox, setShowServiceSearchBox] = useState<boolean>(false)
    // 实际显示在左侧的服务区树
    const [treeView, setTreeView] = useState<any>()
    // 树要展开的行
    const [treeShowRow, setTreeShowRow] = useState<any>()
    // 筛选左侧的服务区树
    const handleFilterServiceTree = async (value?: string) => {
        const resList: any = JSON.parse(JSON.stringify(allTreeViews))
        setSelectedId('')
        if (resList && resList.length > 0 && value) {
            setTreeView([])
            const list: any = []
            resList.forEach((item: any) => {
                if (item.label.indexOf(value) !== -1) {
                    list.push(item)
                } else {
                    if (item.children && item.children.length > 0) {
                        const childrenList: any = []
                        item.children.forEach((subItem: any) => {
                            if (subItem.label.indexOf(value) !== -1) {
                                childrenList.push(subItem)
                            }
                        })
                        item.children = childrenList
                        if (childrenList && childrenList.length > 0) {
                            list.push(item)
                        }
                    }
                }
            })
            if (list && list.length > 0) {
                const keyList: any = ['0-0']
                list.forEach((item: any) => {
                    keyList.push(item.key)
                })
                setTreeShowRow(keyList)
            }
            setTimeout(() => {
                setTreeView(list)
            }, 100)
        } else {
            setTreeView([])
            setTreeShowRow([])
            setTreeView(allTreeViews)
        }
    }
    // 根据传入的服务区id筛选剔除掉这个服务区
    const handleFilterList = (list: any, id: any) => {
        let res: any = []
        list.forEach((item: any) => {
            if (item.value === id) {

            } else {
                res.push(item)
            }
        })
        return res
    }


    return (
        <div>
            <ProCard
                style={{ width: !collapsible ? width ? `${width}px` : "300px" : "60px" }}
                className="pageTable-leftnav"
                bodyStyle={{ padding: 0, paddingTop: 20, paddingLeft: 20, width: !collapsible ? width ? `${width}px` : "300px" : "60px", overflowY: 'auto' }}
                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: width ? `${width}px` : '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}
            >
                {treeView && treeView.length > 0 ? <Tree
                    checkable
                    treeData={isShowAllInTree ? [{
                        label: '全部',
                        value: 0,
                        key: '0-0',
                        children: treeView
                    }] : treeView}
                    fieldNames={{
                        title: "label",
                        key: "key"
                    }}
                    blockNode
                    defaultExpandAll={isShowAllInTree ? false : true}
                    defaultExpandedKeys={isShowAllInTree ? treeShowRow && treeShowRow.length > 0 ? treeShowRow : ['0-0'] : []}
                    onCheck={(checkedKeys: React.Key[] | any, info) => {
                        const selectedIds = info.checkedNodes.filter((n: any) => n?.type === 1)
                        setSelectedId(selectedIds.map(n => n?.value)?.toString() || '')
                        if (reload) {
                            actionRef?.current?.reload()
                        }
                        if (otherFun) {
                            otherFun(info)
                        }
                    }}
                /> : ''}
            </ProCard>
        </div>
    )
}

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