import React, { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Card,
  Input,
  Tooltip,
  Button,
  notification,
  Spin,
  List,
  Space,
  Checkbox,
  Pagination,
  Empty,
} from 'antd';
import lodash, { clone } from 'lodash';
import {
  DoubleLeftOutlined,
  DoubleRightOutlined,
  UserOutlined,
} from '@ant-design/icons';
import PageContainer from '@/components/BasePageContainer';
import {
  getWebModuleTree,
  chooseUserToStation,
  getAllGroup,
  getUserByStation,
  getStationUserList,
  groupUserPagingList,
} from '@/services/userCenter/siteManage/api';
// import ListCard, {
//   checkChildrenByCondition,
//   getId,
// } from '@/components/CheckGroup';
import styles from '@/pages/userCenter/siteManage/SiteManage.less';
import qs from 'qs';
import { appConnector } from '@/containers/App/store';
import classnames from 'classnames';
import AddModal from './AddModal';
import DelModal from './DelModal';
import EditModal from './EditModal';
import userStyles from '@/pages/userCenter/userManage/UserManage.less';

const { Search } = Input;

const placeholder = '请输入机构名称';
const SiteManage = props => {
  const { userMode } = props;
  const [treeData, setTreeData] = useState([]); // 树结构数据
  const [currentStation, setCurrentStation] = useState(''); // 当前选中站点
  const [visibleParams, setvisibleParams] = useState({
    modalVisible: false, // 新增弹窗
    delVisible: false, // 删除弹窗
    editVisible: false, // 修改弹窗
    spinLoading: false, // 加载弹窗
    btnLoading: false,
    loading: false,
    checkBoxLoading: false,
  });
  const [flag, setFlag] = useState(1);
  const [dataList, setdataList] = useState([]);
  const [mulu, setMulu] = useState(true);
  const [selectList, setSelectList] = useState([]); // 选择列表数据
  const [total, setTotal] = useState(0); // 分页总数
  const [page, setPage] = useState({ pageNum: 1, pageSize: 5 });
  const [update, setUpdate] = useState(1);
  const [update1, setUpdate1] = useState(1);
  const [name, setName] = useState('');
  // 侧边栏站点
  useEffect(() => {
    handleShowModal('spinLoading', true);
    getWebModuleTree({
      userMode: userMode || 'super',
      select: '',
      node: -2,
    })
      .then(res => {
        handleShowModal('spinLoading', false);
        let arr = [];
        if (code===0) {
          arr.push(res.find(item => item.id === 'Web4StationRoot'));
        }
        if (arr[0]) {
          const stations = arr[0].children || [];
          setTreeData(stations);
          if (stations.length > 0) {
            if (!currentStation.stationID) {
              setCurrentStation(stations[0]);
            } else {
              setCurrentStation(
                stations.find(s => s.stationID === currentStation.stationID) ||
                  stations[0],
              );
            }
          } else {
            setdataList([]);
          }
        }
      })
      .catch(err => {
        handleShowModal('spinLoading', false);
        console.error(err);
      });
  }, [flag]);
  // 右边对应的机构
  useEffect(() => {
    if (!currentStation.stationID) return;
    handleShowModal('loading', true);
    getList();
  }, [update, name]);
  useEffect(() => {
    if (!currentStation.stationID) return;
    handleShowModal('loading', true);
    getAllcheckList();
  }, [currentStation, update1]);
  const getAllcheckList = async () => {
    let res = await getUserByStation({
      stationID: currentStation.stationID,
      _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));
      setUpdate(update + 1);
    }
  };
  const getList = () => {
    let params = {
      stationId: +currentStation.stationID || '',
      PageIndex: +page.pageNum,
      PageSize: +page.pageSize,
    };
    if (name) params = { ...params, name };
    groupUserPagingList(params).then(res => {
      if (res.code === 0 && res.data) {
        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 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 handleHide = () => {
    setMulu(!mulu);
  };
  const renderListItem = items =>
    items.map(t => (
      <List.Item
        onClick={() => {
          // setSelectList(lodash.cloneDeep([]));
          setPage({ pageNum: 1, pageSize: 5 });
          setCurrentStation(t);
        }}
        key={t.id}
        className={classnames({
          [styles.listItem]: true,
          [styles.selected]: currentStation.id === t.id,
        })}
      >
        {t.text}
      </List.Item>
    ));
  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.stationID, 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(
      qs.stringify({
        userList: String(result.flat()),
        stationID: currentStation.stationID,
      }),
      {
        headers: {
          'content-type': 'application/x-www-form-urlencggoded;charset=UTF-8',
        },
      },
    )
      .then(res => {
        handleShowModal('btnLoading', false);

        if (res.code===0) {
          setSelectList([]);
          setUpdate1(update1 + 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 });
    setUpdate(update + 1);
  };
  return (
    <PageContainer>
      <div className={styles.content}>
        <Card
          className={classnames({
            [styles.cardBox]: true,
            [styles.hideBox]: !mulu,
          })}
        >
          <Spin
            tip="loading...."
            spinning={visibleParams.spinLoading}
            style={{ marginTop: '20px' }}
          >
            <div className={userStyles.siteTitle}>
              <span>选择站点：</span>
            </div>
            <List>{renderListItem(treeData)}</List>
          </Spin>
          <AddModal
            visible={visibleParams.modalVisible}
            onCancel={() => handleShowModal('modalVisible', false)}
            confirmModal={confirmModal}
          />
          <DelModal
            visible={visibleParams.delVisible}
            stationId={currentStation.stationID}
            onCancel={() => handleShowModal('delVisible', false)}
            confirmModal={delModal}
          />
          <EditModal
            visible={visibleParams.editVisible}
            stationObj={currentStation}
            onCancel={() => handleShowModal('editVisible', false)}
            confirmModal={editModal}
          />
          <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>
            )}
            {!mulu && (
              <Tooltip title="显示站点" className={styles.hide}>
                <DoubleRightOutlined 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={() => {
                      handleShowModal('modalVisible', true);
                    }}
                  >
                    新增
                  </Button>
                  <Button
                    type="primary"
                    onClick={() => {
                      handleShowModal('editVisible', true);
                    }}
                    disabled={
                      !currentStation.stationID || visibleParams.spinLoading
                    }
                  >
                    编辑
                  </Button>
                  <Button
                    danger
                    type="primary"
                    onClick={() => {
                      handleShowModal('delVisible', true);
                    }}
                    disabled={
                      !currentStation.stationID || visibleParams.spinLoading
                    }
                  >
                    删除
                  </Button>
                </Space>
              </Col>
            </Row>
          </Card>
          <div style={{ background: '#fff' }}>
            <Card
              className={classnames({
                [styles.boxH]: mulu,
                [styles.cardBoxR]: true,
              })}
            >
              {/* <Checkbox className={styles.siteAll}>全选/反选</Checkbox> */}
              <Spin spinning={visibleParams.loading}>
                {dataList.map((item, index) => (
                  <Panels
                    {...item}
                    index={index}
                    key={item.GroupId}
                    handleChangeCollpase={handleChangeCollpase}
                    handleChangeAll={handleChangeAll}
                    handleChangeSignel={handleChangeSignel}
                  />
                ))}
              </Spin>
              {dataList.length > 0 && !visibleParams.loading ? (
                <>
                  <div style={{ textAlign: 'right' }}>
                    <Pagination
                      size="small"
                      total={total}
                      current={page.pageNum}
                      defaultPageSize="5"
                      onChange={handleChangePage}
                      pageSizeOptions={['5']}
                    />
                  </div>
                  <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} />
              )}
            </Card>
            <div className={styles.siteBtn}>
              <Button
                type="primary"
                className={styles.siteCommit}
                onClick={handleCommitBtn}
              >
                提交
              </Button>
            </div>
          </div>
        </div>
      </div>
    </PageContainer>
  );
};

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} /> */}
        <UserOutlined className={styles.siteIcon} />
        <p style={{ color }}>{GroupName}</p>
      </div>
      <div className={styles.sitePanelCon}>
        <Checkbox
          key="0"
          className={styles.siteList}
          checked={isChecked}
          onClick={e => props.handleChangeAll(e, index)}
        >
          全选
        </Checkbox>
        {Users.length > 0 &&
          Users.map((v, vIndex) => (
            <CheckBoxRow
              {...v}
              index={index}
              vIndex={vIndex}
              key={v.userID}
              handleChangeSignel={props.handleChangeSignel}
            />
          ))}
      </div>
    </div>
  );
});

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 React.memo(appConnector(SiteManage));
