import axios from 'axios'
import md5 from "js-md5"
import envConfig from '@/config/env-config'
// let BASE_API = "https://gd.chfatech.com/guangdian"
let BASE_API = envConfig.appOyAPI

const zlog = console.log.bind(console)

// URL 编码与拼接
const createSign = (inPostData, inAppSecret) => {
    let appUser = inPostData.appUser
    let appCode = inPostData.appCode
    let ts = inPostData.ts
    let args = JSON.parse(JSON.stringify(inPostData.args));
    let appSecret = inAppSecret

    let res = "";

    // URL 编码
    for (let key in args) {
      res += encodeURIComponent(key) + "%3d" + encodeURIComponent(args[key]).toLowerCase() + "%26";
    }
    res = res.slice(0, -3);

    // URL 拼接
    res += `&appUser=${appUser}&appCode=${appCode}&${ts} ${appSecret}`

    return res;
  };

// Basic Info
let basicInfo = {
    appUser: "user001",
    ver: "v2.17",
    appSecret: "JeC0mmE2ZjZmOfdmTGImYzU5Yjg1AYU2M3F="
}

// 创建 axios 实例
const service = axios.create({
    baseURL: BASE_API,
    timeout: 20000
})

// request 拦截器
service.interceptors.request.use(
    res => {
        // log('--->axios: res.data:', res.data)
        let oldPostData = JSON.parse(JSON.stringify(res.data))
        let newPostData = {
            appUser: basicInfo.appUser,
            appCode: oldPostData.args.appCode,
            ts: String(Date.parse(new Date())),
            ver: basicInfo.ver,
            args: oldPostData.args
        }

        let postData = {
            appUser: newPostData.appUser,
            appCode: newPostData.appCode,
            ts: newPostData.ts,
            sign: md5(createSign(newPostData, basicInfo.appSecret)),
            ver: newPostData.ver,
            args: newPostData.args
        }

        delete postData.args.appCode
        zlog()

        res.data = postData

        return res
    },
    error => {
        Promise.reject(error)
    }
)

// response 拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
        return res
    },
    error => {
        return Promise.reject(error)
    }
)

export default service
