import { injectable, Service } from './service'

@injectable
export default class WeatherService extends Service {
  /**
   * 天气图标配置
   */
  private icons = [
    {
      name: '雨',
      icon: 'data:image/png;base64,[encoded data, 7964 characters]'
    },
    {
      name: '阴',
      icon: 'data:image/png;base64,[encoded data, 8224 characters]'
    },
    {
      name: '晴',
      icon: 'data:image/png;base64,[encoded data, 8004 characters]'
    },
    {
      name: '雪',
      icon: 'data:image/png;base64,[encoded data, 8704 characters]'
    },
    {
      name: '云',
      icon: 'data:image/png;base64,[encoded data, 8368 characters]'
    },
    {
      name: '雾',
      icon: 'data:image/png;base64,[encoded data, 8968 characters]'
    },
    {
      name: '沙',
      icon: 'data:image/png;base64,[encoded data, 8768 characters]'
    }
  ]

  /**
   * 获取当前城市天气预报
   * 天气图标请使用SVG+PATH
   *
   */
  async getWeather() {
    let weather = null
    const { info, adcode } = await new Promise<{ info: string, adcode: string }>((resolve, reject) => fetch('https://restapi.amap.com/v3/ip?key=76f9007ba8c4c44bb9ad757fe27acb44').then((res) => res.json()).then((res) => { resolve(res) }).catch((er) => reject(er)))
    if (info === 'OK') {
      const { info: Info, lives } = await new Promise<{ info: string, lives: any[] }>((resolve, reject) => fetch(`https://restapi.amap.com/v3/weather/weatherInfo?key=76f9007ba8c4c44bb9ad757fe27acb44&city=${adcode}`).then((res) => res.json()).then((res) => { resolve(res) }).catch((er) => reject(er)))
      if (Info === 'OK') {
        const obj = lives[0]
        obj.icon = this.icons.find((el) => obj.weather.indexOf(el.name) !== -1)?.icon
        weather = obj
      }
    }
    return weather
  }
}