import React, { useEffect, useState } from 'react'
import {
    // Tree,
    Table,
    Space,
    message,
    Modal,
    Input,
    notification,
    Tooltip,
    Card,
    Button,
    Spin,
    Dropdown,
    Menu,
    Row,
    Col,
    Empty,
    Pagination,
    Checkbox
} from 'antd';

import classnames from 'classnames'
import {
    UserOutlined,
    PlusSquareOutlined,
    UsergroupAddOutlined,
    EditOutlined,
    FormOutlined,
    DeleteOutlined,
    DoubleLeftOutlined,
    DoubleRightOutlined,
    DownOutlined,
    PlusOutlined,
    ApartmentOutlined
} from '@ant-design/icons';

import PageContainer from '@/components/BasePageContainer';
import Tree from '@/components/ExpendableTree';
import voca from 'voca';
import zhCN from 'antd/es/locale/zh_CN';
import qs from 'qs';
import styles from './siteManage.less';

import {
    getWebModuleTree,
    chooseUserToStation,
    getAllGroup,
    getUserByStation,
    getStationUserList,
    groupUserPagingList,
    addChildSiteNode,
    getSiteTree,
    getStationUsers
} from '@/services/userCenter/siteManage/api';
import lodash, { clone } from 'lodash';
import AddModal from '../siteManage/AddModal';
import DelModal from '../siteManage/DelModal';
import EditModal from '../siteManage/EditModal';
import AddChildModal from '../siteManage/AddChildModal';
const { Search } = Input;
const placeholder = '请输入机构名称';
const SiteManageV2 = () => {



    const [showSearchStyle, setShowSearchStyle] = useState(false); // 是否显示模糊查询样式
    const [treeVisible, setTreeVisible] = useState(true); // 树是否可见
    const [treeData, setTreeData] = useState([]); // 用户站点树
    const [treeDataCopy, setTreeDataCopy] = useState([]); // 机构树数据备份，用于更改机构
    const [treeState, setTreeState] = useState(true); // 树第一次加载
    const [treeLoading, setTreeLoading] = useState(false);
    const [currentStation, setCurrentStation] = useState(''); // 当前选中站点
    const [currentStationMsg, setCurrentStationMsg] = useState({}); //当前编辑节点信息
    const [currentStationOperate, setCurrentStationOperate] = useState(false)
    const [flag, setFlag] = useState(1);//操作标致触发界面刷新
    const [dataList, setdataList] = useState([]);//当前站点对应的分页用户列表
    const [visibleParams, setvisibleParams] = useState({
        modalVisible: false, // 新增弹窗
        delVisible: false, // 删除弹窗
        editVisible: false, // 修改弹窗
        spinLoading: false, // 加载弹窗
        btnLoading: false,
        loading: false,
        checkBoxLoading: false,
    });
    const [total, setTotal] = useState(0); // 分页总数
    const [page, setPage] = useState({ pageNum: 1, pageSize: 10 });
    const [selectList, setSelectList] = useState([]); // 选择列表数据
    const [updatePageUser, setUpdatePageUser] = useState(1);//
    const [updateCheck, setUpdateCheck] = useState(1);
    const [name, setName] = useState('');
    const [des, setDes] = useState('')
    const [data, setData] = useState('')
    const [ch, setCh] = useState('')

    let a = []

    // 渲染机构树
    const mapTree = org => {
        const haveChildren = Array.isArray(org.children) && org.children.length > 0;
        return {
            title: (
                <div className={styles.title}>
                    <div className={styles.titleText}>{org.text}</div>
                    <div className={styles.tip}>
                        <Tooltip title="添加下级站点" className={styles.fs}>
                            <PlusSquareOutlined style={{ fontSize: '16px', color: '#1890FF' }} onClick={e => addSite(e, org)} />
                        </Tooltip>
                        <Tooltip title="编辑当前站点" className={styles.fs}>
                            <FormOutlined style={{ fontSize: '16px', color: '#1890FF' }} onClick={e => editorSite(e, org)} />
                        </Tooltip>
                        <Tooltip title="删除当前站点" className={styles.fs}>
                            <DeleteOutlined style={{ fontSize: '16px', color: '#1890FF' }} onClick={e => delSite(e, org)} />
                        </Tooltip>
                    </div>
                </div>
            ),
            key: org.id,
            // icon: <UserOutlined style={{ display: 'inline' }} />,
            // 判断它是否存在子集，若果存在就进行再次进行遍历操作，知道不存在子集便对其他的元素进行操作
            children: haveChildren ? org.children.map(i => mapTree(i)) : [],
        };
    };
    //添加下级站点
    const addSite = (e, recode) => {
        e.stopPropagation();
        setCurrentStation(recode.id);
        handleShowModal('addChildVisible', true);
    }
    //删除当前站点
    const delSite = (e, recode) => {
        e.stopPropagation();
        setCurrentStation(recode.id);
        handleShowModal('delVisible', true);

    }
    //编辑当前站点
    const editorSite = (e, recode) => {
        e.stopPropagation();
        // console.log(recode);
        // 保存编辑回显信息
        setCurrentStationMsg(recode);
        // setCurrentStation(recode.id);
        handleShowModal('editVisible', true);
    }
    // 重新渲染树
    const updateTrees = () => {
        setTreeLoading(true);
        getSiteTree({ selectNode: -1 }).then(
            res => {
                if (res.data.length > 0) {
                    setTreeLoading(false);
                    setTreeData(res.data);
                    setTreeDataCopy(res.data);
                    // 第一次加载，默认选择第一个组织
                    if (treeState) {
                        onSelect([res.data[0].id], false);//待会儿要改
                        setTreeState(false);
                    }
                } else {
                    setTreeLoading(false);
                    notification.error({
                        message: '获取失败',
                        description: res.message,
                    });
                }
            }
        )

    };

    // 获取用户机构树
    useEffect(() => {
        updateTrees();
    }, [flag]);

    useEffect(() => {
        getValue()
    }, [])

    //切换站点，点击分页按钮，提交 
    useEffect(() => {
        if (!currentStation) return;
        getList();
        setShowSearchStyle(false);
    }, [updatePageUser, name]);
    //切换站点，提交时触发已勾选列表更新
    useEffect(() => {
        if (!currentStation) return;
        //getAllcheckList();
        getAllCheckListNew()
    }, [currentStation, updateCheck]);

    //获取当前站点可编辑用户(已勾选和未勾选)分页展示
    const getList = () => {
        let params = {
            id: +currentStation || '',
            PageIndex: +page.pageNum,
            PageSize: +page.pageSize,
        };
        if (name) params = { ...params, name };
        groupUserPagingList(params).then(res => {
            if (res.code === 0 && res.data) {
                setShowSearchStyle(true);
                let { list } = res.data;
                // 还原选择的数据
                if (selectList.length > 0) {
                    selectList.forEach(item => {
                        list.forEach((value, index) => {
                            if (item.GroupId === value.GroupId) {
                                list[index].Users.forEach((user, userIndex) => {
                                    if (user.userID === item.userID) {
                                        list[index].Users[userIndex].isChecked = true;
                                    }
                                });
                                let checkedLen = list[index].Users.filter(v => v.isChecked)
                                    .length;
                                if (checkedLen === list[index].Users.length) {
                                    list[index].isChecked = true;
                                }
                            }
                        });
                    });
                }
                handleShowModal('loading', false);
                setdataList(lodash.cloneDeep(list));
                setTotal(res.data.TotalCount);
            } else {
                handleShowModal('loading', false);
                setdataList(lodash.cloneDeep([]));
            }
        });
    }
    //获取当前站点所有已经勾选的用户
    const getAllcheckList = async () => {
        let res = await getUserByStation({
            stationID: currentStation,
            _version: 9999,
            _dc: new Date().getTime(),
        });
        if (res.length > 0) {
            // 还原从后台返回的数据 选中的列表
            let list = [];
            // console.log(res);
            res.forEach(item => {
                if (item.userList.length > 0) {
                    item.userList.forEach(value => {
                        // console.log(value);
                        if (
                            value.isChecked &&
                            list.findIndex(
                                v => +v.GroupId === +item.OUID && +v.userID === +value.userID,
                            ) === -1
                        ) {
                            list.push({
                                GroupId: +item.OUID,
                                GroupName: item.OUName,
                                userName: value.userName,
                                userID: value.userID,
                            });
                        }
                    });
                }
            });
            setSelectList(lodash.cloneDeep(list));
            setUpdatePageUser(updatePageUser + 1)
        }
    }

    //获取当前站点所有已经勾选的用户新接口
    const getAllCheckListNew = () => {
        getStationUsers({
            stationId: currentStation
        }).then(
            res => {
                let list = []
                if (res.data.length > 0) {

                    res.data.map((item, index) => {
                        list.push({
                            GroupId: +item.OUID,
                            GroupName: item.OUName,
                            userName: item.userName,
                            userID: item.userID,
                        });
                    })

                }
                setSelectList(lodash.cloneDeep(list));
                setUpdatePageUser(updatePageUser + 1)
            }
        )
    }
    //选中某个站点
    const onSelect = (props, e) => {
        console.log('props[0]', props[0]);
        setCh(props[0])
        if (!props[0]) {

            setCurrentStation(currentStation)
        } else {
            setCurrentStation(props[0]);
        }
        setPage({ pageNum: 1, pageSize: 10 });
        console.log(data)
        data.map((item, index) => {
            if (item.id == props[0]) {
                console.log(item.id)
                console.log(item.describe)
                setDes(item.describe)
            }
        })
    }

    const getValue = () => {
        getSiteTree({ selectNode: -1 }).then(
            res => {
                console.log(res.data)
                getData1(res.data)
            }
        )
    }
    const getData1 = e => {
        console.log(e)
        e.map((i, j) => {
            a.push(i)
            if (i.children.length > 0) {
                getData1(i.children)
            }
        })
        console.log(a)
        setData(a)

    }

    // 弹出模态框
    const handleShowModal = (key, value) => {
        setvisibleParams({ ...visibleParams, [key]: value });
    };
    // 获取搜索框的值
    const handleSearch = value => {
        setName(value);
        getList(value);
    };
    const confirmModal = e => {
        handleShowModal('modalVisible', false);
        setFlag(flag + 1);
    };
    const delModal = () => {
        handleShowModal('delVisible', false);
        setFlag(flag + 1);
    };
    const editModal = () => {
        handleShowModal('editVisible', false);
        setFlag(flag + 1);
    };
    const addChildModal = () => {
        handleShowModal('addChildVisible', false);
        setFlag(flag + 1);
    }

    const handleChangeCollpase = (groupId, isShow) => {
        let index = dataList.findIndex(item => item.GroupId === groupId);
        if (dataList[index].children && dataList[index].children.length > 0) {
            setdataList(lodash.cloneDeep(dataList));
            return;
        }
        handleShowModal('loading', true);
        getStationUserList({ stationID: currentStation, groupId }).then(
            res => {
                if (res.code === 0 && res.data) {
                    handleShowModal('loading', false);
                    dataList[index].children = res.data;
                    setdataList(lodash.cloneDeep(dataList));
                }
            },
        );
    };
    // 每组全选全不选
    const handleChangeAll = (e, index) => {
        dataList[index].isChecked = e.target.checked;
        dataList[index].Users.forEach(item => {
            item.isChecked = e.target.checked;
            let delIndex = selectList.findIndex(
                v => v.GroupId === dataList[index].GroupId && v.userID === item.userID,
            );
            if (e.target.checked) {
                if (delIndex === -1) {
                    selectList.push({
                        GroupId: dataList[index].GroupId,
                        GroupName: dataList[index].GroupName,
                        userName: item.userName,
                        userID: item.userID,
                    });
                }
            }
            if (!e.target.checked) {
                selectList.splice(delIndex, 1);
            }
        });

        setSelectList(lodash.cloneDeep(selectList));
        setdataList(lodash.cloneDeep(dataList));
    };
    // 单个选择checkbox
    const handleChangeSignel = (e, index, vIndex) => {
        dataList[index].Users[vIndex].isChecked = e.target.checked;
        let checked = isAllChecked(index);
        let hasIndex = selectList.findIndex(
            item =>
                item.userID === dataList[index].Users[vIndex].userID &&
                item.GroupId === dataList[index].GroupId,
        );
        dataList[index].isChecked = checked;
        if (e.target.checked && hasIndex === -1) {
            selectList.push({
                GroupId: dataList[index].GroupId,
                GroupName: dataList[index].GroupName,
                userName: dataList[index].Users[vIndex].userName,
                userID: dataList[index].Users[vIndex].userID,
            });
        } else {
            selectList.splice(hasIndex, 1);
        }
        setdataList(lodash.cloneDeep(dataList));
    };
    const isAllChecked = index =>
        dataList[index].Users.filter(item => item.isChecked).length ===
        dataList[index].Users.length;
    // 删除已选列表
    const handleDel = index => {
        let { GroupId, userID } = selectList[index];
        let outerIndex = dataList.findIndex(item => item.GroupId === GroupId);
        if (outerIndex > -1) {
            let innerIndex = dataList[outerIndex].Users.findIndex(
                item => item.userID === userID,
            );
            dataList[outerIndex].Users[innerIndex].isChecked = false;
            dataList[outerIndex].isChecked = isAllChecked(outerIndex);
        }
        selectList.splice(index, 1);
        setSelectList(lodash.cloneDeep(selectList));
        setdataList(lodash.cloneDeep(dataList));
    };
    // 提交
    const handleCommitBtn = () => {
        handleShowModal('btnLoading', true);
        let result = [];
        let obj = {};
        selectList.forEach(item => {
            if (obj[item.GroupId]) {
                obj[item.GroupId].push(item.userID);
            } else {
                obj[item.GroupId] = [item.userID];
            }
        });
        // dataList.forEach(item => {
        //     if (obj[item.GroupId] && item.Users.length === obj[item.GroupId].length) {
        //         obj[item.GroupId].push(item.GroupId);
        //     }
        // });
        result = Object.values(obj);
        // 数据处理成后台需要的格式
        if (result.length === 0)
            return notification.warning({
                message: '提示',
                description: '请至少选择选择一个用户！',
            });
        chooseUserToStation(
            {
                userList: String(result.flat()),
                stationID: currentStation,
            }
        )
            .then(res => {
                handleShowModal('btnLoading', false);

                if (res.code === 0) {
                    setSelectList([]);
                    setUpdateCheck(updateCheck + 1);
                    notification.success({
                        message: '提示',
                        duration: 3,
                        description: '设置成功',
                    });
                } else {
                    notification.error({
                        message: '提示',
                        duration: 15,
                        description: res.message,
                    });
                }
            })
            .catch(err => {
                handleShowModal('btnLoading', false);
                console.log(err);
            });
    };
    // 分页
    const handleChangePage = (pageNum, pageSize) => {
        setPage({ pageNum, pageSize });
        setUpdatePageUser(updatePageUser + 1);
    };
    /** ***操作按钮**** */
    // 机构操作
    const addTopStation = () => {
        handleShowModal('modalVisible', true);
    }

    // 模糊查询匹配的样式
    const searchStyle = val => {
        console.log(showSearchStyle)
        console.log(name)
        let n;
        if (showSearchStyle) {
            n = val.replace(
                new RegExp(name, 'g'),
                `<span style='color:red'>${name}</span>`,
            );
        } else {
            n = val;
        }
        console.log(n)
        return <div dangerouslySetInnerHTML={{ __html: n }} />;
    };

    const Panels = React.memo(props => {
        let { index, GroupId, GroupName, Users, isChecked, isShow, color } = props;
        return (
            <div className={styles.sitePanel} key={GroupId} id={`siteId${GroupId}`}>
    
                {/* onClick={() => props.handleChangeCollpase(GroupId, isShow)} */}
                <div className={styles.sitePanelHead}>
                    {/* {isShow ? (
                <UpOutlined className={styles.siteIcon} />
              ) : (
                <DownOutlined className={styles.siteIcon} />
              )} */}
                    {/* <UpOutlined className={styles.siteIcon} /> */}
                    <ApartmentOutlined className={styles.siteIcon} />
                    {searchStyle(GroupName)}
                    <Checkbox
                        key="0"
                        className={styles.siteListTitle}
                        checked={isChecked}
                        onClick={e => props.handleChangeAll(e, index)}
                    >
                        全选
                    </Checkbox>
                </div>
                <div className={styles.sitePanelCon}>
    
                    {Users.length > 0 &&
                        Users.map((v, vIndex) => (
                            <CheckBoxRow
                                {...v}
                                index={index}
                                vIndex={vIndex}
                                key={v.userID}
                                handleChangeSignel={props.handleChangeSignel}
                            />
                        ))}
                </div>
            </div>
        );
    });

    return (
        <PageContainer className={styles.siteManageContainer}>
            <div className={styles.contentContainer}>
                <Card
                    className={classnames({
                        [styles.orgContainer]: true,
                        [styles.orgContainerHide]: !treeVisible,
                    })}
                >
                    <span style={{ margin: '0 180px  0 10px' }}>站点列表</span>
                    <Tooltip title="添加顶级站点">
                        <PlusOutlined
                            onClick={() => addTopStation()}
                            style={{
                                color: '#1890FF',
                                fontSize: '18px',
                                verticalAlign: '0.04em',
                            }}
                        />
                    </Tooltip>
                    {treeData.length > 0 && (
                        <Tree
                            showIcon="true"
                            showLine={{ showLeafIcon: false }}
                            blockNode
                            autoExpandParent
                            selectedKeys={[currentStation]}
                            onSelect={onSelect}
                            height={treeData.length && treeData.length > 30 ? treeData.length * 14 : 780}
                            treeData={treeData.map(t => mapTree(t))}
                        />
                    )}
                    <div className={styles.switcher}>
                        {treeVisible && (
                            <Tooltip title="隐藏机构列表">
                                <DoubleLeftOutlined onClick={() => setTreeVisible(false)} />
                            </Tooltip>
                        )}
                        {!treeVisible && (
                            <Tooltip title="显示机构列表">
                                <DoubleRightOutlined onClick={() => setTreeVisible(true)} />
                            </Tooltip>
                        )}
                    </div>
                </Card>
                {/* 右侧用户表 */}
                <div
                    className={classnames({
                        [styles.userContainer]: true,
                        [styles.userContainerHide]: !treeVisible,
                    })}
                >
                    <AddModal
                        visible={visibleParams.modalVisible}
                        onCancel={() => handleShowModal('modalVisible', false)}
                        confirmModal={confirmModal}
                    />
                    <AddChildModal
                        visible={visibleParams.addChildVisible}
                        pid={currentStation}
                        onCancel={() => handleShowModal('addChildVisible', false)}
                        confirmModal={addChildModal}
                    />
                    <DelModal
                        visible={visibleParams.delVisible}
                        stationId={currentStation}
                        onCancel={() => handleShowModal('delVisible', false)}
                        confirmModal={delModal}
                    />
                    <EditModal
                        visible={visibleParams.editVisible}
                        stationObj={currentStationMsg}
                        des={des}
                        onCancel={() => handleShowModal('editVisible', false)}
                        confirmModal={editModal}
                    />
                    <div
                        className={classnames({
                            [styles.boxR]: true,
                            [styles.boxH]: treeVisible,
                        })}
                    >
                        <Card
                            className={classnames({
                                [styles.cardBoxTop]: true,
                                [styles.boxH]: treeVisible,
                            })}
                        >
                            <Row align="middle">
                                <Col span={1}>搜索</Col>
                                <Col span={8}>
                                    <Search
                                        allowClear
                                        placeholder={placeholder}
                                        onSearch={handleSearch}
                                        // onChange={handleChange}
                                        enterButton
                                    />
                                </Col>
                                <Col span={3} />

                            </Row>
                        </Card>
                        <div style={{ background: '#fff' }}>
                            <Card
                                className={classnames({
                                    [styles.boxH]: treeVisible,
                                    [styles.cardBoxR]: true,
                                })}
                            >
                                {/* <Checkbox className={styles.siteAll}>全选/反选</Checkbox> */}

                                {dataList.length > 0 && !visibleParams.loading ? (
                                    <>

                                        <p className={styles.siteline}>已选择列表：</p>
                                        <div className={styles.siteSelectList}>
                                            <ul className={styles.siteSelectUl}>
                                                {selectList.map((item, index) => (
                                                    <li
                                                        key={`${item.userName}${item.GroupId}${index}`}
                                                        onClick={() => handleDel(index)}
                                                    >
                                                        {`${item.userName}(${item.GroupName})`}
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>
                                    </>
                                ) : (
                                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                                )}
                                <Spin spinning={visibleParams.loading} >
                                    {dataList.map((item, index) => (
                                        <Panels
                                            {...item}
                                            index={index}
                                            key={item.GroupId}
                                            handleChangeCollpase={handleChangeCollpase}
                                            handleChangeAll={handleChangeAll}
                                            handleChangeSignel={handleChangeSignel}
                                        />
                                    ))}
                                </Spin>
                            </Card>
                            {dataList.length > 0 && !visibleParams.loading ? (
                                <div style={{ textAlign: 'right' }}>
                                    <Pagination
                                        size="small"
                                        total={total}
                                        current={page.pageNum}
                                        defaultPageSize="10"
                                        onChange={handleChangePage}
                                        pageSizeOptions={['10']}
                                    />
                                </div>) : ''
                            }
                            <div className={styles.siteBtn}>
                                <Button
                                    type="primary"
                                    className={styles.siteCommit}
                                    onClick={handleCommitBtn}
                                >
                                    提交
                                </Button>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </PageContainer>
    )
}




const CheckBoxRow = React.memo(props => {
    let { vIndex, index, isChecked, userName } = props;
    return (
        <Checkbox
            className={styles.siteList}
            checked={isChecked}
            onClick={e => props.handleChangeSignel(e, index, vIndex)}
        >
            {userName}
        </Checkbox>
    );
});
export default SiteManageV2;