import {Message} from "element-ui";
import fetch from "./fetch";
import storage from "@/framework/utils/storage";
import lStorage from '@/utils/localStorage';
import store from "@/store/index";

function successResponse(vm, response, success, failed) {
  let resp = response.data;
  let result = resp.result ? resp.result : resp.Result;
  if (result === "success") {
    if (success) {
      success(resp);
    }
  } else {
    let msg = resp.message
      ? resp.message
      : resp.ResultMsg || resp.resultMsg || resp.Message;
    Message.error({ message: msg });
    if (failed) {
      failed(resp);
    }
  }
}

function errorResponse(vm, response, err) {
  let json = JSON.parse(JSON.stringify(response));
  if (json.message === "路由调整取消请求") return;
  console.error(response);
  if (json.response) {
    Message.error({
      message: `接口：${json.response.config.url}请求错误，错误状态为：${json.response.status}`
    });
  } else {
    console.error(vm, response, err);
    Message.error({ message: "请求错误" });
  }
}

function downFile(blob, fileName) {
  // 非IE下载
  if ("download" in document.createElement("a")) {
    let link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob); // 创建下载的链接
    link.download = fileName; // 下载后文件名
    link.style.display = "none";
    document.body.appendChild(link);
    link.click(); // 点击下载
    window.URL.revokeObjectURL(link.href); // 释放掉blob对象
    document.body.removeChild(link); // 下载完成移除元素
  } else {
    // IE10+下载
    window.navigator.msSaveBlob(blob, fileName);
  }
}

export default {
  getJson: function(url, data, success, failed, err) {
    let ssoToken = store.state.ssoToken
      ? store.state.ssoToken
      : lStorage.get("ssoToken");
    let ProjectId = store.state.layout.projectId
      ? store.state.layout.projectId
      : lStorage.get("projectId");
    let userName = store.state.layout.userInfo.userName
      ? store.state.layout.userInfo.userName
      : storage.get("user_name");
    let group_code = store.state.layout.group_code
      ? store.state.layout.group_code
      : lStorage.get("group_code");
    let vm = this;
    fetch({
      url: url,
      method: "get",
      params: data,
      headers: {
        projectId: ProjectId,
        token: ssoToken,
        appId: "adm",
        userId: userName,
        groupCode: group_code
      }
    })
      .then(response => {
        successResponse(vm, response, success, failed);
      })
      .catch(error => {
        errorResponse(vm, error, err);
      });
  },
  postJson: function (url, data, success, failed, err, isShowPid) {
    let ssoToken = store.state.ssoToken
      ? store.state.ssoToken
      : lStorage.get("ssoToken");
    let ProjectId = store.state.layout.projectId
      ? store.state.layout.projectId
      : lStorage.get("projectId");
    let userName = store.state.layout.userInfo.userName
      ? store.state.layout.userInfo.userName
      : storage.get("user_name");
    let group_code = store.state.layout.group_code
      ? store.state.layout.group_code
      : lStorage.get("group_code");

    let vm = this;
    let params = {
      url: url,
      method: "post",
      data: data,
      headers: {
        // projectId: ProjectId,
        token: ssoToken,
        appId: "adm",
        userId: userName,
        groupCode: group_code
      }
    }
    let params1 = {
      url: url,
      method: "post",
      data: data,
      headers: {
        projectId: ProjectId,
        token: ssoToken,
        appId: "adm",
        userId: userName,
        groupCode: group_code
      }
    }
    fetch(isShowPid ? {...params} : { ...params1})
      .then(response => {
        successResponse(vm, response, success, failed);
      })
      .catch(error => {
        errorResponse(vm, error, err);
      });
  },
  getDownload(url, requestData, success, name) {
    // 响应类型：arraybuffer, blob
    fetch
      .get(url, { params: requestData, responseType: "blob" })
      .then(resp => {
        const headers = resp.headers;
        const contentType = headers["content-type"];

        console.log("响应头信息", headers);
        if (!resp.data) {
          console.error("响应异常：", resp);
          return false;
        } else {
          console.log("下载文件：", resp);
          const blob = new Blob([resp.data], { type: contentType });

          const contentDisposition = resp.headers["content-disposition"];
          let fileName = "unknown";

          if (name) {
            fileName = name
          } else if (contentDisposition) {
            fileName = window.decodeURI(
              resp.headers["content-disposition"].split("=")[1]
            );
          }
          console.log("文件名称：", fileName);
          downFile(blob, fileName);
          success();
        }
      })
      .catch(function(error) {
        console.log(error);
      });
  },
  download(url, requestData) {
    // 响应类型：arraybuffer, blob
    fetch
      .post(url, requestData, { responseType: "blob" })
      .then(resp => {
        let headers = resp.headers;
        let contentType = headers["content-type"];

        console.log("响应头信息", headers);
        if (!resp.data) {
          console.error("响应异常：", resp);
          return false;
        } else {
          console.log("下载文件：", resp);
          const blob = new Blob([resp.data], { type: contentType });

          const contentDisposition = resp.headers["content-disposition"];
          let fileName = "unknown";
          if (contentDisposition) {
            fileName = window.decodeURI(
              resp.headers["content-disposition"].split("=")[1]
            );
          }
          console.log("文件名称：", fileName);
          downFile(blob, fileName);
        }
      })
      .catch(function(error) {
        console.log(error);
      });
  }
};
