import React, { useState } from 'react';
import { intersection, difference, sortBy, uniq } from 'lodash';
import { inject, observer } from 'mobx-react';
import { Popover, Row, Col } from 'antd';
import { BaseStore, Dict } from '@zenview/micro-basic-library';

import IconFont from '../../themeComponents/IconFont';
import CBox from '../../themeComponents/CBox';
import SearchInput from '../../components/SearchInput';
import PlaceTree from '../PlaceTree';
import OrgTreeWithSystem from '../OrgTreeWithSystem';
import Tree from '../../components/Tree';
import DeviceList from '../DeviceList';
import './index.less';
import { useMemoizedFn, useUpdateEffect } from 'ahooks';

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 = (
      <div className={`lm-c-base-list-wrapper`} style={{ borderRight: 'none', height: '100%' }}>
        <div className="title-part">
          <span className="title-text">{treeName}</span>
          <InputAfter className="keywords-list-input" onChange={(value) => onValueChange(value, treeData)} placeholder={inputPlaceholder} />
        </div>
        <div className="an-lm-c-base-list-layout">
          <Tree
            treeData={treeData}
            showIcon={showIcon}
            defaultSelectedKeys={['0-0']}
            defaultExpandAll
            onSelect={changeData}
            treeNodeProps={{
              treeNodeIcon: (node) => <IconFont type={IconFontType} />,
              key: 'key',
            }}
          />
        </div>
      </div>
    );
    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' ? (
          <OrgTreeWithSystem isInclude={includeSubOrganizations} isIncludeChange={isIncludeChange} treeData={orgTreeData} activeKey={[orgId]} hasTitle={true} hasSearch={true} onSelect={(keys) => onSelect(mode, keys[0])} showCount={true} />
        ) : (
          <PlaceTree treeData={placeTreeData} activeKey={placeId} hasTitle={true} hasSearch={true} onSelect={(keys) => onSelect(mode, keys[0])} showCount={true} />
        );
    } else {
      treeView =
        mode === 'org' ? (
          <OrgTreeWithSystem
            activeKey={[orgId]}
            hasTitle={true}
            hasSearch={true}
            isIncludeChange={isIncludeChange}
            isInclude={includeSubOrganizations}
            onSelect={(keys) => onSelect(mode, keys[0])}
            showCount={true}
            treeData={orgTreeData}
            title={
              <div className="change-select-mode">
                <SelectModeView currentMode={mode} changeMode={changeMode} title="组织机构" />
              </div>
            }
          />
        ) : (
          <PlaceTree
            activeKey={placeId}
            hasTitle={true}
            hasSearch={true}
            onSelect={(keys) => onSelect(mode, keys[0])}
            showCount={true}
            treeData={placeTreeData}
            title={
              <div className="change-select-mode">
                <SelectModeView currentMode={mode} changeMode={changeMode} title="行政区划" />
              </div>
            }
          />
        );
    }
    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 (
    <CBox>
      <Row style={boxStyle}>
        {!otherTree && (
          <Col span={8} style={{ ...boxStyle, border: '1px solid var(--bd-color)', borderRight: 'none' }}>
            {treeView}
          </Col>
        )}
        {otherTree && (
          <Col span={8} style={{ ...boxStyle, borderRight: 'none' }}>
            {otherMoreTree}
          </Col>
        )}
        <Col span={16} style={boxStyle}>
          <Row style={boxStyle} gutter={8}>
            <Col span={12} style={boxStyle}>
              <DeviceList
                placeholder={"请输入设备名称/CID/SN搜索"}
                hasFilter={hasFilter}
                deviceGroup={deviceGroup}
                onChange={onChangeKeywords}
                deviceList={cameraList}
                onChecked={checkListDevices}
                checkedKeys={tentativeDevicesKey}
                keywords={allListKeywords}
                checkable={true}
                key={listKey}
              />
            </Col>
            <Col span={12} style={boxStyle}>
              <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})`}
              />
            </Col>
          </Row>
        </Col>
      </Row>
    </CBox>
  );
}

const models = [
  { value: 'org', label: '组织机构' },
  { value: 'place', label: '行政区划' },
];
const SelectModeView = ({ title, changeMode, currentMode }) => {
  return (
    <Popover
      overlayClassName="lm-c-select-mode-view"
      placement="bottom"
      content={
        <div className="lm-c-mode-change-popup">
          {models.map((v) => (
            <div className={currentMode === v.value ? 'active-mode' : ''} key={v.value} onClick={() => changeMode(v.value)}>
              {v.label}
            </div>
          ))}
        </div>
      }
      trigger="click"
    // onVisibleChange={this.handleVisibleChange}
    >
      <span>
        {title} <IconFont type="icon-S_Arrow_SmallDown" />
      </span>
    </Popover>
  );
}
export default inject('device', 'org', 'place')(observer(SelectDevices));




