import useModal from 'antd/lib/modal/useModal';
import React, { useEffect, useState } from 'react';
import SiteModal from '@/components/Modal/SiteModa';
import classnames from 'classnames';
import lodash, { clone } from 'lodash';
import { Card, Empty, Pagination, Checkbox, notification, Input, Row, Col } from 'antd';
import {
  getWebModuleTree,
  chooseUserToStation,
  getAllGroup,
  getUserByStation,
  getStationUserList,
  groupUserPagingList,
  addChildSiteNode,
  getSiteTree,
  getStationUsers,
} from '@/services/siteManage/api';
import { UserOutlined } from '@ant-design/icons';
import qs from 'qs';
import styles from './UserModal.less';
const { Search } = Input;
const placeholder = '请输入机构名称';
const UserModal = props => {
  const [dataList, setdataList] = useState([]);
  const [total, setTotal] = useState(0); // 分页总数
  const [page, setPage] = useState({ pageNum: 1, pageSize: 5 });
  const [selectList, setSelectList] = useState([]); // 选择列表数据
  const [updatePageUser, setUpdatePageUser] = useState(1); //
  const [updateCheck, setUpdateCheck] = useState(1);
  const [name, setName] = useState('');
  const { itemObj, confirmModal, visible } = props;
  const isAllChecked = index =>
    dataList[index].Users.filter(item => item.isChecked).length === dataList[index].Users.length;

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

  // 获取当前站点可编辑用户(已勾选和未勾选)分页展示
  const getList = () => {
    let params = {
      id: +itemObj.roleID || '',
      PageIndex: +page.pageNum,
      PageSize: +page.pageSize,
    };
    console.log(123);
    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);
        setTotal(0);
        setdataList(lodash.cloneDeep([]));
      }
    });
  };
  // 获取当前站点所有已经勾选的用户新接口
  const getAllCheckListNew = () => {
    getStationUsers({
      stationId: itemObj.roleID,
    }).then(res => {
      let list = [];
      if (res.data && res.data.length > 0) {
        console.log(res.data);
        res.data.map((item, index) => {
          list.push({
            GroupId: +item.OUID,
            GroupName: item.OUName,
            userName: item.userName,
            userID: item.userID,
          });
        });
      }
      setSelectList(lodash.cloneDeep(list));
      console.log(lodash.cloneDeep(list));
      setUpdatePageUser(updatePageUser + 1);
    });
  };
  const onSubmit = () => {
    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: itemObj.roleID,
      },
      // {
      //     headers: {
      //         'content-type': 'application/x-www-form-urlencggoded;charset=UTF-8',
      //     },
      // },
    )
      .then(res => {
        if (res.code === 0) {
          setSelectList([]);
          setUpdateCheck(updateCheck + 1);
          confirmModal(itemObj.roleID);
          notification.success({
            message: '提示',
            duration: 3,
            description: '设置成功',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 15,
            description: res.message,
          });
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  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: itemObj.roleID, 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 handleChangePage = (pageNum, pageSize) => {
    setPage({ pageNum, pageSize });
    setUpdatePageUser(updatePageUser + 1);
  };
  // 删除已选列表
  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 handleSearch = value => {
    setPage({ pageNum: 1, pageSize: 5 });
    setName(value);
    // getList(value);
  };
  return (
    <SiteModal
      {...props}
      title="关联用户"
      bodyStyle={{ width: '100%', minHeight: '100px' }}
      style={{ top: 100 }}
      width="800px"
      destroyOnClose
      cancelText="取消"
      okText="确认"
      onOk={() => onSubmit()}
    >
      <div style={{ background: '#fff' }}>
        <Card
          className={classnames({
            [styles.cardBoxR]: true,
          })}
        >
          <Row align="middle">
            <Col span={8}>
              <Search
                allowClear
                placeholder={placeholder}
                onSearch={handleSearch}
                // onChange={handleChange}
                enterButton
              />
            </Col>
          </Row>
          {dataList.length > 0 ? (
            <>
              <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} />
          )}
          {dataList.map((item, index) => (
            <Panels2
              {...item}
              index={index}
              key={item.GroupId}
              handleChangeCollpase={handleChangeCollpase}
              handleChangeAll={handleChangeAll}
              handleChangeSignel={handleChangeSignel}
            />
          ))}
          <div style={{ textAlign: 'right' }}>
            <Pagination
              size="small"
              total={total}
              current={page.pageNum}
              defaultPageSize="5"
              onChange={handleChangePage}
              // pageSizeOptions={['5']}
              pageSizeOptions={[10, 20, 40, 100]}
            />
          </div>
        </Card>
      </div>
    </SiteModal>
  );
};

const Panels2 = 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>
        <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>
  );
});

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 UserModal;
