import React__default, { useState, useEffect, useCallback, useMemo } from 'react';
import { inject, observer } from 'mobx-react';
import { difference, cloneDeep } from 'lodash';
import { Row, Col } from 'antd';
import { cache, treeHelper } from '@zenview/micro-utils';
import CBox from '../CBox/index.js';
import IconFont from '../IconFont/index.js';
import OrgTree from '../OrgTree/index.js';
import { _ as _extends } from '../_rollupPluginBabelHelpers-736b301a.js';
import '../VList/index.js';
import { L as ListView } from '../index-f41abfce.js';
import { BaseStore, Service } from '@zenview/micro-basic-library';
import '../Tree/index.js';
import '../index-71189681.js';
import '../_commonjsHelpers-e7b0df42.js';
import 'react-is';
import '../HightLevel/index.js';
import '../TreeTitle/index.js';
import '../SearchInput/index.js';
import 'react-virtualized';
import '../index-6ef7005c.js';
import 'ahooks';
import '../index-fcf1ad06.js';

class ClearList extends React__default.Component {
  constructor(...args) {
    super(...args);
    this.deleteItem = (item, e) => {
      e.stopPropagation();
      e.preventDefault();
      const {
        deleteItem
      } = this.props;
      deleteItem && deleteItem(item);
    };
  }
  render() {
    const {
      className = "",
      deleteItem,
      renderItemExt,
      ...props
    } = this.props;
    return /*#__PURE__*/React__default.createElement(ListView.CheckList, _extends({}, props, {
      className: `lm-c-clear-list-wrapper ${className}`,
      renderItemExt: item => renderItemExt ? renderItemExt(item) : deleteItem && /*#__PURE__*/React__default.createElement("span", {
        className: "clear-item",
        onClick: e => this.deleteItem(item, e)
      }, /*#__PURE__*/React__default.createElement(IconFont, {
        type: "icon-S_Edit_LineClose",
        title: "\u5220\u9664"
      }))
    }));
  }
}

