import React from "react";
import DrawTools from "../../components/DrawTools";
import MapResetTools from "../../components/MapResetTools";
import SearchPio from "../../components/SearchPio";
import ClusterLayer from "../../components/ClusterLayer";
import { providerMap } from "../../providerMap";
import { map } from "../../mapContext";
import * as _ from "lodash";
import "../../style/select-map.less";
import * as L from 'leaflet';
import DeviceList from "../../../DeviceList";

import {BaseStore} from '@zenview/micro-basic-library';


@providerMap("map-select-layout")
@map
class SelectMap extends React.Component {
  constructor(props) {
    super(props);
    this.mouseTool = null;
    this.clusterLayerRef = React.createRef();
    this.state = {
      selectKeys: props.selectKeys || props.defaultSelectKeys,
      keyword: null,
      listSelectKeys: props.selectKeys || props.defaultSelectKeys
    };
  }
  static getDerivedStateFromProps(props, state) {
    const options = {};
    if (props.defaultSelectKeys) {
      if (!state.selectKeys) {
        options.selectKeys = props.defaultSelectKeys;
      }
      if (!state.listSelectKeys) {
        options.listSelectKeys = props.defaultSelectKeys;
      }
    }
    if (props.selectKeys) {
      options.listSelectKeys = props.selectKeys;
    }
    return _.isEmpty(options) ? null : options;
  }
  componentWillUnmount() {
    this.mouseTool = null;
  }

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

  drawEnd = (path, isCircle) => {
    const { mapMethods } = this.props;
    const { selectKeys = [], listSelectKeys = [] } = this.state;
    const points = this.clusterLayerRef.current.getAllClusterPoints();
    let selectPoints = [];
    if (isCircle) {
      selectPoints = mapMethods.computedPointsInCircle(points, path.center, path.radius).map(v => v.id);
    } else {
      selectPoints = mapMethods.computedPointsInArea(points, path).map(v => v.id);
    }
    const keys = _.uniqBy([...selectPoints, ...selectKeys]);
    const listKeys = _.uniqBy([...selectPoints, ...listSelectKeys]);
    this.setState({ selectKeys: keys, listSelectKeys: listKeys });
    mapMethods.resetCursor();
    this.props.onChange && this.props.onChange(listKeys);
  };

  clearDraw = (isUnmount) => {
    this.setState({ selectKeys: [], listSelectKeys: [] });
    if(!isUnmount){
      this.props.onChange && this.props.onChange([]);
    }
  };

  getSelectList(ids) {
    const { keyword } = this.state;
    let deviceList = BaseStore.device.getDeviceByIds(ids);
    if (keyword) {
      deviceList = deviceList.filter(v => {
        let name = v.name || v.deviceName || v.realName;
        return !!name ? name.indexOf(keyword) > -1 : false;
      });
    }
    return deviceList;
  }

  /**
   * 列表操作导致select改变
   */
  onChecked = ids => {
    this.setState({ listSelectKeys: ids });
    this.props.onChange && this.props.onChange(ids);
  };

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

  onChangeKeywords = keyword => {
    this.setState({ keyword });
  };

  markerClick = item => {
    const selectKeys = _.cloneDeep(this.state.selectKeys) || [];
    const listSelectKeys = _.cloneDeep(this.state.listSelectKeys) || [];
    if (selectKeys.indexOf(item.id) === -1) {
      selectKeys.push(item.id);
    }
    if (listSelectKeys.indexOf(item.id) === -1) {
      listSelectKeys.push(item.id);
    }
    this.setState({
      selectKeys: _.uniq([...selectKeys]),
      listSelectKeys: _.uniq([...listSelectKeys])
    });
    this.props.onChange && this.props.onChange(listSelectKeys);
  };
  getCenter = item => {
    const { mapMethods ,mapConfig} = this.props;
    const latlng = L.latLng({ lat: item.latitude, lng: item.longitude })
    const {maxZoom} = mapConfig
    mapMethods.setZoomAndCenter(maxZoom-2,latlng);
  }

  render() {
    const { selectKeys = [], listSelectKeys = [], keyword } = this.state;
    const { points, title, markerClick,cameraList } = this.props; //,...props
    const deviceList = this.getSelectList(selectKeys);
    return (
      <React.Fragment>
        <ClusterLayer points={points} ref={this.clusterLayerRef} markerClick={markerClick} />
        <SearchPio getCenter={this.getCenter}/>
        <DrawTools drawStart={this.drawStart} clearDraw={this.clearDraw} drawEnd={this.drawEnd} init={this.initDrawTools} />
        {selectKeys.length > 0 && (
          <DeviceList
            style={{ width: 300, height: "calc(100% - 76px - 20px)" }}
            className="device-list-layout"
            deviceList={cameraList?cameraList:deviceList}
            checkedKeys={listSelectKeys}
            checkable={true}
            title={`${title || "已选摄像机"}(${listSelectKeys.length}个)`}
            onChecked={this.onChecked}
            onChange={this.onChangeKeywords}
            keywords={keyword}
          />
        )}
        <MapResetTools mapReset={this.mapReset} />
      </React.Fragment>
    );
  }
}
export default SelectMap;
