import { axios } from '../utils/request'
import {Modal as MessageUtil} from "ant-design-vue";
import YchConstant from "./YchConstant";
import TokenStorageUtil from "./TokenStorageUtil";
import LocleUtil from "./LocleUtil";

const api = {
  user: '/api/user',
  role: '/api/role',
  service: '/api/service',
  permission: '/api/permission',
  permissionNoPager: '/api/permission/no-pager'
}

export default api

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

export function httpAction(url,parameter,method) {
  return axios({
    url: url,
    method:method ,
    data: parameter
  })
}

//put
export function putAction(url,parameter) {
  return axios({
    url: url,
    method:'put',
    data: parameter
  })
}

//get
export function getAction(url,parameter) {
  return axios({
    url: url,
    method: 'get',
    params: parameter
  })
}

//deleteAction
export function deleteAction(url,parameter) {
  return axios({
    url: url,
    method: 'delete',
    params: parameter
  })
}


/**
 * 下载文件 用于excel导出
 * @param url
 * @param parameter
 * @returns {*}
 */
export function downFile(url,parameter, method){
  return axios({
    url: url,
    params: (!method || method.toLowerCase() == "get") ? parameter : {},
    data: (method && method.toLowerCase() == "post") ? parameter : {},
    method: method || 'get',
    responseType: 'blob'
  })
}

/**
 * 下载文件
 * @param url 文件路径
 * @param fileName 文件名
 * @param parameter
 * @returns {*}
 */
export function downloadFile(url, fileName, parameter, method) {
  return downFile(url, parameter, method).then((data) => {
    if (!data || data.size === 0) {
      return
    }
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([data]), fileName)
    } else {
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) //下载完成移除元素
      window.URL.revokeObjectURL(url) //释放掉blob对象
    }
  })
}

/**
 * 文件上传 用于富文本上传图片
 * @param url
 * @param parameter
 * @returns {*}
 */
export function uploadAction(url,parameter){
  return axios({
    url: url,
    data: parameter,
    method:'post' ,
    headers: {
      'Content-Type': 'multipart/form-data',  // 文件上传
    },
  })
}

/**
 * 获取文件服务访问路径
 * @param avatar
 * @returns {*}
 */
export function getFileAccessHttpUrl(avatar) {
  if (avatar && (avatar.startsWith('http') || avatar.startsWith('https'))) {
    return avatar;
  } else {
    if (avatar && avatar.length > 0 && avatar.indexOf('[') === -1 && avatar !== 'null') {
      // 统一从nginx或vue.config.js中转发，减少后台开放接口
      // let baseUrl = location.protocol + "//" + location.host
      // return baseUrl + "/api/system/common/static/" + avatar;
      const staticUrl = YchConstant.PREFIX_REQUEST + '/api/system/common/static'
      if (staticUrl && !avatar.startsWith(staticUrl)) {
        return staticUrl + "/" + avatar;
      }
    }
  }
  return avatar
}

export function uidGenerator(){
  return '-' + parseInt(Math.random() * 10000 + 1, 10);
}
export function getFileName(path){
  if (path.lastIndexOf("\\") >= 0) {
    let reg = new RegExp("\\\\", "g");
    path = path.replace(reg, "/");
  }
  return path.substring(path.lastIndexOf("/") + 1);
}

/**
 * TODO 判断是否允许当前环境编辑设计器脚本
 * 用于防止线上环境的一些危险操作被使用
 * @param noWarning 不允许编辑时不显示提示信息，返回reject
 * true 标识允许； false 标识禁止
 * @returns {Promise<unknown>}
 */
export function allowEditScript(noWarning) {
  return new Promise((resolve,reject) => {
    getAction(YchConstant.PREFIX_SYSTEM + '/permission/allowEditScript').then(res => {
      if (res.result === true) {
        resolve()
      } else {
        if(noWarning){
          reject()
        }else{
          MessageUtil.warning(LocleUtil.getLocale('m.common.tip.disabled_current_action'))
        }

      }
    })
  })
}

/**
 * 加密下载文件
 * @param url
 * @param parameter
 * @returns {*}
 */
export function encryptedDownload(file){
  const url = YchConstant.PREFIX_SYSTEM + '/ftxt/encryptedDownload';
  const method = 'GET';
  const parameter = {fileUrl:file.url}
  const fileName = file.name

  return downFile(url, parameter, method).then((data) => {
    //文件为空的时候走blod直接下载
    if (!data || data.size === 0) {
      const x = new XMLHttpRequest();
      console.log(file)
      x.open("GET", getFileAccessHttpUrl(file.url || file.thumbUrl), true);
      x.responseType = 'blob';

      const token = TokenStorageUtil.get();
      x.setRequestHeader('X-Access-Token', token);

      x.onload = function (e) {
        const url = window.URL.createObjectURL(x.response);
        const a = document.createElement("a");
        a.href = url
        a.download = fileName
        a.click()
      }
      x.send();
      return
    }
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([data]), fileName)
    } else {
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) //下载完成移除元素
      window.URL.revokeObjectURL(url) //释放掉blob对象
    }
  })
}
