import React__default, { useState } from 'react';
import { intersection, sortBy, difference, uniq } from 'lodash';
import { inject, observer } from 'mobx-react';
import { Row, Col, Popover } from 'antd';
import { Dict, BaseStore } from '@zenview/micro-basic-library';
import IconFont from '../IconFont/index.js';
import CBox from '../CBox/index.js';
import SearchInput from '../SearchInput/index.js';
import PlaceTree from '../PlaceTree/index.js';
import OrgTreeWithSystem from '../OrgTreeWithSystem/index.js';
import TreeView from '../Tree/index.js';
import DeviceList from '../DeviceList/index.js';
import { useMemoizedFn, useUpdateEffect } from 'ahooks';
import '../_rollupPluginBabelHelpers-736b301a.js';
import '@zenview/micro-utils';
import '../TreeTitle/index.js';
import '../index-71189681.js';
import '../_commonjsHelpers-e7b0df42.js';
import 'react-is';
import '../HightLevel/index.js';
import '../OrgTree/index.js';
import '../index-6ef7005c.js';
import '../index-f41abfce.js';
import 'react-virtualized';
import '../index-33416316.js';

const boxStyle = {
  height: '100%'
};
const InputAfter = SearchInput;
const SelectDevices = props => {
  const [state, upDateState] = useState({
    selectDevices: props.selectDevices || [],
    // key值集合（选中设备）
    tentativeDevicesKey: props.selectDevices || [],
    tentativeDevicesList: props.device.getDeviceByIds(props.selectDevices || []),
    // 初步选中设备列表
    allListKeywords: '',
    // 未分配数据关键字筛选
    selectedKeywords: '',
    // 分配数据关键字筛选
    includeSubOrganizations: 0,
    //组织是否包含子菜单
    orgId: null,
    placeId: null,
    mode: 'org',
    listKey: Math.random()
  });
  const setState = useMemoizedFn(options => {
    upDateState(old => ({
      ...old,
      ...options
    }));
  });
  useUpdateEffect(() => {
    setState({
      selectDevices: [],
      tentativeDevicesKey: [],
      tentativeDevicesList: []
    });
  }, [props.selectFlag]);
  const onSelect = (mode, id) => {
    setState({
      [`${mode}Id`]: id,
      listKey: id
    });
  };
  const changeMode = mode => {
    setState({
      mode
    });
  };

  // 未初步选中数据列表
  const computedList = list => {
    const {
      org,
      place
    } = props;
    const {
      noSoldier = false
    } = props;
    const {
      orgId,
      placeId,
      mode,
      allListKeywords,
      includeSubOrganizations
    } = state;
    let newList = [];
    if (noSoldier) {
      list = list.filter(v => v.deviceType !== Dict.device.db.value);
    }
    if (allListKeywords) {
      list = list.filter(v => {
        const {
          name,
          deviceName,
          realName,
          cid,
          sn
        } = v;
        let filterName = name || deviceName || realName || '';
        return filterName.includes(allListKeywords) || cid.includes(allListKeywords) || sn.includes(allListKeywords);
      });
    }
    if (mode === 'org') {
      if (!orgId) {
        newList = list;
      } else {
        let orgIds = [orgId];
        if (includeSubOrganizations) {
          orgIds = org.queryOrgIdsForParentOrgId(orgId);
        }
        newList = list.filter(item => {
          const arr = item.organizationIds || [];
          return intersection(arr, orgIds).length > 0;
        });
      }
    } else {
      if (!placeId) {
        newList = list;
      } else {
        const allParentIds = place.getIdsForCodes(placeId ? place.getPlaceCodesWithChild(placeId) : []);
        for (let i = 0, l = list.length; i < l; i++) {
          const item = list[i];
          if (allParentIds.indexOf(item.placeId) > -1) {
            newList.push(item);
          }
        }
      }
    }
    return sortBy(newList, function (item) {
      return -item.deviceStatus;
    });
  };

  // 已选设备筛选
  const getSelectedList = () => {
    const {
      selectedKeywords,
      tentativeDevicesList
    } = state;
    return selectedKeywords ? tentativeDevicesList.filter(v => {
      const {
        name,
        deviceName,
        realName,
        cid,
        sn
      } = v;
      let filterName = name || deviceName || realName || '';
      return filterName.includes(selectedKeywords) || cid.includes(selectedKeywords) || sn.includes(selectedKeywords);
    }) : tentativeDevicesList;
  };

  // 摄像机列表选中 (选中后同步到右侧组件，同时同步的设备全部选中)
  const checkListDevices = (devicesKey, notSelect) => {
    const {
      selectDevices,
      tentativeDevicesKey
    } = state;

    // let addIds = difference(devicesKey, tentativeDevicesKey); // 新加的key
    let delIds = difference(tentativeDevicesKey, devicesKey); // 删除的key

    let rightIdFilter = uniq([].concat(difference(selectDevices, delIds), devicesKey));

    // // 解决选择第一个设备时rightIdFilter为空
    // rightIdFilter = rightIdFilter.length ? rightIdFilter : tentativeDevicesKey;
    setState({
      selectDevices: rightIdFilter,
      tentativeDevicesKey: devicesKey,
      tentativeDevicesList: props.device.getDeviceByIds(devicesKey)
    });
    props.onChange && props.onChange(rightIdFilter);
  };

  // 已选摄像机选择
  const checkedDevices = devices => {
    setState({
      selectDevices: devices,
      tentativeDevicesKey: devices
    });
    props.onChange && props.onChange(devices);
  };
  const onChangeKeywords = allListKeywords => {
    setState({
      allListKeywords
    });
  };
  const onChangeSelectedKeyword = selectedKeywords => {
    setState({
      selectedKeywords
    });
  };

  //修改右侧列表中设备顺序
  const onChangeSort = rightDevices => {
    setState({
      tentativeDevicesList: rightDevices
    });
    const {
      selectDevices
    } = state;
    const rightDevicesFilter = rightDevices.filter(v => selectDevices.includes(v.id)).map(v => v.id);
    props.onChange && props.onChange(rightDevicesFilter);
  };
  const deleteDevice = item => {
    const {
      selectDevices,
      tentativeDevicesKey
    } = state;
    let selectDevicesFilter = difference(selectDevices, [item.id]);
    let tentativeDevicesFilter = difference(tentativeDevicesKey, [item.id]);
    setState({
      selectDevices: selectDevicesFilter,
      tentativeDevicesKey: tentativeDevicesFilter,
      tentativeDevicesList: props.device.getDeviceByIds(tentativeDevicesFilter)
      // listKey: Math.random(),
    });
    props.onChange && props.onChange(selectDevicesFilter);
  };
  const changeData = v1 => {
    const {
      deviceListChange,
      treeData
    } = props;
    if (v1.length > 0) {
      let findKet;
      treeData[0].children.forEach(v => {
        if (v.key === v1[0]) {
          findKet = v.id;
        }
      });
      let deviceList = BaseStore.device.getDeviceByIds(JSON.parse(findKet));
      deviceListChange(deviceList);
      setState({
        listKey: findKet
      });
    }
  };

  //需要渲染别的树
  const getOtherTree = () => {
    const {
      treeName,
      inputPlaceholder,
      onValueChange,
      treeData,
      IconFontType,
      showIcon
    } = props;
    //otherTree（true需要其他树）treeName(tree列表名称)
    let otherMoreTree = /*#__PURE__*/React__default.createElement("div", {
      className: `lm-c-base-list-wrapper`,
      style: {
        borderRight: 'none',
        height: '100%'
      }
    }, /*#__PURE__*/React__default.createElement("div", {
      className: "title-part"
    }, /*#__PURE__*/React__default.createElement("span", {
      className: "title-text"
    }, treeName), /*#__PURE__*/React__default.createElement(InputAfter, {
      className: "keywords-list-input",
      onChange: value => onValueChange(value, treeData),
      placeholder: inputPlaceholder
    })), /*#__PURE__*/React__default.createElement("div", {
      className: "an-lm-c-base-list-layout"
    }, /*#__PURE__*/React__default.createElement(TreeView, {
      treeData: treeData,
      showIcon: showIcon,
      defaultSelectedKeys: ['0-0'],
      defaultExpandAll: true,
      onSelect: changeData,
      treeNodeProps: {
        treeNodeIcon: node => /*#__PURE__*/React__default.createElement(IconFont, {
          type: IconFontType
        }),
        key: 'key'
      }
    })));
    return otherMoreTree;
  };
  const isIncludeChange = flag => {
    setState({
      includeSubOrganizations: flag
    });
  };
  const getTreeView = () => {
    const {
      orgId,
      mode,
      placeId,
      includeSubOrganizations
    } = state;
    const {
      singleMode,
      placeTreeData,
      orgTreeData
    } = props;
    let treeView;
    if (singleMode) {
      treeView = singleMode === 'org' ? /*#__PURE__*/React__default.createElement(OrgTreeWithSystem, {
        isInclude: includeSubOrganizations,
        isIncludeChange: isIncludeChange,
        treeData: orgTreeData,
        activeKey: [orgId],
        hasTitle: true,
        hasSearch: true,
        onSelect: keys => onSelect(mode, keys[0]),
        showCount: true
      }) : /*#__PURE__*/React__default.createElement(PlaceTree, {
        treeData: placeTreeData,
        activeKey: placeId,
        hasTitle: true,
        hasSearch: true,
        onSelect: keys => onSelect(mode, keys[0]),
        showCount: true
      });
    } else {
      treeView = mode === 'org' ? /*#__PURE__*/React__default.createElement(OrgTreeWithSystem, {
        activeKey: [orgId],
        hasTitle: true,
        hasSearch: true,
        isIncludeChange: isIncludeChange,
        isInclude: includeSubOrganizations,
        onSelect: keys => onSelect(mode, keys[0]),
        showCount: true,
        treeData: orgTreeData,
        title: /*#__PURE__*/React__default.createElement("div", {
          className: "change-select-mode"
        }, /*#__PURE__*/React__default.createElement(SelectModeView, {
          currentMode: mode,
          changeMode: changeMode,
          title: "\u7EC4\u7EC7\u673A\u6784"
        }))
      }) : /*#__PURE__*/React__default.createElement(PlaceTree, {
        activeKey: placeId,
        hasTitle: true,
        hasSearch: true,
        onSelect: keys => onSelect(mode, keys[0]),
        showCount: true,
        treeData: placeTreeData,
        title: /*#__PURE__*/React__default.createElement("div", {
          className: "change-select-mode"
        }, /*#__PURE__*/React__default.createElement(SelectModeView, {
          currentMode: mode,
          changeMode: changeMode,
          title: "\u884C\u653F\u533A\u5212"
        }))
      });
    }
    return treeView;
  };
  const {
    selectDevices,
    allListKeywords,
    selectedKeywords,
    tentativeDevicesKey,
    listKey,
    includeSubOrganizations
  } = state;
  const {
    deviceList,
    device,
    otherTree,
    treeMode,
    deviceGroup,
    hasFilter
  } = props;
  const cameraList = computedList(deviceList || device.cameraList); // 待选择设备列表

  const treeView = getTreeView(); // 组织场所树
  const otherMoreTree = getOtherTree(); // 其他树
  const selectDevicesFilter = getSelectedList(); // 已选设备列表
  return /*#__PURE__*/React__default.createElement(CBox, null, /*#__PURE__*/React__default.createElement(Row, {
    style: boxStyle
  }, !otherTree && /*#__PURE__*/React__default.createElement(Col, {
    span: 8,
    style: {
      ...boxStyle,
      border: '1px solid var(--bd-color)',
      borderRight: 'none'
    }
  }, treeView), otherTree && /*#__PURE__*/React__default.createElement(Col, {
    span: 8,
    style: {
      ...boxStyle,
      borderRight: 'none'
    }
  }, otherMoreTree), /*#__PURE__*/React__default.createElement(Col, {
    span: 16,
    style: boxStyle
  }, /*#__PURE__*/React__default.createElement(Row, {
    style: boxStyle,
    gutter: 8
  }, /*#__PURE__*/React__default.createElement(Col, {
    span: 12,
    style: boxStyle
  }, /*#__PURE__*/React__default.createElement(DeviceList, {
    placeholder: "请输入设备名称/CID/SN搜索",
    hasFilter: hasFilter,
    deviceGroup: deviceGroup,
    onChange: onChangeKeywords,
    deviceList: cameraList,
    onChecked: checkListDevices,
    checkedKeys: tentativeDevicesKey,
    keywords: allListKeywords,
    checkable: true,
    key: listKey
  })), /*#__PURE__*/React__default.createElement(Col, {
    span: 12,
    style: boxStyle
  }, /*#__PURE__*/React__default.createElement(DeviceList, {
    placeholder: "请输入设备名称/CID/SN搜索",
    hasFilter: hasFilter,
    deviceGroup: deviceGroup,
    checkable: true,
    treeMode: treeMode,
    deviceList: selectDevicesFilter,
    checkedKeys: selectDevices,
    deleteItem: deleteDevice,
    keywords: selectedKeywords,
    onChange: onChangeSelectedKeyword,
    onChecked: checkedDevices,
    onChangeSort: onChangeSort,
    title: `已选摄像机(${selectDevices.length})`
  }))))));
};
const models = [{
  value: 'org',
  label: '组织机构'
}, {
  value: 'place',
  label: '行政区划'
}];
const SelectModeView = ({
  title,
  changeMode,
  currentMode
}) => {
  return /*#__PURE__*/React__default.createElement(Popover, {
    overlayClassName: "lm-c-select-mode-view",
    placement: "bottom",
    content: /*#__PURE__*/React__default.createElement("div", {
      className: "lm-c-mode-change-popup"
    }, models.map(v => /*#__PURE__*/React__default.createElement("div", {
      className: currentMode === v.value ? 'active-mode' : '',
      key: v.value,
      onClick: () => changeMode(v.value)
    }, v.label))),
    trigger: "click"
    // onVisibleChange={this.handleVisibleChange}
  }, /*#__PURE__*/React__default.createElement("span", null, title, " ", /*#__PURE__*/React__default.createElement(IconFont, {
    type: "icon-S_Arrow_SmallDown"
  })));
};
var SelectDevices$1 = inject('device', 'org', 'place')(observer(SelectDevices));

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