import obj from '#/utils/obj'

import { get, post, postMultipart } from '../http'
import { only_last_id } from '../only-last'

export type FindPageResponse = {
  current: number
  rows: any[]
  size: number
  totalPage: number
  totalRows: number
}

export abstract class BasicService {
  // 分页查询
  async findPage(
    current: number,
    size: number,
    condition: any,
  ): Promise<FindPageResponse> {
    const data = await get<FindPageResponse>(this.findPageUrl(), {
      size,
      current,
      ...condition,
    })
    const list = this.switchKeyValues()
    if (data?.rows?.length && list.length) {
      for (const entity of data.rows) {
        for (const item of list) {
          if (!Array.isArray(item.key)) {
            item.key = [item.key]
          }
          for (const key of item.key) {
            entity[key] = obj.isEqualIgnoreNumberString(
              entity[key],
              item.trueValue,
            )
          }
        }
      }
    }
    return data
  }

  // id、id[]
  async remove(ids: any): Promise<any> {
    ids = this.getIdsList(ids)
    return await post(this.removeUrl(), ids)
  }

  // 增/改（自动根据id判断）
  async saveOrUpdate(entity: any) {
    const url = this.saveOrUpdateUrl()
    const config = (await this.willUpdateSwitchKeyValues(url, entity)) as any
    if (this.saveOrUpdateMultipart()) {
      return await postMultipart(url, entity, config)
    }
    return await post(url, entity, config)
  }

  protected abstract findPageUrl(): string

  protected getIdsList(ids: any) {
    if (!Array.isArray(ids)) {
      ids = [ids]
    }
    return ids
  }

  protected abstract removeUrl(): string

  protected saveOrUpdateMultipart(): boolean {
    return false
  }

  protected abstract saveOrUpdateUrl(): string

  protected switchKeyValues(): { falseValue: any; key: any; trueValue: any }[] {
    return []
  }

  protected async willUpdateSwitchKeyValues(url: string, data: any) {
    const list = this.switchKeyValues()
    let updateCount = 0
    if (list.length) {
      for (const item of list) {
        if (!Array.isArray(item.key)) {
          item.key = [item.key]
        }
        for (const key of item.key) {
          if (data[key] === undefined) continue
          data[key] = data[key] ? item.trueValue : item.falseValue
          updateCount += 1
        }
      }
    }
    let config = undefined as any
    if (data.id && Object.keys(data).length - 1 === updateCount) {
      // 要防止频繁请求
      config = {
        [only_last_id]: url,
      }
    }
    return config
  }
}
