import React, { useEffect,useCallback } from "react";
import {message} from 'antd';
import Modal from "./Modal";
import { useLoaded, useMap } from "../../util/hooks";
import { getCurrCity } from "../../data/getCurrCity";
import { CenterBtnGrp, OkBtn, CancelBtn } from "../../util/GeneralButton";
import CityList from "./city/CityList";
import SelectedCity from "./city/SelectedCity";
import { getHotCity } from "../../data/getHotCity";
import Loading from "../../util/Loading";

//visible, setValue, onCancel
export default ({ setValue, ...props }) => {
  const { isLoaded: isCurrCityLoaded, data: currCity } = useLoaded(
    getCurrCity,
    []
  );
  const { isLoaded: isCityLoaded, data: cityLst } = useLoaded(getHotCity, []);
  const { map, add, remove } = useMap((m) => {
    if (m.size >= 5) {
      message.error("最多选择5项");
      return false;
    }
    return true;
  });
  useEffect(() => {
    if (isCurrCityLoaded) {
      add(currCity, true);
    }
  }, [isCurrCityLoaded]);
  const onOk = useCallback(() => {
    props.onCancel();
    setValue(Array.from(map.keys()));
  }, []);
  const content =
    !isCurrCityLoaded || !isCityLoaded ? (
      <Loading />
    ) : (
      <React.Fragment>
        <SelectedCity selected={map} remove={remove} />
        <CityList select={add} data={cityLst} />
        <CenterBtnGrp style={{marginBottom:"20px"}}>
          <CancelBtn onClick={props.onCancel} />
          <OkBtn onClick={onOk} />
        </CenterBtnGrp>
      </React.Fragment>
    );
  return <Modal width="680px" {...props} getContainer={false}>
    {content}
  </Modal>;
};
