
import axios, { AxiosInstance } from "axios"
import {global} from '@/const/Global'

import router from '@/router'

import { Toast } from 'vant'
import { generateToken } from "@/util/Sign";
import { isAppEnv, signAuth } from "@/util/Bridge";

export const Account = {
    entId: '166961152260050944',
    staffId: '1FKxgaEh5fuSm7a35BfUnKYAmradowpiTR' 
}

interface RouterConfig{
    path: string
    method?: string
    crediential?: boolean
    headers?:string[][]
}
export default class BaseService {
    private service: AxiosInstance;
    constructor() {
         this.service = axios.create({
            baseURL:'/proxyApi',
            timeout: 15000,
        })
        this.service.interceptors.request.use(
            (res)=>{
                if (!isAppEnv()) {
                    // from pc
                    res.headers['FZM-SIGNATURE'] = global.sig || 'MOCK'
                }
                return res
            },
            (err)=>{
                throw new Error(err)
            }
        )
    }
    public async useService(routerConfig: RouterConfig,payload?:any, ext?: {onUploadProgress?: (e: ProgressEvent)=>any}){
        let token;
        let headerItems:{[key:string]:string|number} ={}
        if(!routerConfig.method) routerConfig.method = 'post'
        if(routerConfig.crediential) token = signAuth()
        switch(routerConfig.method){
            case 'post':
                routerConfig.crediential&&Object.assign(headerItems,{'FZM-SIGNATURE':token})
                routerConfig.headers&&routerConfig.headers.map(i=>{
                    headerItems[i[0]] = i[1]
                })
                const res = await this.service.post(routerConfig.path,payload,{
                   headers:headerItems,
                   onUploadProgress: ext?.onUploadProgress
                })
            return res
        }
    }

}