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 { 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 close from '@/assets/ai/close.png'
import { getServerpartTree } from "@/services/options";
import useRequest from "@ahooksjs/use-request";
import './style.less'
import { getMerchantShopTree } from "@/pages/Setting/Users/service";
import session from "@/utils/session";
import { handleGetCOOPSHOP_RULEList, handleGetCOUPONList } from "../../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 // 把万佳商贸隐藏
    selectOnly?: boolean// 传入的时候 仅支持单选
}
const selectCardVouch = ({ setSelectedId, reload, actionRef, currentUser, width, otherFun, setCollapsible, collapsible, haveTest, handleGetLeftTreeData, noWj, selectOnly }: DetailProps) => {
    const searchTreeRef = useRef<FormInstance>();
    // 默认的服务区树
    const [allTreeViews, setAllTreeViews] = useState<any>()
    // 是否要显示全部
    const [isShowAllInTree, setIsShowAllInTree] = useState<boolean>(false)
    // 加载服务区树
    const { loading: treeLoading, data: treeViews } = useRequest(async () => {
        const req: any = {
            SearchParameter: {
                OWNERUNIT_ID: 911,
                COUPON_TYPES: "",
                COUPON_ISVALID: 1
            },
            PageIndex: 1,
            PageSize: 999999
        }

        const data = await handleGetCOUPONList(req)
        console.log('datadatadatadatadatadata', data);


        setAllTreeViews(data)
        setTreeView(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)
            }
        })
        console.log('res', res);
        return res
    }

    // 仅支持单选一个服务区的时候 调用的方法
    const convertTreeForSelectOnly = (treeData: any[]): any[] => {
        return treeData.map(item => {
            const newItem = {
                ...item,
                disabled: item.type !== 1,
            };
            if (item.children) {
                newItem.children = convertTreeForSelectOnly(item.children);
            }
            return newItem;
        });
    };

    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" }}
                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={[{
                        COUPON_NAME: '全部',
                        COUPON_ID: 0,
                        key: '0-0',
                        children: treeView
                    }]}
                    blockNode
                    defaultExpandAll={isShowAllInTree ? false : true}
                    defaultExpandedKeys={isShowAllInTree ? treeShowRow && treeShowRow.length > 0 ? treeShowRow : ['0-0'] : []}
                    onCheck={(checkedKeys: React.Key[] | any, info) => {
                        if (selectOnly) {
                            // 只允许单选且只允许type为1
                            const checked = Array.isArray(checkedKeys.checked) ? checkedKeys.checked : checkedKeys;
                            const node = info.node;
                            if (node.type === 1) {
                                setSelectedId(node.value);
                                if (reload) {
                                    actionRef?.current?.reload();
                                }
                                if (otherFun) {
                                    otherFun(info);
                                }
                            } else {
                                // 取消非type=1的勾选
                                setSelectedId('');
                            }
                        } else {
                            // 多选逻辑
                            const selectedIds = info.checkedNodes.filter((n: any) => n?.COUPON_ID > 0)
                            setSelectedId(selectedIds.map((n: any) => n?.COUPON_ID)?.toString() || '')
                            if (reload) {
                                actionRef?.current?.reload()
                            }
                            if (otherFun) {
                                otherFun(info)
                            }
                        }
                    }}
                    fieldNames={{
                        title: "COUPON_NAME",
                        key: "COUPON_ID"
                    }}
                /> : ''}
            </ProCard>
        </div>
    )
}

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