import { useCallback, useState, useRef } from "react";

const formateArroundTag = str => (str || '').split(',').filter(Boolean).map(x => ({name: x}));

export default function useArrounds() {
  const [arrounds, setArrounds] = useState({})

  // 用来初始化数据库数据
  const initArrounds = useCallback((data) => {
    const tags = {
      buildingTransport: formateArroundTag(data.buildingTransport),
      buildingMall: formateArroundTag(data.buildingMall),
      buildingEdu: formateArroundTag(data.buildingEdu),
      buildingHospital: formateArroundTag(data.buildingHospital),
      buildingBank: formateArroundTag(data.buildingBank),
      buildingRestaurant: formateArroundTag(data.buildingRestaurant),
    }

    setArrounds(tags)
  }, [])

  // 用于周边 onChange 事件
  const updateArrounds = useCallback((key, vals) => {
    debugger
    setArrounds({
      ...arrounds,
      [key]: vals || [],
    })
  }, [arrounds])

  // 主要用户单个 tag 删除
  const deleteArround = useCallback((key, tag) => {
    if (!arrounds[key] || !arrounds[key].length) return;

    const leftArrounds = arrounds[key].filter((x) => x.name !== tag.name)

    setArrounds({
      ...arrounds,
      [key]: leftArrounds,
    })
  }, [arrounds])

  return [
    arrounds,
    initArrounds,
    updateArrounds,
    deleteArround,
  ]
}
