import { reactive } from 'vue'
import { postMessage } from './native-message'
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',
  MUSIC_FREE: 'music-list-free'
}
/**
 * 获取声部编号 | 保存声部编号
 */
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
}

const eventTracks = {
  专辑: 'klx_album',
  视频课: 'klx_videoClass',
  直播课: 'klx_liveClass',
  达人风采: 'klx_talentElegant',
  热门资讯: 'klx_hotInformation',
  小酷AI功能埋点: 'klx_xiaokuAI',
  我的乐谱: 'klx_myMusic',
  评测记录: 'klx_myEvaluation',
  订单: 'klx_myOrder',
  交易记录: 'klx_myTrade',
  优惠券: 'klx_myCoupon',
  帮助中心: 'klx_helpCenter',
  商品列表: 'klx_goods',
  商品详情: 'klx_goodDetail',
  购买支付: 'klx_payment',
  取消支付: 'klx_cancelPayment'
}
type eventName =
  | '专辑'
  | '视频课'
  | '直播课'
  | '达人风采'
  | '热门资讯'
  | '小酷AI功能埋点'
  | '我的乐谱'
  | '评测记录'
  | '订单'
  | '交易记录'
  | '优惠券'
  | '帮助中心'
  | '商品列表'
  | '商品详情'
  | '购买支付'
  | '取消支付'

/**
 * 事件埋点
 */
export const useEventTracking = (name: eventName) => {
  postMessage({
    api: 'setEventTracking',
    content: {
      type: eventTracks[name]
    }
  })
}
