import {
  iGetList,
  iGetItem,
  iUpdateItem,
  iAddItem,
  iDeleteRecommend,
  iDeleteRecommends,
  iChangeShowStatus
} from '@/api/indexRecommend'

import listResult from '@/model/listResult'
import { translateLabel, setStatus } from '@/utils'

const getList = async data => listResult(await iGetList(data), x => ({
  id: x.id,
  sort: x.sort.toString(),
  title: x.title,
  url: x.url,
  imgUrl: process.env.VUE_APP_BASE_IMG + x.imgUrl,
  type: x.type,
  typeF: translateLabel(setStatus(['文章', '直播', '其他'], ['ARTICLE', 'LIVE_BROADCAST', 'OTHER']), x.type),
  isTop: x.isTop,
  isTopF: x.isTop ? '已置顶' : '未置顶',
  isShow: x.isShow,
  isShowF: x.isShow ? '已展示' : '未展示'
}))

const getArticleIdByParams = (str, type) => {
  if (type === 'ARTICLE') {
    const obj = JSON.parse(str)
    return obj.id
  }
  return ''
}

const getItem = async params => {
  const result = await iGetItem(params)
  if (result.success) {
    const data = result.data
    result.data = {
      article: getArticleIdByParams(data.params, data.type),
      params: data.params,
      type: data.type,
      imgFile: [{ url: `${process.env.VUE_APP_BASE_IMG}${data.imgUrl}` }], // [{ url: data.imgUrl }],
      isTop: data.isTop,
      isShow: data.isShow,
      sort: data.sort
    }
  }
  return result
}

const saveItem = async({ id, ...params }) => {
  if (id) {
    return await iUpdateItem(id, params)
  } else {
    return await iAddItem(params)
  }
}

const deleteRecommend = async params => await iDeleteRecommend(params)

const deleteRecommends = async params => await iDeleteRecommends(params)

const changeShowStatus = async params => await iChangeShowStatus(params)

export {
  getList,
  getItem,
  saveItem,
  deleteRecommend,
  deleteRecommends,
  changeShowStatus
}
