import React, { useState, useEffect } from 'react';
import { Row, Col, Tree, Card, Input, Tooltip, Spin, notification } from 'antd';
import { FileAddTwoTone, EditTwoTone, DeleteTwoTone } from '@ant-design/icons';
import { PageContainer, GridContent } from '@ant-design/pro-layout';
import {
  getWebModuleTree,
  chooseUserToStation,
} from '@/services/userCenter/roleManage/api';
import ListCard from '@/pages/orgnazation/ListCard';
import qs from 'qs';
import styles from '@/pages/userCenter/roleManage/RoleManage.less';
import AddModal from './AddModal';
import DelModal from './DelModal';
import EditModal from './EditModal';
const { Search } = Input;
const placeholder = '请输入人员姓名';
const SiteManage = () => {
  const [treeData, setTreeData] = useState([]);
  const [searchWord, setSearchWord] = useState('');
  const [ouid, setOuid] = useState('');
  const [saveTreeId, setSaveTreeId] = useState(''); // 保存点击回调的ird
  const [modalVisible, setModalVisible] = useState(false); // 新增弹窗
  const [flag, setFlag] = useState(1);
  const [stationId, setStationId] = useState(''); // 选择的站点
  const [stationObj, setStationObj] = useState({}); // 选择的站点
  const [delVisible, setDelVisible] = useState(false); // 删除弹窗
  const [editVisible, setEditVisible] = useState(false); // 修改弹窗
  const [subList, setSubList] = useState([]); // 选中的数组
  const [spinLoading, setSpinLoading] = useState(false);
  // 点击树的回调
  const handleTreeSelect = e => {
    console.log(e);
    let id = e[0];
    if (id) {
      setSaveTreeId(id);
      setOuid(id);
    } else {
      setOuid(saveTreeId);
    }
  };
  useEffect(() => {
    setSpinLoading(true);
    getWebModuleTree({
      userMode: 'super',
      select: '',
      _version: 9999,
      _dc: Date.now(),
      node: -2,
    })
      .then(res => {
        setSpinLoading(false);

        let arr = [];
        if (res) {
          arr.push(res.find(item => item.id === 'Web4StationRoot'));
          console.log(arr, 'arr');
        }
        let arr2 = transTree(arr);
        setTreeData(arr2);
      })
      .catch(err => {
        setSpinLoading(false);
        console.error(err);
      });
  }, [flag]);
  const Title = props => {
    const { text } = props;
    console.log(props);
    return (
      <div className={styles.treeTitle}>
        {text}
        <div className={styles.titleBox}>
          <Tooltip title="新增角色">
            <FileAddTwoTone
              onClick={() => {
                handleAdd(props);
              }}
            />
          </Tooltip>
          <Tooltip title="编辑角色">
            <EditTwoTone
              onClick={() => {
                handleEdit(props);
              }}
            />
          </Tooltip>
          <Tooltip title="删除角色">
            <DeleteTwoTone
              onClick={() => {
                handleDel(props);
              }}
            />
          </Tooltip>
        </div>
      </div>
    );
  };
  const handleAdd = e => {
    console.log(e);
    setModalVisible(true);
  };
  // 角色删除
  const handleDel = e => {
    setStationId(e.stationID);
    setDelVisible(true);
  };
  // 编辑角色
  const handleEdit = e => {
    setStationObj(e);
    setEditVisible(true);
  };
  // 树形数据转换
  const transTree = val => {
    console.log(val);
    let arr = val;
    return arr.map((item, index) => {
      item.title = Title(item) || item.text;
      item.key = item.stationID || '';
      let obj = {};
      if (Array.isArray(item.children) && item.children.length > 0) {
        transTree(item.children);
        obj = item;
        return obj;
      }
      return item;
    });
  };
  // 获取搜索框的值
  const handleSearch = value => {
    setSearchWord(value);
  };
  const confirmModal = e => {
    setModalVisible(false);
    setFlag(flag + 1);
  };
  const delModal = () => {
    setDelVisible(false);
    setFlag(flag + 1);
  };
  const editModal = () => {
    setEditVisible(false);
    setFlag(flag + 1);
  };
  const valueCallback = valueObj => {
    setSubList(valueObj);
  };
  const handleCommit = value => {
    let arr = Object.values(subList);
    chooseUserToStation(
      qs.stringify({
        userList: String(arr.flat()),
        stationID: ouid,
      }),
      {
        headers: {
          'content-type': 'application/x-www-form-urlencggoded;charset=UTF-8',
        },
      },
    )
      .then(res => {
        if (res.success) {
          notification.success({
            message: '提示',
            duration: 3,
            description: '设置成功',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: res.message,
          });
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  return (
    <PageContainer>
      <GridContent>
        <Row gutter={12}>
          <Col lg={6} md={24}>
            <Card className={styles.cardBox}>
              <Spin
                tip="loading...."
                spinning={spinLoading}
                style={{ marginTop: '20px' }}
              >
                <Tree
                  showLine={{ showLeafIcon: false }}
                  showIcon
                  onSelect={e => handleTreeSelect(e)}
                  treeData={treeData}
                />
              </Spin>
              <AddModal
                visible={modalVisible}
                onCancel={() => setModalVisible(false)}
                confirmModal={confirmModal}
              />
              <DelModal
                visible={delVisible}
                stationId={stationId}
                onCancel={() => setDelVisible(false)}
                confirmModal={delModal}
              />
              <EditModal
                visible={editVisible}
                stationObj={stationObj}
                onCancel={() => setEditVisible(false)}
                confirmModal={editModal}
              />
            </Card>
          </Col>
          <Col lg={18} md={24}>
            <Card className={styles.cardBox}>
              <Row align="middle">
                <Col span={1}>搜索</Col>
                <Col span={8}>
                  <Search
                    allowClear
                    placeholder={placeholder}
                    onSearch={handleSearch}
                    enterButton
                  />
                </Col>
              </Row>
              {ouid && (
                <ListCard
                  ouid={ouid}
                  searchWord={searchWord}
                  valueCallback={valueCallback}
                  onCommit={handleCommit}
                />
              )}
            </Card>
          </Col>
        </Row>
      </GridContent>
    </PageContainer>
  );
};

export default SiteManage;