import React, { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Tree,
  Card,
  Input,
  Spin,
  notification,
  Button,
  Tooltip,
  Space,
} from 'antd';
import PageContainer from '@/components/BasePageContainer';
import {
  DoubleLeftOutlined,
  DoubleRightOutlined,
  TeamOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  setMenuToRole,
  getRoleGroupList,
  getMenuByRoleWithLevel,
} from '@/services/userCenter/roleManage/api';
import ListCard, {
  checkChildrenByCondition,
  getId,
} from '@/components/CheckGroup';
// import ListCard from '@/pages/orgnazation/ListCard';
import qs from 'qs';
import classnames from 'classnames';
import styles from '@/pages/userCenter/roleManage/RoleManage.less';
import AddModal from './AddModal';
import DelModal from './DelModal';
import EditModal from './EditModal';
import EditGroup from './EditGroup';
import userStyles from '../UserManage.less';

const { Search } = Input;
const placeholder = '请输入功能名称';

const SiteManage = () => {
  const [treeData, setTreeData] = useState([]);
  const [searchWord, setSearchWord] = useState('');
  const [roleID, setRoleID] = useState(''); // 角色ID
  const [saveTreeId, setSaveTreeId] = useState(''); // 保存点击回调的roleid
  const [modalVisible, setModalVisible] = useState(false); // 新增弹窗
  const [flag, setFlag] = useState(1);
  const [itemObj, setItemObj] = useState({}); // 选择的角色item
  const [delVisible, setDelVisible] = useState(false); // 删除弹窗
  const [editVisible, setEditVisible] = useState(false); // 修改弹窗
  const [subList, setSubList] = useState([]); // 选中的数组
  const [spinLoading, setSpinLoading] = useState(false);
  const [currentSelectId, setCurrentSelectId] = useState([]); // 选中的树节点
  const [saveCurId, setSaveCurId] = useState([]); // 树节点ID
  const [groupVisible, setGroupVisible] = useState(false); // 分组编辑弹窗
  const [hasData, setHasData] = useState(false);
  const [valueList, setValueList] = useState([]);
  const [dataList, setdataList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [btnLoading, setBtnLoading] = useState(false);
  const [mulu, setMulu] = useState(true);

  // 点击树的回调
  const handleTreeSelect = (e, treenode) => {
    if (treenode) {
      console.log(e, node, 'node');
      const { node } = treenode;
      const { roleID: id } = node;
      setItemObj(node);
      if (id) {
        setSaveTreeId(id);
        setRoleID(id);
        setValueList([...valueList]);
      } else {
        setRoleID(saveTreeId);
      }
    }

    if (e[0]) {
      setCurrentSelectId(e);
      setSaveCurId(e);
    } else {
      setCurrentSelectId(saveCurId);
    }
  };
  useEffect(() => {
    setSpinLoading(true);
    getRoleGroupList({ userID: '1' }).then(res => {
      setSpinLoading(false);
      if (res.code === 0) {
        const { roleList } = res.data;
        let arr = transTree(roleList);
        setTreeData(arr);
      }
    });
    return () => {
      setItemObj({});
    };
  }, [flag]);

  const buildMap = list => {
    const mapObj = {
      type: 'widgetGroup',
      searchWord,
      children: list.filter(l => l.type === 'widgetUIPage'),
      text: '地图组件',
      itemid: '9999',
    };

    return list.some(l => l.type === 'widgetUIPage')
      ? [mapObj, ...list.filter(l => l.type !== 'widgetUIPage')]
      : list;
  };

  useEffect(() => {
    if (!roleID) return;
    setLoading(true);
    const defaultConfig = {
      optionsList: [],
      title: '默认组',
      id: '',
    };
    getMenuByRoleWithLevel({
      roleID: itemObj.roleID,
      subSystemValue: itemObj.subSystemValue,
      subSystemName: itemObj.subSystemValue,
      _version: 9999,
      _dc: new Date().getTime(),
    })
      .then(res => {
        const list = [];
        // eslint-disable-next-line no-unused-expressions
        res.success &&
          res.root.forEach(item => {
            list.push({ ...defaultConfig, ...item });
          });
        const finalList = buildMap(list);
        setdataList(finalList);
        setValueList(
          finalList
            .map(l =>
              checkChildrenByCondition(
                l,
                it => (it.isChecked ? [getId(it)] : []),
                true,
                'map',
              ).flat(Infinity),
            )
            .flat(Infinity)
            .filter(Boolean),
        );
        setLoading(false);
      })
      .catch(err => {
        setLoading(false);
      });
  }, [roleID]);

  const handleAdd = e => {
    setModalVisible(true);
  };
  // 角色删除
  const handleDel = e => {
    setDelVisible(true);
  };
  // 编辑角色
  const handleEdit = e => {
    setEditVisible(true);
  };
  // 分组编辑
  const groupEdit = () => {
    setGroupVisible(true);
  };
  // 树形数据转换;
  const transTree = val => {
    let arr = val;
    let newArr = [];
    let arr2 = arr.filter(item => {
      if (item.child && item.child.length > 0) {
        item.child.forEach(itemC => {
          item.roleList.unshift(itemC);
        });
      }
      if (item.visibleTitle === '手持系统') {
        newArr[0] = item;
      }
      if (item.visibleTitle === '小程序') {
        newArr[1] = item;
      }
      return (
        item.visibleTitle !== '其它角色' &&
        item.visibleTitle !== '运维管理' &&
        item.visibleTitle !== '手持系统' &&
        item.visibleTitle !== '小程序'
      );
    });
    arr2 = arr2.concat(newArr);
    console.log(arr2, 'arr2');
    let arr3 = arr2.map(item => {
      item.title = item.visibleTitle || '';
      item.key = item.visibleValue || '';
      item.icon = <TeamOutlined />;
      if (item.roleList && item.roleList.length > 0) {
        item.roleList.map((itemRole, index) => {
          if (itemRole.roleList) {
            itemRole.title = itemRole.visibleTitle || '';
            itemRole.key = itemRole.visibleTitle + itemRole.visibleValue || '';
            itemRole.groupflag = itemRole.visibleTitle;
            itemRole.icon = <TeamOutlined />;
            itemRole.roleList.map(i => {
              i.title = i.roleName;
              i.key = i.roleID;
              i.subSystemValue = item.visibleValue;
              i.group = itemRole.visibleTitle;
              i.icon = <UserOutlined />;
              if (roleID && roleID === i.roleID) {
                setItemObj(i);
              }
            });

            itemRole.children = itemRole.roleList;
          } else {
            itemRole.title = itemRole.roleName;
            itemRole.key = itemRole.roleID;
            itemRole.subSystemValue = item.visibleValue;
            itemRole.icon = <UserOutlined />;
            if (roleID && roleID === itemRole.roleID) {
              setItemObj(itemRole);
            }
          }
          return itemRole;
        });
      }
      item.children = item.roleList;
      return item;
    });
    return arr3;
  };
  // 获取搜索框的值
  const handleSearch = value => {
    setSearchWord(value);
  };
  const handleChange = e => {
    const { value } = e.target;
    setSearchWord(value);
  };
  // 确认回调
  const confirmModal = e => {
    setModalVisible(false);
    setFlag(flag + 1);
    setItemObj('');
  };
  // 删除弹窗回调
  const delModal = () => {
    setDelVisible(false);
    setFlag(flag + 1);
    setItemObj('');
  };
  // 编辑弹窗回调
  const editModal = () => {
    setEditVisible(false);
    setFlag(flag + 1);
    handleTreeSelect(saveCurId);
    // setItemObj('');
  };
  // 分组编辑回调
  const groupModal = () => {
    setGroupVisible(false);
    setFlag(flag + 1);
    setItemObj('');
    handleTreeSelect(saveCurId);
  };
  const valueCallback = valueObj => {
    setSubList(valueObj);
  };
  const handleHide = () => {
    setMulu(!mulu);
  };
  const handleCommit = results => {
    setBtnLoading(true);
    setMenuToRole(
      qs.stringify({
        roleID,
        menuNameList: String(results.flat()),
      }),
      {
        headers: {
          'content-type': 'application/x-www-form-urlencggoded;charset=UTF-8',
        },
      },
    )
      .then(res => {
        setBtnLoading(false);
        if (res.success) {
          setValueList([...results.flat()]);
          notification.success({
            message: '提示',
            duration: 3,
            description: '设置成功',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 15,
            description: res.message,
          });
        }
      })
      .catch(err => {
        setBtnLoading(false);
        console.log(err);
      });
  };
  return (
    <PageContainer>
      {/* <Row gutter={0}>
        <Col span={mulu ? 4 : 0}> */}
      <div
        className={classnames({
          [styles.content]: true,
        })}
      >
        <Card
          className={classnames({
            [styles.cardBox]: true,
            [styles.hideBox]: !mulu,
          })}
        >
          <Spin
            tip="loading...."
            spinning={spinLoading}
            style={{ margin: '20px auto ', display: 'block' }}
          >
            <div className={userStyles.siteTitle}>
              <span>选择角色:</span>
            </div>
            {treeData && treeData.length > 0 && (
              <Tree
                // showLine={{ showLeafIcon: false }}
                showIcon
                onSelect={handleTreeSelect}
                autoExpandParent
                expandedKeys={currentSelectId}
                treeData={treeData}
                selectedKeys={currentSelectId}
                blockNode
              />
            )}
          </Spin>
          <AddModal
            visible={modalVisible}
            onCancel={() => setModalVisible(false)}
            itemObj={itemObj}
            confirmModal={confirmModal}
          />
          <DelModal
            visible={delVisible}
            itemObj={itemObj}
            onCancel={() => setDelVisible(false)}
            confirmModal={delModal}
          />
          <EditModal
            visible={editVisible}
            itemObj={itemObj}
            onCancel={() => setEditVisible(false)}
            confirmModal={editModal}
          />
          <EditGroup
            visible={groupVisible}
            itemObj={itemObj}
            onCancel={() => setGroupVisible(false)}
            confirmModal={groupModal}
          />
          <div>
            {mulu && (
              <Tooltip title="隐藏角色栏" className={styles.hide}>
                <DoubleLeftOutlined onClick={() => handleHide()} />
              </Tooltip>
            )}
            {!mulu && (
              <Tooltip title="显示角色栏" className={styles.hide}>
                <DoubleRightOutlined onClick={() => handleHide()} />
              </Tooltip>
            )}
          </div>
        </Card>
        {/* <div>
            {mulu && (
              <Tooltip title="隐藏角色栏" className={styles.hide}>
                <DoubleLeftOutlined onClick={() => handleHide()} />
              </Tooltip>
            )}
          </div> */}
        {/* </Col> */}
        {/* <Col span={mulu ? 0 : 1}>
          {mulu && (
            <Tooltip title="隐藏角色栏" className={styles.hide}>
              <DoubleLeftOutlined onClick={() => handleHide()} />
            </Tooltip>
          )}
          {!mulu && (
            <Tooltip title="显示角色栏" className={styles.hide}>
              <DoubleRightOutlined onClick={() => handleHide()} />
            </Tooltip>
          )}
        </Col> */}
        {/* <Col span={mulu ? 20 : 23}> */}
        <div
          className={classnames({
            [styles.boxR]: true,
            [styles.boxH]: mulu,
          })}
        >
          <Card
            className={classnames({
              [styles.cardBoxTop]: true,
              [styles.boxH]: mulu,
            })}
          >
            <Row align="middle">
              <Col span={1}>搜索</Col>
              <Col span={8}>
                <Search
                  allowClear
                  placeholder={placeholder}
                  onSearch={handleSearch}
                  onChange={handleChange}
                  enterButton
                />
              </Col>
              <Col span={3} />
              <Col span={8}>
                <Space size="large">
                  <Button
                    type="primary"
                    onClick={() => {
                      handleAdd();
                    }}
                  >
                    新增角色
                  </Button>
                  <Button
                    type="primary"
                    disabled={!itemObj.roleID}
                    onClick={() => {
                      handleEdit();
                    }}
                  >
                    编辑角色
                  </Button>
                  <Button
                    type="primary"
                    danger
                    onClick={() => {
                      handleDel();
                    }}
                    disabled={!itemObj.roleID}
                  >
                    删除角色
                  </Button>
                  <Button
                    type="primary"
                    onClick={() => {
                      groupEdit();
                    }}
                    disabled={!itemObj.groupflag}
                  >
                    编辑分组
                  </Button>
                </Space>
              </Col>
            </Row>
          </Card>
          <Card
            className={classnames({
              [styles.boxH]: mulu,
              [styles.cardBoxR]: true,
            })}
          >
            {roleID && (
              <ListCard
                loading={loading}
                checkList={valueList}
                dataList={dataList}
                searchWord={searchWord}
                onCommit={handleCommit}
                btnLoading={btnLoading}
                hasData={hasData}
              />
            )}
          </Card>
        </div>
        {/* </Col>
      </Row> */}
      </div>
    </PageContainer>
  );
};

export default SiteManage;