import React from 'react';
import { uniqBy } from 'lodash';
import DrawTools from '../../components/DrawTools';
import MapResetTools from '../../components/MapResetTools';
import ClusterDeivceAndPlaceLayer from '../../components/ClusterDeivceAndPlaceLayer';
import { providerMap } from '../../providerMap';
import { map } from '../../mapContext';
import '../../style/map-select-device-and-place.less';
import DeviceList from "../../../DeviceList";
import PlaceTree from "../../../PlaceTree";
import DeviceAndPlace from '../../../DeviceAndPlace'
import { BaseStore } from '@zenview/micro-basic-library';
import { computPlaceTreeHasUnknown } from './util'

@providerMap('lm-tl-map-select-device-and-place')
@map
class MapSelectDeviceAndPlace extends React.Component {
  constructor(props) {
    super(props);
    this.mouseTool = null;
    this.clusterLayerRef = React.createRef();
    this.dataPoints = this.getPoints(); // 点位集合
    this.state = {
      deviceSelectedKeys: props.deviceKeys || props.defaultDeviceKeys || [],
      placeSelectedKeys: props.placeKeys || props.defaultPlaceKeys || [],
      deviceKeywords: '', // 设备关键字搜索
      deviceListKey: Math.random(), // 用于刷新设备列表
      placeTreeKey: Math.random(), // 用于刷新场所树
    };
  }

  drawStart = () => {
    const { mapMethods } = this.props;
    mapMethods.setSelectCursor();
  };

  drawEnd = (path, isCircle) => {
    const { mapMethods } = this.props;
    const { deviceSelectedKeys = [], placeSelectedKeys = [] } = this.state;
    const points = this.clusterLayerRef.current.getAllClusterPoints();
    let selectPoints = [];
    if (isCircle) {
      selectPoints = mapMethods.computedPointsInCircle(points, path.center, path.radius);
    } else {
      selectPoints = mapMethods.computedPointsInArea(points, path);
    }
    let deviceKeys = [],
      placeKeys = [];
    selectPoints.forEach((v) => {
      if (v.pointDataType === 'place') {
        placeKeys.push(v.areaCode);
      } else {
        deviceKeys.push(v.id);
      }
    });
    const listDeviceKeys = uniqBy([...deviceKeys, ...deviceSelectedKeys]);
    const listPlaceKeys = uniqBy([...placeKeys, ...placeSelectedKeys]);
    this.setState({ deviceSelectedKeys: listDeviceKeys, placeSelectedKeys: listPlaceKeys });
    mapMethods.resetCursor();
    this.props.onChange &&
      this.props.onChange({
        devices: listDeviceKeys,
        places: listPlaceKeys,
      });
  };

  clearDraw = (isUnmount) => {
    this.setState({ deviceSelectedKeys: [], placeSelectedKeys: [] });
    if (!isUnmount) {
      this.props.onChange &&
        this.props.onChange({
          devices: [],
          places: [],
        });
    }
  };

  mapReset = () => {
    this.clusterLayerRef.current.mapReset();
  };

  onChangeDeviceKeywords = (deviceKeywords) => {
    this.setState({ deviceKeywords });
  };

  // 摄像机列表选中 (选中后同步到右侧组件，同时同步的设备全部选中)
  checkListDevices = (deviceSelectedKeys) => {
    this.setState({ deviceSelectedKeys });
    this.props.onChange &&
      this.props.onChange({
        devices: deviceSelectedKeys,
        places: this.state.placeSelectedKeys,
      });
  };

  // 获取设备列表，通过关键字过滤设备
  getDeviceList = () => {
    const { deviceData = [] } = this.props.dataPoint;
    let { placeSelectedKeys, deviceKeywords } = this.state;
    let deviceList = [...deviceData];
    let levelOver5 = [],
      levelLower5 = [];
    BaseStore.place.getPlaceInfoByCodes(placeSelectedKeys || []).forEach((v) => {
      if (v.level >= 5) {
        levelOver5.push(v.placeId);
      } else {
        levelLower5.push(v.placeId);
      }
    });
    if (levelOver5.length === 0 && levelLower5.length === 0 && !deviceKeywords) {
      return deviceList; // 没有选中设备且没有搜索时
    }
    if (Array.isArray(levelLower5) && levelLower5.length > 0) {
      // 根据行政区域和关键字筛选
      deviceList = deviceList.filter((v) => levelLower5.includes(v.placeId));
    }
    if (deviceKeywords) {
      deviceList = deviceList.filter((v) => {
        let name = v.name || v.deviceName || v.realName;
        return !!name ? name.indexOf(deviceKeywords) > -1 : false;
      });
    }
    return deviceList;
  };

