//如果部署在同域名的话可以直接取cookie,后端需 HttpOnly 设置成否
// var cookie_name = 'wolfking.jeesharp.session.id'
// getCookie(cookie_name)

// 是否本地环境
function isLocalEnv() {
  let domain = window.location.origin
  if (['http://127.0.0.1:5501', 'file://'].includes(domain)) {
    return true
  } else {
    return false
  }
}


window.apiType = "prod"  // dev 本地测试 ,  sit  线上测试  uat  客户测试环境 prod  正式环境
// if(window.location.search){
//   apiType = window.location.search.split("=")[1]
// }
window.fetchUrl = ""
// window.fetchUrl = "http://172.21.9.236:8081"
window.user = "18335173447"
// window.user = "18035133443"

if (window.apiType == "dev") {
  window.fetchUrl = "http://192.168.1.12:8080"
} else if (window.apiType == "sit") {
  window.fetchUrl = "http://172.21.9.236:8081"
} else if (window.apiType == "uat") {
  window.fetchUrl = "http://172.21.12.247:8081"
} else if(window.apiType == "prod"){
  window.fetchUrl = "http://172.21.12.244:8081"
}

// api 前缀
function getApiUrl() {
  // 为线上时
  if (!isLocalEnv()) {
    return window.location.origin
  } else {
    // 本地时
    // return 'http://sxtc.com:10002'        // 内网环境
    // return 'http://10.8.8.100:10002'   // 内网环境
    // return 'http://1.71.170.214:18080' // 线上环境
    // return 'http://szxm.sxcig.com:8012' // 线上环境
    // return 'http://10.0.0.27:8080'     // 超哥环境
    // return 'http://10.0.0.22:8080'     // 闫敏的环境
    // return 'http://10.0.0.8:8080' // 祥慧的环境
    // return 'http://10.0.0.115:8080'    // 王蒙的环境
    return 'http:192.168.1.60:8081' // 焦煤内网
  }
}
// websocket 前缀
function getWsUrl() {
  let prefix = location.protocol === 'https:' ? 'wss://' : 'ws://'
  // 为线上时
  if (!isLocalEnv()) {
    return prefix + window.location.host
  } else {
    return prefix + 'sxtc.com:10002'
    // return prefix + '10.0.0.115:8080'
  }
}

// minio 前缀
function getMinioUrl() {
  let isProduction = location.origin.indexOf('1.71.170.214') != -1
  if (isProduction) {
    return 'http://1.71.170.214:19000/constr-documents/'
  } else {
    return 'http://10.8.8.191:9000/constr-documents-test/'
  }
}

/** axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
const httpRequest = axios.create({
  baseURL: 'http:192.168.1.60:8081', // 测试环境
  timeout: 3 * 60 * 1000, // 3分钟等待
  withCredentials: true // 携带cookie
})

// 请求拦截器
httpRequest.interceptors.request.use(
  function (config) {
    if (!isLocalEnv()) {
      if (getQueryVariable('token')) {
        config.headers['access_token'] = getQueryVariable('token')
      }
    } else {
      config.headers['access_token'] = localStorage.getItem('token')
      // config.headers['access_token'] = '4b3ed521-f509-48d9-b907-ab127479df41'
    }
    // 上传文件
    if (config.url == '/apiSys/oss/upload') {
      config.headers['Content-Type'] = 'multipart/form-data'
    } else {
      config.headers['Content-Type'] = 'application/json'
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

//响应拦截
httpRequest.interceptors.response.use(
  function (response) {
    const res = response.data
    // if (res.code == 201) {
    //   this.ELEMENT.Message.error(res.msg)
    //   if (!isLocalEnv()) {
    //     // 跳登录页
    //     window.location = window.location.origin
    //   } else {
    //     localEnvLogin()
    //   }
    // }
    return response
  },
  function (error) {
    this.ELEMENT.Message.error(error.message)
    return Promise.reject(error)
  }
)

function get(url, params) {
  return new Promise((resolve, reject) => {
    httpRequest
      .get(url, { params: params })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err.data)
      })
  })
}
// qs.stringify(data)
function post(url, data, config) {
  return new Promise((resolve, reject) => {
    httpRequest
      .post(url, data, config)
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

function postFile(url, blob) {
  return new Promise((resolve, reject) => {
    let formdata = new FormData()
    formdata.append('multipartFile', blob)
    httpRequest
      .post(url, formdata)
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

function localEnvLogin() {
  post(
    '/ierp/api/getAppToken.do',
    {
      username: 'admin',
      password: '1q2w3e4r5t'
    },
    {
      transformRequest: [
        function (data, headers) {
          // 将请求数据转换成功 formdata 接收格式
          headers['Content-Type'] = 'application/x-www-form-urlencoded'
          return stringify(data)
        }
      ]
    }
  ).then(res => {
    localStorage.setItem('token', res.data.token || getQueryVariable('token'))
  })
}


function localEnvAppToken() {
  return new Promise((resole, reject) => {
    let data
    if (window.apiType == "dev") {
      data = {
        appId: "jsc",
        appSecuret: "G|s26?hAW1TzX5rY",
        tenantid: "jmdev",
        accountId: "1541173495969351680",
      }
    } else if (window.apiType == "sit") {
      data = {
        appId: "jsc",
        appSecuret: "OA9#'Jn'4p|f`nBG",
        tenantid: "dev",
        accountId: "1493393884158362624",
      }
    } else if (window.apiType == "uat") {
      data = {
        appId: "jsc",
        appSecuret: "Cs?9HeKqacN%gnu3",
        tenantid: "jmuatierp",
        accountId: "1507348433172694016",
      }
    } else if(window.apiType == "prod") {
      data = {
        appId: "jsc",
        appSecuret: '{Li$d73F13x"+ASb',
        tenantid: "jmierp",
        accountId: "1507155316804943872",
      }
    }else {
      console.log("未知类型");
      return
    }

    fetch(fetchUrl + "/ierp/api/getAppToken.do", {
      method: "post",
      body: JSON.stringify(data),
      timeout: 5000,
      mode: 'cors'
    }).then(res => {
      return res.json()
    })
      .catch(error => {
        reject(error)
      })
      .then(response => {
        if (response != undefined) {
          resole(response.data)
        } else {
          reject({ requestType: false })
        }

      });
  })
};

function getLocalEnvAccessToken() {
  return new Promise((resole, reject) => {
    let data
    if (window.apiType == "dev") {
      data = {
        user: "17649834944",
        apptoken: localStorage.getItem("app_token"),
        tenantid: "jmdev",
        accountId: "1541173495969351680",
        usertype: "Mobile",
      }
    } else if (window.apiType == "sit") {
      data = {
        user: window.user,
        // user: "17649834944",
        apptoken: localStorage.getItem("app_token"),
        tenantid: "dev",
        accountId: "1493393884158362624",
        usertype: "Mobile",
      }
    } else if (window.apiType == "uat") {
      data = {
        // appId: "jsc",
        apptoken: localStorage.getItem("app_token"),
        // appSecuret: "Cs?9HeKqacN%gnu3",
        tenantid: "jmuatierp",
        // user: "18335173447",
        user: window.user,
        usertype: "Mobile",
        accountId: "1507348433172694016",
      }
    }  else if(window.apiType == "prod") {
      data = {
        // appId: "jsc",
        user: window.user,
        usertype: "Mobile",
        apptoken: localStorage.getItem("app_token"),
        // appSecuret: '{Li$d73F13x"+ASb',
        tenantid: "jmierp",
        accountId: "1507155316804943872",
      }
    } else {
      console.log("未知类型");
      return
    }


    fetch(fetchUrl + "/ierp/api/login.do", {
      method: "post",
      body: JSON.stringify(data),
      mode: 'cors'
    }).then(res => res.json())
      .catch(error => {
        reject(error)
      })
      .then(response => {
        resole(response.data)
      });
  })
}

function fetchPostMethods(url, params) {
  return new Promise((resole, reject) => {
    fetch(fetchUrl + url, {
      method: "post",
      body: JSON.stringify(params),
      headers: new Headers({
        "Content-Type": "application/json",
        "accesstoken": localStorage.getItem("access_token"),
      }),
      mode: 'cors'
    }).then(res => {
      return res.json()
    })
      .catch(error => {
        reject(error)
      })
      .then(response => {
        if (response != undefined) {
          resole(response.data)
        }
      });
  })
}


// 将参数转换成功 formdata 接收格式
function stringify(data) {
  let ret = ''
  for (const it in data) {
    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
  }
  ret = ret.substring(0, ret.lastIndexOf('&'))
  return ret
}
// 格式化日期
function formatDate(time) {
  let date = time ? new Date(Number(time)) : new Date();
  let Y = date.getFullYear() + '-';
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  let D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' ';
  let h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':';
  let m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':';
  let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  return Y + M + D + h + m + s;
}