import baseAxios from '../index'
import { iOutLetDetail } from './types'

export default class AddressService {
  private prefix: string
  static instance: AddressService
  private max_len_gps: number
  static getInstance() {
    if (!AddressService.instance) {
      AddressService.instance = new AddressService()
    }
    return AddressService.instance
  }
  constructor() {
    this.prefix = '/address'
    this.max_len_gps = 10
  }

  getGpses(data: { addrs: string[] }): Promise<string[]> {
    return new Promise((resolve, reject) => {
      const resultList = [] as string[]
      if (data.addrs.length) {
        for (
          let i = 0;
          i < Math.ceil(data.addrs.length / this.max_len_gps);
          ++i
        ) {
          const reqList = data.addrs.slice(
            i * this.max_len_gps,
            i * this.max_len_gps + this.max_len_gps,
          )
          this.__getGpses(reqList).then((ret) => {
            if (ret.code === 200) {
              resultList.push(...ret.data.gps)
              if (resultList.length === data.addrs.length) {
                resolve(resultList)
              }
            } else {
              reject('解析错误')
            }
          })
        }
      }
    })
  }
  private __getGpses(addrs: string[]) {
    if (addrs.length > 10) {
      throw new Error('长度超过10')
    } else {
      return baseAxios<{ gps: string[] }>({
        url: this.prefix + '/getGps',
        method: 'post',
        data: {
          addrs: addrs,
        },
      })
    }
  }

  getOutlet(data: { outlet_name: string }) {
    return baseAxios<iOutLetDetail>({
      url: '/address/getOutlet',
      method: 'post',
      data,
    })
  }

  note(id: number) {
    return baseAxios({
      url: '/address/note',
      method: 'post',
      data: {
        id,
      },
    })
  }

  update(data: {
    id: number
    is_normal_work: boolean
    lat_lon: string
    location: string
    note: string
    opening_hours: string
    weekend_status: number
  }) {
    return baseAxios({
      url: '/address/update',
      method: 'post',
      data, 
    })
  }
}
