import React from 'react';
import { connect } from 'dva';
import ACascader from '../../components/ACascader';
import allArea from './area.json';
import * as _ from 'lodash';

const fieldNames = { label: 'name', value: 'adcode', children: 'districts' };

function filterOpenedArea(customerList) {
  if (!customerList.length) return []
  const openedCity = [...new Set(customerList.map(item => `${item.city}`))];

  const res = allArea.filter(item => {
    const opened = item.districts.filter(city => {
      return openedCity.includes(city.adcode);
    });
    item.districts = opened;
    return opened.length > 0
  })
  return res;
}

// 映射地图中城市定位
const positionMap = {
  460000: '469001', // 海南省 -> 五台山
}

export default connect(({ screen }) => ({
  customerList: screen.customerList,
  company: screen.company
}))(
  React.memo(function Company(props) {
    const [popupVisible, setPopupVisible] = React.useState(false)
    const onChange = e => {
      setPopupVisible(false)
      if (e.length) {
        let position = e[e.length - 1];
        position = positionMap[position] || position;
        props.mapInstance.setCity(position, () => props.mapInstance.setZoom(9));
      } else {
        props.resetScale();
      }
      props.dispatch({
        type: 'screen/filterArea',
        payload: e
      })
      props.dispatch({type: 'overview/fetchRealTimeData', payload: {
          enterprise_id: props.company,
          province: e[0],
          city: e[1]
        }})
    };
    const openedArea = filterOpenedArea(props.customerList)

    return (
      <ACascader
        placeholder="选择地区"
        showSearch
        changeOnSelect
        popupVisible={popupVisible}
        onClick={() => setPopupVisible(true)}
        allowClear
        onChange={onChange}
        className="map-filter-area"
        fieldNames={fieldNames}
        options={openedArea}
      />
    );
  }),
);