  // 将场所和设备组合一起，pointDataType区分
  getPoints = () => {
    const { placeData = [], deviceData = [] } = this.props.dataPoint;
    let placeList = [];
    placeData.forEach((v) => {
      if (v.level >= 5) {
        const [longitude, latitude] = v.center.split(',');
        placeList.push({ ...v, longitude, latitude, pointDataType: 'place' });
      }
    });
    return [...placeList, ...deviceData];
  };

  // 选中组织
  onCheckAssign = (keys) => {
    this.setState({
      placeSelectedKeys: keys,
      deviceListKey: Math.random(),
    });
    this.props.onChange &&
      this.props.onChange({
        devices: this.state.deviceSelectedKeys,
        places: keys,
      });
  };

  // 获取全部已经选中的地点
  getAreaPoinst = () => {
    const { placeSelectedKeys, deviceSelectedKeys } = this.state;
    let deviceArray = [], placeArray = [];
    BaseStore.device.getDeviceByIds(deviceSelectedKeys || []).map(v => {
      deviceArray.push({
        ...v,
        itemKey: v.id,
        itemName: v.deviceName
      })
    })
    BaseStore.place.getPlaceInfoByCodes(placeSelectedKeys || []).forEach(v => {
      if(v.level >= 5){
        placeArray.push({ ...v, pointDataType: 'place', itemKey: v.areaCode, itemName: v.areaName });
      }
    });
    return [...placeArray, ...deviceArray];
  }

  // 右侧列表取消选中
  cancelChecked = keys => {
    // 根据key的长度判断当前是设备还是场所
    let deviceSelectedKeys = [], placeSelectedKeys = [];
    keys.forEach( v => {
      if(v.length >= 17){
        deviceSelectedKeys.push(v);
      }else{
        placeSelectedKeys.push( v);
      }
    })
    this.setState({
      deviceSelectedKeys,
      placeSelectedKeys,
    })
    this.props.onChange &&
      this.props.onChange({
        devices: deviceSelectedKeys,
        places: placeSelectedKeys,
      });
  }

  render() {
    const { deviceSelectedKeys = [], deviceKeywords, placeSelectedKeys, deviceListKey, placeTreeKey } = this.state;
    const { title, dataPoint = {} } = this.props; //,...props
    const { placeData = [], deviceData } = dataPoint;
    const deviceList = this.getDeviceList(); // 设备列表
    let treeData = computPlaceTreeHasUnknown(placeData);
    const areaList = this.getAreaPoinst();
    return (
      <React.Fragment>
        <ClusterDeivceAndPlaceLayer autoView={false} points={this.dataPoints} ref={this.clusterLayerRef} />
        <DrawTools drawStart={this.drawStart} clearDraw={this.clearDraw} drawEnd={this.drawEnd} />
        <MapResetTools mapReset={this.mapReset} />
        <div className="device-place-box-container">
          <div className="place-and-devices-selected-box">
            <PlaceTree 
              checkable={true} 
              onCheck={this.onCheckAssign} 
              checkedKeys={placeSelectedKeys} 
              treeData={treeData} 
              key={placeTreeKey}
            />
            <DeviceList
              className="tl-device-list"
              deviceList={deviceList}
              checkable={true}
              title={`${title || '摄像机列表'}(已选${deviceSelectedKeys.length}个)`}
              onChange={this.onChangeDeviceKeywords}
              onChecked={this.checkListDevices}
              checkedKeys={deviceSelectedKeys}
              keywords={deviceKeywords}
              key={deviceListKey}
            />
          </div>
          <div className="selectd-right-box">
            <DeviceAndPlace
              deviceList={areaList}
              checkable={true}
              title={`已选地点(${areaList.length}个)`}
              onChecked={this.cancelChecked}
              checkedKeys={areaList.map(v => v.itemKey)}
            />
          </div>
        </div>
      </React.Fragment>
    );
  }
}

export default MapSelectDeviceAndPlace;
