import { useStore } from '@/store'
import HttpClient, { HttpClientConfig } from 'axios-mapper'
import networkConfig from '@/config/default/net.config'
import { getToken } from '@/utils/cookies'
import { Toast } from 'vant'
import Cookies from 'js-cookie'
import { request } from 'http'
import { getComparams, getUserInfo, setQueryConfig } from '.'

export const https = (configobj: any = { timeout: '',isComParams:true }) => {
  // debugger
  let config: HttpClientConfig = {
    baseURL: networkConfig.host,
    headers: {
      'token': getToken(),
      'sso-token': getToken(),
      'X-Forwarded-Token': getToken()
    }
  }
  if (configobj.timeout) {
    config.timeout = configobj.timeout
  }
  const https = new HttpClient(config)
  https.httpClient.interceptors.request.use(function (request) {
    let comInfo = getUserInfo()
    const comParams: string = configobj.isComParams?setQueryConfig(comInfo):''
    // const comParams: string=setQueryConfig(comInfo);
    let url: any = request.url
    console.log("url==",url);
    console.log("url==",comParams);
    if (url.indexOf("?") != -1) {
      request.url = request.url + "&" + comParams
    } else {
      request.url = request.url + "?" + comParams
    }
    return request
  }, function (error) {

  })
  // https.httpClient.interceptors.response.use(function (response) {
  //   return response
  // }, function (error) {
  //   // console.log('error===')
  //   // console.log(error.response.status)
  //   // console.log(error.status)
  //   // if (error.response.status === 401) {
  //   //   Toast('登录失效，请退出app重新登录')
  //   //   sessionStorage.clear()
  //   //   const tokenOld: any = Cookies.get('accessToken')
  //   //   window.location.href = `/sgh5/home?accessToken=${tokenOld}`
  //   // }
  //   return Promise.reject(error)
  // })
  return https
}

export const post = (url: any, data: any) => {
  return https().httpClient.post<Array<any>>(url, data).then(res => {
    const resData: string = JSON.parse(JSON.stringify(res.data))
    if (res.status >= 200 && res.status < 300) {
      return Promise.resolve(resData)
    } else {
      return Promise.reject(resData)
    }
  }).catch(async error => {
    return Promise.reject(error)
  })
}

export const getUrlParams = (key: any = 'accessToken') => {
  let url: any = location.search //获取url中"?"符后的字串
  let theRequest: any = new Object()
  if (url.indexOf('?') != -1) {
    let str: any = url.substr(1)
    let strs: any = str.split('&')
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]
    }
  }
  let token: string = theRequest[key] || ''
  return token
}



