import { tenantRequest } from '@/utils/request'
import {
  update,
  del,
  submit,
  resolve,
  reject,
  addStatusScope,
  canDel
} from './base'
import { AssetType } from '@/constant'

export function getAssets (query) {
  const { pageNum: currentPage, pageSize: pageCount, ...params } = query
  return tenantRequest({
    url: '/minio-data/listByPage',
    method: 'POST',
    data: addStatusScope({
      currentPage, pageCount,
      ...params
    })
  }).then(({ data, totalCount }) => {
    data.forEach(asset => {
      if (asset.type === AssetType.IMAGE) {
        asset.thumbnail = asset.keyName
      } else if (asset.type === AssetType.VIDEO && asset.screenshot !== 'analyzing') {
        asset.thumbnail = asset.screenshot
      }
    })
    return { data, totalCount }
  })
}

export function getAssetsWithDel (query) {
  return getAssets(query).then(({ data, totalCount }) => {
    data.forEach(asset => {
      asset.del = canDel(asset)
    })
    return { data, totalCount }
  })
}

export function updateAsset (data) {
  return update({
    url: '/minio-data/update',
    method: 'POST',
    data
  })
}

export function deleteAsset ({ keyName, originalName }) {
  return del({
    url: '/minio-data/delete',
    method: 'DELETE',
    params: { keyName }
  }, originalName)
}

export function getAssetUrl (keyName) {
  return `${process.env.VUE_APP_MINIO}/${keyName}`
}

const LIMIT_SIZE = 1024 * 1024
export function getThumbnailUrl (item, ratio = 'x0.2,q30') {
  let url
  if (item && typeof item === 'object') {
    const { size, keyName } = item
    if (size <= LIMIT_SIZE) {
      return getAssetUrl(keyName)
    }
    url = getAssetUrl(keyName)
  } else {
    url = getAssetUrl(item)
  }
  if (url.charAt(0) === '/') {
    url = `${location.origin}${url}`
  }
  return `${process.env.VUE_APP_THUMBNAIL}/${ratio}/${url}`
}

export function submitAsset ({ keyName, originalName }) {
  return submit({
    url: '/minio-data/submit',
    method: 'GET',
    params: { keyName }
  }, originalName)
}

export function resolveAsset ({ keyName, originalName }) {
  return resolve({
    url: '/minio-data/reviewed',
    method: 'GET',
    params: { keyName }
  }, originalName)
}

export function rejectAsset ({ keyName, originalName }, reason) {
  return reject({
    url: '/minio-data/reject',
    method: 'GET',
    params: { keyName },
    data: { reason }
  }, originalName)
}
