import { axios } from '@/utils/request'

export function login (parameter) {
  return axios({
    url: '/auth/login',
    method: 'post',
    data: parameter
  })
}

export const listLookUp = params => {
  let url = `/lookup/queryLike`
  return axios({
    url: url,
    data: params,
    method: 'POST'
  })
}

export const getLookUpData = (params) => {
  let url = `/lookupItem/query/${params.pageNo}/${params.pageSize}`
  delete params.pageNo
  delete params.pageSize
  return axios({
    url: url,
    data: params,
    method: 'post'
  })
}

export const getAreaAll = () => {
  return axios({
    url: '/area/findAll',
    method: 'get'
  }).then(res => res.data)
}

/**
 * 获取ali OSS 上传签名
 * @returns {Q.Promise<any> | * | Q.Promise<T | never> | PromiseLike<T | never> | Promise<T | never>}
 */
export const getOSSToken = (params) => {
  return axios({
    url: `ossUpload?bizType=${params.bizType}`,
    method: 'get'
  })
}

/**
 * 上传文件到阿里OSS
 * @param params
 * @returns {Q.Promise<any> | * | Q.Promise<T | never> | PromiseLike<T | never> | Promise<T | never>}
 */
export const uploadOSS = (params) => {
  return axios({
    // url: params.url,
    url: 'ossUploadFile',
    method: 'post',
    data: params.data,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 上传文件到阿里OSS
 * @param params
 * @returns {Q.Promise<any> | * | Q.Promise<T | never> | PromiseLike<T | never> | Promise<T | never>}
 */
export const uploadImgOnce = (bizType, params) => {
  return getOSSToken({
    bizType
  }).then(config => {
    const fileName = createFileName(params.name)
    const _data = new FormData()
    _data.append('key', config.dir + '/' + fileName)
    _data.append('name', fileName)
    _data.append('policy', config.policy)
    _data.append('OSSAccessKeyId', config['accessid'])
    _data.append('success_action_status', '200')
    _data.append('callback', config.callback)
    _data.append('signature', config.signature)
    _data.append('file', params)
    return uploadOSS({
      data: _data
    })
  })
}

function createFileName (filename) {
  const pos = filename.lastIndexOf('.')
  const suffix = filename.substring(pos)
  return randomStr(20) + suffix
}
function randomStr (len) {
  len = len || 32
  const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  const maxPos = chars.length
  let pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}
