/*
 * @Author: cclu 1106109051@qq.com
 * @Date: 2024-09-03 11:33:00
 * @LastEditors: cclu 1106109051@qq.com
 * @LastEditTime: 2024-09-14 11:22:07
 * @FilePath: \cloud-platform\src\pages\newDataAnalysis\panoramaConfig\components\relationService.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import { useEffect, useImperativeHandle, useRef, useState } from "react";
import { handleGetServerpartDDL, handleGetSERVERPARTTYPEDetail } from "../service";
import { Button, Col, Row, Tree } from "antd";
import ProForm, { ProFormInstance, ProFormText } from "@ant-design/pro-form";
import { FormInstance } from "rc-field-form";

type DetailProps = {
    onShow: boolean
    currentUser?: any
    currentRow?: any
    onRef?: any
}
const RelationService = ({ onShow, currentUser, currentRow, onRef }: DetailProps) => {
    const formRef = useRef<ProFormInstance>()

    // 服务区列表
    const [serviceList, setServiceList] = useState<any>()
    // 选择的服务区
    const [selectRowKey, setSelectRowKey] = useState<any>()
    // 选择的服务区详情
    const [selectRowKeyDetail, setSelectRowKeyDetail] = useState<any>()
    // 已经关联的服务区列表
    const [alreadyList, setAlreadyList] = useState<any>()
    // 未关联的服务区列表
    const [unrelated, UnrelatedList] = useState<any>()
    // 未关联的服务区列表原始数据
    const [defaultUnRealted, setDefaultUnRealted] = useState<any>()
    // 未关联的树形选择
    const [unSelectRowKey, setUnSelectRowKey] = useState<any>()
    // 未关联的树形选择行详情
    const [unSelectRowKeyDetail, setUnSelectRowKeyDetail] = useState<any>()


    // 拿到全部服务区的数据
    const handleGEetService = async () => {
        const detail = await handleGetSERVERPARTTYPEDetail({ SERVERPARTTYPEId: currentRow?.SERVERPARTTYPE_ID })
        console.log('detail', detail);
        let list: any = []
        if (detail?.RTServerpartList && detail?.RTServerpartList.length > 0) {
            detail?.RTServerpartList.forEach((item: any) => {
                list.push(item.SERVERPART_ID.toString())
            })
            // setSelectRowKey(list)
        }

        const req: any = {
            ProvinceCode: currentUser?.ProvinceCode,
            ServerpartType: 1000
        }
        console.log('select', list);

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

        // 已关联
        let isAssociationList: any = []
        // 未关联
        let unAssociationList: any = []
        if (data && data.length > 0) {
            data.forEach((item: any) => {
                if (item.value !== '424') {
                    if (list.indexOf(item.value) === -1) {
                        unAssociationList.push(item)
                    } else {
                        isAssociationList.push(item)
                    }
                }
            })
        }

        setAlreadyList(isAssociationList)
        UnrelatedList(unAssociationList)
        setDefaultUnRealted(unAssociationList)

        setServiceList(data)
    }

    useEffect(() => {
        if (onShow) {
            handleGEetService()
        }
    }, [onShow])

    // 搜索服务区的方法
    const handleSearchServerPart = () => {
        let res: any = formRef.current?.getFieldsValue()
        console.log('res', res);
        console.log('defaultUnRealted', defaultUnRealted);
        if (res?.serverPartName) {
            let list: any = []
            if (defaultUnRealted && defaultUnRealted.length > 0) {
                defaultUnRealted.forEach((item: any) => {
                    if (item.label.indexOf(res?.serverPartName) !== -1) {
                        list.push(item)
                    }

                })
            }
            UnrelatedList(list)
        } else {
            UnrelatedList(defaultUnRealted)
        }


    }

    // 添加服务区
    const handleAddServerPart = () => {
        if (unSelectRowKeyDetail && unSelectRowKeyDetail.length > 0) {
            // 左侧移动之后的服务区列表数据
            let newList: any = []
            defaultUnRealted.forEach((item: any) => {
                if (unSelectRowKey.indexOf(item.value) === -1) {
                    newList.push(item)
                }
            })
            UnrelatedList(newList)
            setDefaultUnRealted(newList)

            // 右侧移动之后的表格数据
            if (alreadyList && alreadyList.length > 0) {
                let rightList: any = JSON.parse(JSON.stringify(alreadyList))
                unSelectRowKeyDetail.forEach((item: any) => {
                    rightList.push(item)
                })
                setAlreadyList(rightList)
            } else {
                let list: any = []
                unSelectRowKeyDetail.forEach((item: any) => {
                    list.push(item)
                })
                setAlreadyList(list)
            }
        }
        setUnSelectRowKey([])
        setUnSelectRowKeyDetail([])
        formRef.current?.setFieldsValue({ serverPartName: '' })
    }

    // 移除服务区
    const handleRemoveServerPart = () => {
        if (selectRowKeyDetail && selectRowKeyDetail.length > 0) {
            // 右侧移除之后的服务区列表数据
            let newList: any = []
            alreadyList.forEach((item: any) => {
                if (selectRowKey.indexOf(item.value) === -1) {
                    newList.push(item)
                }
            })
            setAlreadyList(newList)
            // 左侧更新的数据的表格数据
            if (unrelated && unrelated.length > 0) {
                let rightList: any = JSON.parse(JSON.stringify(unrelated))
                selectRowKeyDetail.forEach((item: any) => {
                    rightList.push(item)
                })
                UnrelatedList(rightList)
                setDefaultUnRealted(rightList)
            } else {
                let list: any = []
                selectRowKeyDetail.forEach((item: any) => {
                    list.push(item)
                })
                UnrelatedList(list)
                setDefaultUnRealted(list)
            }
        }
        setSelectRowKey([])
        setSelectRowKeyDetail([])
    }


    useImperativeHandle(onRef, () => ({
        selectRowKey,
        alreadyList
    }));



    return (
        <div>
            <div style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>
                <div style={{ width: 'calc(50% - 8px)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <span>未关联服务区</span>
                    <Button onClick={() => {
                        handleAddServerPart()
                    }}>{"选择>>"}</Button>
                </div>
                <div style={{ width: 'calc(50% - 8px)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <Button onClick={() => {
                        handleRemoveServerPart()
                    }}>{"<<移除"}</Button>
                    <span>已关联服务区</span>
                </div>
            </div>

            <div style={{ width: '100%', height: '500px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ width: 'calc(50% - 8px)', height: '500px' }}>
                    <div style={{ height: '95px' }}>
                        <ProForm
                            formRef={formRef}
                            submitter={false}
                            isKeyPressSubmit
                            onFinish={(values: any) => {
                                handleSearchServerPart()
                            }}
                        >
                            <Row>
                                <Col span={14}>
                                    <ProFormText
                                        label={"服务区名称"}
                                        name={"serverPartName"}
                                    />
                                </Col>
                                <Col span={1}></Col>
                                <Col span={8} style={{ display: 'flex', alignItems: 'center' }}>
                                    <Button type="primary" onClick={() => {
                                        formRef.current?.submit()
                                    }}>查询</Button>
                                </Col>
                            </Row>

                        </ProForm>
                    </div>
                    <div style={{ height: 'calc(100% - 100px)', overflowY: 'auto' }}>
                        <Tree
                            checkable
                            treeData={unrelated}
                            fieldNames={{
                                title: 'label',
                                key: 'value'
                            }}
                            multiple
                            checkedKeys={unSelectRowKey}
                            onCheck={(checkedKeys: React.Key[] | any, info) => {
                                console.log('checkedKeys', checkedKeys);
                                console.log('info', info);
                                setUnSelectRowKey(checkedKeys)
                                setUnSelectRowKeyDetail(info?.checkedNodes)
                            }}
                        />
                    </div>


                </div>
                <div style={{ width: 'calc(50% - 8px)', height: '500px', overflowY: 'auto' }}>
                    <Tree
                        checkable
                        treeData={alreadyList}
                        fieldNames={{
                            title: 'label',
                            key: 'value'
                        }}
                        multiple
                        checkedKeys={selectRowKey}
                        onCheck={(checkedKeys: React.Key[] | any, info) => {
                            console.log('checkedKeys', checkedKeys);
                            console.log('info', info);
                            setSelectRowKey(checkedKeys)
                            setSelectRowKeyDetail(info?.checkedNodes)
                        }}
                    />
                </div>
            </div>






            {/* {
                serviceList && serviceList.length > 0 ?
                    <Tree
                        checkable
                        treeData={serviceList}
                        fieldNames={{
                            title: 'label',
                            key: 'value'
                        }}
                        multiple
                        checkedKeys={selectRowKey}
                        onCheck={(checkedKeys: React.Key[] | any, info) => {
                            console.log('checkedKeys', checkedKeys);
                            console.log('info', info);
                            setSelectRowKey(checkedKeys)
                        }}
                    /> : ''
            } */}
        </div>
    )
}

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