function SelectUser({
  privilegeNames = [],
  initialValue = [],
  onChange,
  onInfoChange,
  style,
  boxStyle = {
    height: '400px'
  },
  orgTreeData,
  org,
  exceptValue = []
}) {
  const [state, setState] = useState({
    orgId: null,
    // 选中的组织
    keywords: '',
    // 左侧关键字
    selKeywords: '',
    // 右侧选中列表关键字
    leftIds: [],
    // 左侧选中的id
    rightList: [],
    // 右侧人员列表
    rightIds: [],
    // 右侧选中的id
    listKey: Math.random() // 用于刷新用户列表
  });
  const [userList, setUserList] = useState([]);
  useEffect(() => {
    // 请求接口，拿到有权限的用户列表
    let functionCodes = [];
    if (privilegeNames.length > 0) {
      const codes = BaseStore.auth.getInfoByNames(privilegeNames);
      if (codes && codes.length > 0) {
        for (const item of codes) {
          if (item && item.code) functionCodes.push(item.code);
        }
      }
    }
    // 请求接口，拿到有权限的用户列表
    Service.$http({
      headers: {
        Authorization: cache.getCache('token', 'session')
      },
      requestId: 'user',
      method: 'post',
      url: `/api/user/userRole/v3/queryPrivilegeUsers`,
      data: {
        functionCodes
      }
    }).then(res => {
      // res为有权限的所有用户-----根据单一数组id筛选对应的整个用户详情
      let userList = res.data || [];
      // 过滤掉不需要展示的数据
      if (exceptValue.length) {
        userList = userList.filter(item => !exceptValue.includes(item.id));
      }
      setUserList(userList); // 保存到全局
      setState(old => ({
        ...old,
        leftIds: initialValue,
        rightList: userList.filter(v => ~initialValue.indexOf(v.id)),
        rightIds: initialValue
      }));
      onChange && onChange(initialValue);
      onInfoChange && onInfoChange(getUserListByIds(initialValue));
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const onOrgSelect = useCallback(id => {
    setState(old => ({
      ...old,
      orgId: id,
      listKey: id
    }));
  }, []);
  const onChangeKeywords = useCallback(keywords => {
    setState(old => ({
      ...old,
      keywords
    }));
  }, []);

  // 已分配布控库关键字
  const onChangeSelectedKeyword = useCallback(selKeywords => {
    setState(old => ({
      ...old,
      selKeywords
    }));
  }, []);
  const getUserListByIds = useCallback(ids => {
    return userList.filter(v => ~ids.indexOf(v.id));
  }, [userList]);

  /**
   * @desc 左侧人员选中
   * @param keys 左侧所有选中的id集合（包含两个部分，当前列表选中，其他列表选中）
   */
  const leftOnChecked = useCallback(keys => {
    const {
      leftIds,
      rightIds
    } = state;
    let addIds = difference(keys, leftIds); // 新加的key
    let delIds = difference(leftIds, keys); // 删除的key
    let rightIdFilter = [].concat(difference(rightIds, delIds), addIds);
    setState(old => ({
      ...old,
      leftIds: keys,
      rightIds: rightIdFilter,
      rightList: getUserListByIds(keys)
    }));
    onChange && onChange(rightIdFilter);
    onInfoChange && onInfoChange(getUserListByIds(rightIdFilter));
  }, [getUserListByIds, state, onChange, onInfoChange]);

  /**
   * @desc 右侧人员选中
   */
  const rightOnChecked = useCallback(keys => {
    setState(old => ({
      ...old,
      rightIds: keys
    }));
    onChange && onChange(keys);
    onInfoChange && onInfoChange(getUserListByIds(keys));
  }, [getUserListByIds, onChange, onInfoChange]);
  const getUserList = useCallback(data => {
    const {
      orgId,
      keywords
    } = state;
    let arr = cloneDeep(data); // 所有有权限用户集合
    if (!!orgId) {
      let orgIds = BaseStore.org.queryOrgIdsForParentOrgId(orgId);
      arr = arr.filter(item => orgIds.indexOf(item.organizationId) > -1);
    }
    if (keywords) {
      arr = arr.filter(v => ~v.realName.indexOf(keywords));
    }
    return arr;
  }, [state]);
  const getRightList = useCallback(data => {
    const {
      selKeywords
    } = state;
    if (selKeywords) {
      return data.filter(v => ~v.realName.indexOf(selKeywords));
    }
    return data;
  }, [state]);

  // 待添加列表取消选中
  const deleteItem = useCallback(item => {
    const {
      leftIds,
      rightIds
    } = state;
    const leftIdsFilter = difference(leftIds, [item.id]);
    const rightIdsFilter = difference(rightIds, [item.id]);
    setState(old => ({
      ...old,
      leftIds: leftIdsFilter,
      rightIds: rightIdsFilter,
      rightList: getUserListByIds(leftIdsFilter) // 右侧列表是左侧列表选中的ids的集合
    }));
    onChange && onChange(rightIdsFilter);
    onInfoChange && onInfoChange(getUserListByIds(rightIdsFilter));
  }, [state, onChange, onInfoChange, getUserListByIds]);
  const {
    orgId,
    keywords,
    selKeywords,
    leftIds,
    rightIds,
    rightList
  } = state;
  const leftList = useMemo(() => getUserList(userList), [userList, getUserList]);
  const rightListFilter = useMemo(() => getRightList(rightList), [rightList, getRightList]);
  const treeData = useMemo(() => orgTreeData ? orgTreeData : treeHelper.computTreeList(org.orgListWithCameraCount), [orgTreeData, org.orgListWithCameraCount]);
  return /*#__PURE__*/React__default.createElement(CBox, {
    style: style
  }, /*#__PURE__*/React__default.createElement(Row, null, /*#__PURE__*/React__default.createElement(Col, {
    span: 8,
    style: {
      ...boxStyle,
      border: '1px solid var(--bd-color)',
      borderRight: 'none'
    }
  }, /*#__PURE__*/React__default.createElement(OrgTree, {
    treeData: treeData,
    activeKey: [orgId],
    onSelect: keys => onOrgSelect(keys[0]),
    showCount: false,
    title: "\u7EC4\u7EC7\u673A\u6784"
  })), /*#__PURE__*/React__default.createElement(Col, {
    span: 16,
    style: boxStyle
  }, /*#__PURE__*/React__default.createElement(Row, {
    gutter: 8
  }, /*#__PURE__*/React__default.createElement(Col, {
    span: 12,
    style: boxStyle
  }, /*#__PURE__*/React__default.createElement(ClearList, {
    title: "\u4EBA\u5458",
    keywords: keywords,
    onChange: onChangeKeywords,
    placeholder: "\u8BF7\u8F93\u5165\u4F60\u8981\u641C\u7D22\u7684\u4EBA\u5458",
    whatIcon: () => /*#__PURE__*/React__default.createElement(IconFont, {
      type: "icon-S_Edit_Avatar"
    }),
    checkable: true,
    list: leftList,
    onChecked: leftOnChecked,
    checkedKeys: leftIds,
    itemNameKey: "realName"
  })), /*#__PURE__*/React__default.createElement(Col, {
    span: 12,
    style: boxStyle
  }, /*#__PURE__*/React__default.createElement(ClearList, {
    title: `已添加(${rightIds.length}人)`,
    keywords: selKeywords,
    onChange: onChangeSelectedKeyword,
    placeholder: "\u8BF7\u8F93\u5165\u4F60\u8981\u641C\u7D22\u7684\u4EBA\u5458",
    whatIcon: () => /*#__PURE__*/React__default.createElement(IconFont, {
      type: "icon-S_Edit_Avatar"
    }),
    checkable: true,
    list: rightListFilter,
    onChecked: rightOnChecked,
    checkedKeys: rightIds,
    itemNameKey: "realName",
    deleteItem: deleteItem
  }))))));
}
var index = inject('org')(observer(/*#__PURE__*/React__default.forwardRef(SelectUser)));

export { index as default };
//# sourceMappingURL=index.js.map
