import axios, {
  AxiosError,
  AxiosHeaders,
  AxiosProgressEvent,
  AxiosRequestConfig,
  AxiosResponse,
  FormData,
  InternalAxiosRequestConfig
} from '@ohos/axios';
import { IBestToast, YTDate, YTLog, yTRouter } from '../../../../Index';
import { AppStorageKeyCollect } from '../constants';
import { ReqString } from '../models';
import { userInfo, UserInfo } from '../models/UserInfo';
import { HuaweiAuthPlugin } from './HuaWeiAuthPlugin';


export const baseURL: string = 'https://hm-test.ytpm.net/prod-api'

export const instance = axios.create({
  baseURL,
  timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {

  // 对请求数据做点什么
  if (AppStorage.get<string>(AppStorageKeyCollect.TOKEN)) {
    config.headers.Authorization = AppStorage.get<string>(AppStorageKeyCollect.TOKEN)
  }
  return config;
}, (error: AxiosError) => {
  // 对请求错误做些什么

  return Promise.reject(error);
});


// 添加响应拦截器
instance.interceptors.response.use((response: AxiosResponse) => {
  // 对响应数据做点什么
  YTLog.info(response)
  // 对响应错误做点什么
  if (response.data.code == 401) {
    userInfo.logout()
    yTRouter.router2LoginPage()
    return Promise.reject('401');
  }

  return response.data.data;
}, (error: AxiosError) => {
  YTLog.error(error)
  setTimeout(() => {
    IBestToast.hide()
    setTimeout(() => {
      IBestToast.show({ message: '请求超时，请检查网络' })
    }, 100)
  }, 1000)
  return Promise.reject(error);
});


export class YTRequest {
  private static productName: string = 'chat'

  static get<T>(url: string, params?: Record<string, string | number | boolean>,
    headers?: Record<string, string>): Promise<T> {
    return instance.get<null, T, null>(url, { params, headers })
  }

  static post<T, D>(url: string, data?: D, params?: Record<string, string | number | boolean>, headers?: AxiosHeaders) {
    return instance.post<null, T, D>(url, data, { params, headers })
  }

  static upPost<T, D>(url: string, data: D, configs?: AxiosRequestConfig<D>) {
    return instance.post<string, T, D>(url, data, configs)
  }

  //获取验证码
  static getCaptcha(phonenumber: string, success: (res: string) => void, fail: (err: Error) => void) {
    YTRequest.post<ReqString, ReqString>(`/api/${YTRequest.productName}/member/sendSmsCode`,
      { 'phonenumber': phonenumber })
      .then(res => {
        success(res['uuid'])
      })
      .catch((err: Error) => {
        fail(err)
      })
  }

  //手机号登录
  static phonenumberLogin(param: ReqString) {
    const uuid = AppStorage.get<string>('uuid')
    if (uuid !== undefined) {
      YTRequest.post<ReqString, ReqString>(`/api/${YTRequest.productName}/member/phoneLogin`, {
        'phonenumber': param['phonenumber'],
        'smsCode': param['captcha'],
        'uuid': uuid
      })
        .then(res => {
          userInfo.setToken(res[AppStorageKeyCollect.TOKEN])
          YTRequest.refreshUserInfo(() => {
            IBestToast.show({ message: '登录成功' })
            yTRouter.routerBack()
          })
        })
    }
  }

  //华为登录
  static huaweiLogin() {
    try {
      IBestToast.showLoading()
      HuaweiAuthPlugin.requestAuth()
        .then(res => {
          YTRequest.post<ReqString, ReqString>(`/api/${YTRequest.productName}/member/hmLogin`,
            { 'code': res } as ReqString)
            .then(data => {
              const token = data['token']
              userInfo.setToken(token)
              YTRequest.refreshUserInfo((userInfo) => {
                // YTLog.info(userInfo)
                IBestToast.hide()
                setTimeout(() => {
                  IBestToast.show({ message: '登录成功' })
                }, 100)
                yTRouter.routerBack()
              })
            })
            .catch((err: Error) => {
              // AlertDialog.show({ message: JSON.stringify(err, null, 2) })
              // IBestToast.hide()
              YTLog.error(err)
            })
        })
        .catch((e: Error) => {
          // AlertDialog.show({ message: JSON.stringify(e, null, 2) })
          YTLog.error(e)
          // IBestToast.hide()
        })
    } catch (e) {
      // AlertDialog.show({ message: JSON.stringify(e, null, 2) })
      YTLog.error(e)
      // IBestToast.hide()
    }
  }

  //刷新用户信息
  static refreshUserInfo(success?: (res: UserInfo) => void) {
    YTRequest.post<UserInfo, null>(`/api/${YTRequest.productName}/member/info`)
      .then(res => {
        userInfo.setUserInfoAndLogin(res)
        YTLog.info(userInfo)
        success?.(res)
      })
  }

  //上传文件
  static uploadFile(context: Context, fullpath: string, success: (url: string) => void) {
    const formData = new FormData()
    formData.append('file', fullpath)
    YTRequest.upPost<ReqString, FormData>('/common/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      context,
      onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
        YTLog.info(progressEvent && progressEvent.loaded && progressEvent.total ?
          Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%', 'uploadFile');
      }
    })
      .then(res => {
        const url = res['url']
        success(url)
      })
  }

  // 修改用户头像
  static uploadHeadImg(context: Context, fullpath: string, success: () => void) {
    const formData = new FormData()
    formData.append('file', fullpath)

    YTRequest.upPost<ReqString, FormData>('/common/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      context,
      onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
        YTLog.info(progressEvent && progressEvent.loaded && progressEvent.total ?
          Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%', 'uploadFile');
      }
    })
      .then(res => {
        const url = res['url']
        YTRequest.post<null, ReqString>(`/api/${YTRequest.productName}/member/modifyMemberIcon`, { 'memberIcon': url })
          .then(() => {
            success()
          })
          .catch((e: Error) => {
            YTLog.error(e)
            // IBestToast.show({ message: '头像上传失败', type: 'fail' })
          })
      })
      .catch((e: Error) => {
        YTLog.error(e)
      })
  }

  // 修改用户昵称
  static changeNickname(name: string, success: () => void) {
    YTRequest.post<null, ReqString>(`/api/${YTRequest.productName}/member/modifyMemberName`, { 'memberName': name })
      .then(() => {
        YTRequest.refreshUserInfo(() => {
          success()
        })
      })
  }

  //问题反馈
  static questionBack(des: string, createBy: string) {
    YTRequest.post<null, ReqString>(`/api/${YTRequest.productName}/question/saveQuestion`, {
      'backQuestion': des,
      'createBy': createBy,
      'createTime': new YTDate().formatDate(),
    })
      .then(() => {
        IBestToast.show("反馈成功")
        yTRouter.routerBack()
      })
      .catch((e: Error) => {
        YTLog.error(e)
      })
  }
}


