import { watch, computed, nextTick } from 'vue'
import { ajax, api } from '@/ajax'
import store from '@/store'
import smStar from '@/assets/images/star-sm.png'
import star from '@/assets/images/star.png'

export default function useSwitchMap(map: any): any {
  const curMapType = computed(() => store.state.curMapType)
  const curViewType = computed(() => store.state.curView.type)
  watch(
    () => curMapType.value,
    (type) => {
      if (!map.value) return
      map.value.initMap({ viewMode: type })
    },
    { immediate: true }
  )
  watch(
    () => store.state.showCommunityPoints,
    (val) => {
      val ? setPointsAndBoundary(curViewType.value) : map.value.hideCommunity()
    }
  )
  watch(
    () => curViewType.value,
    (type) => {
      store.commit('SET_SHOW_COMMUNITY_POINTS', false)
      setPointsAndBoundary(type)
      if (areaLines && areaLines.length > 0) {
        map.value.remove(areaLines)
      }
      if (curMapType.value === '2D') return
      store.commit('SET_MAP_TYPE', '2D')
    }
  )
  let boundary: any = null
  // 根据条件显示小区点和添加边界
  function setPointsAndBoundary(type: string) {
    if (!map.value) return
    boundary && boundary.remove()
    const show = store.state.showCommunityPoints
    switch (type) {
      case 'work1':
        show && showPoints({ gridId: store.state.workArea1.id })
        boundary = map.value.addBoundary({
          type: 'jwh_boundary',
          name: '第一',
          color: 'rgba(0,0,0,0)',
        })
        map.value.focus(...store.state.workArea1.center, 8)
        break
      case 'work2':
        show && showPoints({ gridId: store.state.workArea2.id })
        boundary = map.value.addBoundary({
          type: 'jwh_boundary',
          name: '第二',
          color: 'rgba(0,0,0,0)',
        })
        map.value.focus(...store.state.workArea2.center, 8)
        break
      case 'work3':
        show && showPoints({ gridId: store.state.workArea3.id })
        boundary = map.value.addBoundary({
          type: 'jwh_boundary',
          name: '第三',
          color: 'rgba(0,0,0,0)',
        })
        map.value.focus(...store.state.workArea3.center, 8)
        break
      case 'street':
        show && showPoints()
        boundary = map.value.addBoundary({
          name: '南京东路街道',
          color: 'rgba(0,0,0,0)',
        })
        map.value.focus(207.9006154792994, 71.67111885454233, 8)
        break
      default:
        break
    }
  }
  async function showPoints(params = {}) {
    const { content } = (
      await ajax.get({ url: api.GET_COMMUNITY_IDS, params })
    ).data
    map.value.setFilter(content)
    map.value.showCommunity()
  }

  // 工作站勾边
  let areaLines: any = null
  const selectArea = (e: any) => {
    map.value.remove(areaLines)
    areaLines = e.map(
      (
        name:
          | 'workArea1'
          | 'workArea2'
          | 'workArea3'
          | 'zhenxing'
          | 'weihai'
          | null
      ) => {
        if (!name) return
        let color = '#FF6161'
        if (name.indexOf('workArea') >= 0) {
          color = '#FFCE34'
        }
        return map.value.addPolyLine({
          key: name,
          paths: store.state[name].paths,
          strokeColor: color,
        })
      }
    )
  }
  const handleZoom = (type: string) => {
    map.value.zoom(type)
  }

  const curPointType = computed(() => store.state.curPointType)
  const checkedKeys = computed(() => store.state.checkedKeys)

  const handleMapComplete = async () => {
    setPointsAndBoundary(curViewType.value)
    if (curMapType.value === '3D') {
      if (curViewType.value === 'work1') {
        map.value.layer('model_white_zw').visible = false
        map.value.layer('model_white_dyjd').visible = true // 第一街道名
      } else {
        map.value.layer('model_white_zw').visible = true
        map.value.layer('model_white_dyjd').visible = false
      }
    }
    await nextTick()
    handlePoint(curPointType.value, checkedKeys.value)
  }

  // 撒点相关
  watch(
    [() => curPointType.value, () => checkedKeys.value],
    ([type, keys], [pastType, pastKeys]) => {
      if (type === pastType && keys.join() === pastKeys.join()) return
      handlePoint(type, keys)
    }
  )
  const ecologyPoints = computed(() => store.state.ecologyPoints)
  let mapPoints: any = null
  const emergencyPoints = computed(() => store.state.emergencyPoints)
  let mapEmergency: any = null
  function handlePoint(type: null | string, keys: string[]) {
    if (!map.value) return
    const { showCommunity, hideCommunity, addPoint, remove } = map.value

    if (keys.length === 0) {
      hideCommunity()
      remove(mapPoints)
      return
    }

    const pointData = type
      ? ecologyPoints.value.filter((e) => e.labelName === type)
      : ecologyPoints.value

    if (keys.some((key) => key === 'community')) {
      showCommunity()
    } else {
      hideCommunity()
    }
    const yiPoints = pointData.filter((e) => e.labelName === '衣')
    const shiPoints = pointData.filter((e) => e.labelName === '食')
    const zhuPoints = pointData.filter((e) => e.labelName === '住')
    const xingPoints = pointData.filter((e) => e.labelName === '行')
    const otherPoints = pointData.filter((e) => e._type === 'other')
    // const oldPoints = []
    // const signPoints = []
    // const historyPoints = []

    remove(mapEmergency)
    remove(mapPoints)
    mapPoints = addPoint({
      key: 'map-points',
      size: 20,
      data: [
        ...(keys.some((key) => key === 'yi') ? yiPoints : []),
        ...(keys.some((key) => key === 'shi') ? shiPoints : []),
        ...(keys.some((key) => key === 'zhu') ? zhuPoints : []),
        ...(keys.some((key) => key === 'xing') ? xingPoints : []),
        ...(keys.some((key) => key === 'other') ? otherPoints : []),
        {
          icon: star,
          '479477007408168960': '上海市人民政府',
          stAddr: '人民大道200号',
          belong: '第一工作站',
          x: 130.78,
          y: -433.2,
        },
        {
          icon: smStar,
          '479477007408168960': '南京东路街道',
          stAddr: '大沽路123号',
          belong: '第一工作站',
          x: 17.95,
          y: -788.21,
        },
      ],
    })
  }

  watch(
    () => emergencyPoints.value,
    (points) => {
      if (points.length === 0 || !map.value) return
      const { addPoint, remove } = map.value
      remove(mapEmergency)
      remove(mapPoints)
      store.commit('SET_CHECKED_KEYS', [])
      mapEmergency = addPoint({
        key: 'map-emergency',
        size: 14,
        data: points,
      })
    }
  )

  return {
    handleMapComplete,
    selectArea,
    handleZoom,
  }
}
