import { getNewsTop, getProvinceInitialization, getNewsDetailInfo } from '@/service/index/api'
import { useCityStore } from '@/store/city'
import { useUserStore } from '@/store/user'
import { City, News, NewsDetail } from '@/types/app-type'
import { pinyin } from 'pinyin-pro'

interface Province {
  provincename: string
}

const cityStore = useCityStore()
const userStore = useUserStore()

export const cities = []
export const useCityInfo = () => {
  getProvinceInitialization().then((res) => {
    if (res.result) {
      const list = res.result as Province[]
      const li = groupByFirstLetter(list)
      cityStore.setCities(li)
      const defaultCity = list.filter((item) => item.provincename === '山东省')[0] as City
      if (userStore.userInfo.city?.code === '0') {
        userStore.setUserCity(defaultCity)
      }
    }
  })
}

// 按照首字母分组
const groupByFirstLetter = (lis: Province[]): { letter: string; provinces: Province[] }[] => {
  const grouped: { [key: string]: Province[] } = {}

  for (let i = 0; i < lis.length; i++) {
    const firstLetter = pinyin(lis[i].provincename, {
      pattern: 'first',
      toneType: 'none',
    })[0].toUpperCase()

    if (!grouped[firstLetter]) {
      grouped[firstLetter] = []
    }

    grouped[firstLetter].push(lis[i])
  }

  return Object.keys(grouped)
    .sort()
    .map((key) => ({ letter: key, provinces: grouped[key] }))
}

export const newsList = ref<News[]>([])
export const useCityNewTop = () => {
  const fetchNewTopFun = (provinceCode: string) => {
    getNewsTop({ Top: 4, CategoryId: 1, provinceCode }).then((res) => {
      if (res.code === 200) {
        newsList.value = res.result as News[]
      }
    })
  }

  if (userStore.userInfo.city.code === '0') {
    userStore.$subscribe((mutation, state) => {
      if ((mutation.events as { key: string }).key === 'city') {
        fetchNewTopFun(state.userInfo.city.code)
      }
    })
  } else {
    fetchNewTopFun(userStore.userInfo.city.code)
  }
}

export const newsDetail = ref<NewsDetail>({
  coverImg: '',
  createTime: '',
  id: 0,
  summary: '',
  title: '',
  author: '',
  click: 0,
  detail: '',
})
export const useCityNewDetail = (id: number) => {
  getNewsDetailInfo({ id }).then((res) => {
    if (res.code === 200) {
      newsDetail.value = res.result as NewsDetail
    }
  })
}
