import { IBestToast } from '@ibestservices/ibest-ui'
import { AppStorageKeyCollect } from '../constants'
import { ReqString, ResultCallBack } from '../models'
import { LoginCollect } from '../models/LoginCollect'
import { UserInfo, userInfo } from '../models/UserInfo'
import { yTRouter } from '../utils/YTRouter'
import { YTRequest } from './YTRequest'
import { YTLog } from '../../../../Index'
import { AxiosProgressEvent, FormData } from '@ohos/axios'
import { YTDate } from '../utils/FormatDate'
import { HuaweiAuthPlugin } from '../utils/HuaWeiAuthPlugin'

//用户相关api
export class YTUserRequest extends YTRequest {
  //获取验证码
  static getLoginCaptcha(phonenumber: string, result: ResultCallBack<LoginCollect>) {
    YTUserRequest.post<LoginCollect, LoginCollect>(
      `/warehouseApUser/sendSmsCode`,
      new LoginCollect('login')
        .setPhonenumber(phonenumber)
    )
      .then(res => {
        result(res)
      })
      .catch((err: Error) => {
        result(undefined, err)
      })
  }

  //验证码登录
  static phonenumberLogin(param: LoginCollect, result?: ResultCallBack<UserInfo>) {
    if (param.getUuid() !== undefined) {
      YTUserRequest.post<ReqString, LoginCollect>(`/warehouseApUser/phoneLogin`, param)
        .then(res => {
          userInfo.setToken(res[AppStorageKeyCollect.TOKEN])
          YTUserRequest.refreshUserInfo((res) => {
            IBestToast.show({ message: '登录成功' })
            yTRouter.routerBack()
            result?.(res)
          })
        })
    } else {
      IBestToast.show({ message: "请求异常,请重新发送验证码", type: "fail" })
    }
  }

  //注册
  static register(param: LoginCollect) {
    if (param.getUuid() !== undefined) {
      YTUserRequest.post<ReqString, LoginCollect>(`/warehouseApUser/phoneSave`, param)
        .then(res => {
          userInfo.setToken(res[AppStorageKeyCollect.TOKEN])
          YTUserRequest.refreshUserInfo(() => {
            IBestToast.show({ message: '注册成功' })
            yTRouter.routerBack()
          })
        })
    } else {
      IBestToast.show({ message: "请求异常,请重新发送验证码", type: "fail" })
    }
  }

  //密码登录
  static passwordLogin(param: LoginCollect, result?: ResultCallBack<UserInfo>) {
    YTUserRequest.post<ReqString, LoginCollect>(`/warehouseApUser/passwordLogin`, param)
      .then(res => {
        userInfo.setToken(res[AppStorageKeyCollect.TOKEN])
        YTUserRequest.refreshUserInfo((res) => {
          IBestToast.show({ message: '登录成功' })
          yTRouter.routerBack()
          result?.(res)
        })
      })
  }

  //重置密码
  static resetPassword(param: LoginCollect, result?: ResultCallBack<undefined>) {
    YTUserRequest.post<ReqString, LoginCollect>(`/warehouseApUser/resetPwd`, param)
      .then(() => {
        result?.()
      })
  }

  //华为登录
  static harmonyLogin(instance: LoginCollect) {
    try {
      IBestToast.showLoading()
      HuaweiAuthPlugin.requestAuth()
        .then(code => {
          instance.setCode(code!)
          YTUserRequest.post<ReqString, LoginCollect>(`/warehouseApUser/hmLogin`,
            instance)
            .then(data => {
              const token = data['token']
              userInfo.setToken(token)
              YTUserRequest.refreshUserInfo((userInfo) => {
                YTLog.info(userInfo)
                IBestToast.hide()
                setTimeout(() => {
                  IBestToast.show({ message: '登录成功' })
                }, 100)
                yTRouter.routerBack()
              })
            })
            .catch((err: Error) => {
              IBestToast.hide()
              YTLog.error(err)
            })
        })
        .catch((e: Error) => {
          YTLog.error(e)
          IBestToast.hide()
        })
    } catch (e) {
      YTLog.error(e)
      IBestToast.hide()
    }
  }

  //刷新用户信息
  static refreshUserInfo(result?: ResultCallBack<UserInfo>) {
    YTUserRequest.post<UserInfo, null>(`/warehouseApUser/info`)
      .then(res => {
        userInfo.setUserInfoAndLogin(res)
        YTLog.info(userInfo)
        result?.(res)
      })
      .catch((err: Error) => {
        result?.(undefined, err)
      })
  }

  //上传文件
  static uploadFile(context: Context, fullpath: string, success: (url: string) => void) {
    const formData = new FormData()
    formData.append('file', fullpath)
    YTUserRequest.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)

    YTUserRequest.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']
        YTUserRequest.post<null, ReqString>(`/warehouseApUser/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) {
    YTUserRequest.post<null, ReqString>(`/warehouseApUser/modifyMemberName`,
      { 'memberName': name })
      .then(() => {
        YTUserRequest.refreshUserInfo(() => {
          success()
        })
      })
  }

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