import { reactive } from 'vue'
import request from './request'

// 搜索关键字
export const SubjectEnum = {
  SEARCH: 'music-songbook-subject',
  ALBUM: 'music-album-subject',
  MUSIC: 'music-subject',
  LIVE: 'live-subject',
  VIDEO: 'video-subject',
  ELEGANT: 'elegant-subject'
}
/**
 * 获取声部编号 | 保存声部编号
 */
export const useSubjectId = (
  key: string,
  value?: any,
  type = 'get' as 'get' | 'set'
) => {
  // 判断是否在关键字
  // console.log(key, value, type)
  if (!key) return ''
  if (type === 'get') {
    let subject = localStorage.getItem(key)
    subject = subject ? JSON.parse(subject) : { name: '', id: '' }
    return subject
  } else {
    localStorage.setItem(key, value)
    return ''
  }
}

interface IList {
  params?: any
  requestType?: 'json' | 'form'
  loading: boolean
  list: any[]
  dataShow: boolean
  finished: boolean
}

let lockLoad = false
/*
 * 列表获取数据
 * @param url 请求地址
 * @returns {Promise<IList>}
 */
export const useList = async (
  url: string,
  params: IList,
  method = 'POST' as 'POST' | 'GET'
) => {
  try {
    if (lockLoad) return params
    // 上锁
    lockLoad = true
    const res =
      method === 'POST'
        ? await request.post(url, {
            requestType: params.requestType || 'json',
            data: {
              ...params.params
            }
          })
        : await request.get(url, {
            requestType: params.requestType || 'json',
            params: {
              ...params.params
            }
          })
    params.loading = false
    const result = res.data || {}
    params.list = params.list.concat(result.rows || [])
    params.finished = result.pageNo >= result.totalPage
    params.params.page = result.pageNo + 1
    params.dataShow = params.list.length > 0
  } catch {
    params.dataShow = false
    params.finished = true
  }
  // 解锁
  lockLoad = false
  return params
}
