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'
import { promptAction } from '@kit.ArkUI'
import { staticMap } from '@kit.MapKit'

//用户相关api
export class YTUserRequest extends YTRequest {
  //获取验证码
  static getLoginCaptcha(phonenumber: string, result: ResultCallBack<LoginCollect>) {
    YTUserRequest.post<LoginCollect, LoginCollect>(
      `/decisionApUser/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>(`/decisionApUser/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>(`/decisionApUser/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>(`/decisionApUser/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>(`/decisionApUser/resetPwd`, param)
      .then(() => {
        result?.()
      })
  }

  //注销
  static logout(){
    YTUserRequest.post<null,null>(`/decisionApUser/logout`).then(()=>{

    })
  }
  //华为登录
  static harmonyLogin(instance: LoginCollect) {
    try {
      IBestToast.showLoading()
      HuaweiAuthPlugin.requestAuth()
        .then(code => {
          instance.setCode(code!)
          YTUserRequest.post<ReqString, LoginCollect>(`/decisionApUser/hmLogin`,
            instance)
            .then(data => {
              const token = data['token']
              userInfo.setToken(token)
              YTUserRequest.changeNickname('华为用户',()=>{})
              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>(`/decisionApUser/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>(`/decisionApUser/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>(`/decisionApUser/modifyMemberName`,
      { 'memberName': name })
      .then(() => {
        YTUserRequest.refreshUserInfo(() => {
          success()
        })
      })
  }

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

  //其他接口
  //用户设置界面的密码重置
  //获取验证码
  static getMyCaptcha(phonenumber: string, success: (res: string) => void, fail: (err: Error) => void) {
    YTRequest.post<ReqString, ReqString>(`/decisionApUser/sendSmsCode`,
      { 'phonenumber': phonenumber })
      .then(res => {
        success(res['uuid'])
      })
      .catch((err: Error) => {
        IBestToast.show({
          message:err.message,
          duration:500
        })
      })
  }

  static resetMyPassword(param: ReqString,callback?:()=>void) {
    const uuid = AppStorage.get<string>('resetPassword'+'uuid')
    if (uuid !== undefined) {
      YTRequest.post<ReqString, ReqString>(`/decisionApUser/resetPwd`, {
        'phonenumber': param['phonenumber'],
        'password': param['password'],
        'smsCode': param['smsCode'],
        'confirmPassword':param['confirmPassword'],
        'uuid': uuid
      })
        .then(res => {
          if(res!=null) {
            userInfo.logout()
            callback?.()
          }else{
            IBestToast.show({
              message:"验证码错误"
            })
          }

        })
        .catch((err:string)=>{
          // IBestToast.show({
          //   message:err
          // })
        })
    }else{
      IBestToast.show({
        message:'请先获取验证码',duration:500
      })
    }
  }



  //抛硬币接口
  static getTossCoinResult(result: ResultCallBack<ReqString>){
    YTUserRequest.get<ReqString>(`/decisionCoinRecord/throwCoin`)
      .then((res) => {
        result(res as ReqString)
      })
      .catch((e: Error) => {
        YTLog.error(e)
      })
  }

  //获取最近得抛硬币一次接口

  static getNearTossCoinResult(result: ResultCallBack<ReqString>){
    YTUserRequest.get<ReqString>(` /decisionCoinRecord/queryByLastCoinRecord`)
      .then((res) => {
        result(res)
      })
      .catch((e: Error) => {
        YTLog.error(e)
      })
  }

  //获取筛子结果，获取最近得一次记录

  static getRollDiceResult(diceCount:number,result: ResultCallBack<ReqString>){
    YTUserRequest.get<ReqString>(`/decisionDiceRecord/rollDice?diceCount=${diceCount}`)
      .then((res) => {
        result(res)
      })
      .catch((e: Error) => {
        YTLog.error(e)
      })
  }

  static getNearRollDiceResult(result: ResultCallBack<ReqString>){
    YTUserRequest.get<ReqString>(`/decisionDiceRecord/queryByDiceRecord`)
      .then((res) => {
        result(res)
      })
      .catch((e: Error) => {
        YTLog.error(e)
      })
  }

  //吃什么

  static getEatResult(result: ResultCallBack<ReqString>){
    YTUserRequest.get<ReqString>(`/decisionFoodRecord/randomFood`)
      .then((res) => {
        result(res)
      })
      .catch((e: Error) => {
        YTLog.error(e)
      })
  }

  static getNearEatResult(result: ResultCallBack<ReqString>){
    YTUserRequest.get<ReqString>(`/decisionFoodRecord/queryByFoodRecord`)
      .then((res) => {
        result(res)
      })
      .catch((e: Error) => {
        YTLog.error(e)
      })
  }


  //随机数

  static getNumberResult(count:number,maxValue:number,minValue:number,result: ResultCallBack<ReqString>){
    YTUserRequest.get<ReqString>(`/decisionRandomNumberRecord/generateRandomNumbers?count=${count}&maxValue=${maxValue}&minValue=${minValue}`)
      .then((res) => {
        result(res)
      })
      .catch((e: Error) => {
        YTLog.error(e)
      })
  }

  static getNearNumberResult(result: ResultCallBack<ReqString>){
    YTUserRequest.get<ReqString>(`/decisionRandomNumberRecord/queryLastRecord`)
      .then((res) => {
        result(res)
      })
      .catch((e: Error) => {
        YTLog.error(e)
      })
  }


  //转盘,重复
  static allowRepeat(params:ReqString, success: (res: string) => void, fail: (err: Error) => void) {
    YTRequest.post<ReqString, ReqString>(`/decisionTurntableConfig/allowRepeat`,
      { 'id': params['id'],
        'allowRepeat':params['allowRepeat']
      }
      )
      .then(res => {

        //data:"只能传0，1",不能为0
        success(res['data'])
      })
      .catch((err: Error) => {
        IBestToast.show({
          message:err.message,
          duration:500
        })
      })
  }
  //旋转时长修改
  static rotateTime(params:ReqString, success: (res: string) => void, fail: (err: Error) => void) {
    YTRequest.post<ReqString, ReqString>(`/decisionTurntableConfig/rotateTime`,
      { 'id': params['id'],
        'spinDuration':params['spinDuration']
      }
    )
      .then(res => {

        //data:"6",不能为0 一样
        success(res['data'])
      })
      .catch((err: Error) => {
        IBestToast.show({
          message:err.message,
          duration:500
        })
      })
  }

  //转盘选项修改

  static updateBach(params:ReqString, success: (res: string) => void, fail: (err: Error) => void) {
    YTRequest.post<ReqString, ReqString>(`/decisionTurntableOption/updateBach`,
      { 'id': params['id'],
        'spinDuration':params['spinDuration']
      }
    )
      .then(res => {

        //data:"6",不能为0 一样
        success(res['data'])
      })
      .catch((err: Error) => {
        IBestToast.show({
          message:err.message,
          duration:500
        })
      })
  }


  //重置选项
  // static reset(params:ReqString, success: (res: string) => void, fail: (err: Error) => void) {
  //   YTRequest.post<ReqString, ReqString>(`/decisionTurntableOption/reset`,
  //     { 'turntableId': params['turntableId'],
  //     }
  //   )
  //     .then(res => {
  //       //data：true
  //       //操作成功
  //
  //     })
  //     .catch((err: Error) => {
  //       IBestToast.show({
  //         message:err.message,
  //         duration:500
  //       })
  //     })
  // }

  //转一转
  static bigWheelSave(params:ReqString, success: (res: string) => void, fail: (err: Error) => void) {
    YTRequest.post<ReqString, ReqString>(`/decisionTurntableRecord/save`,
      { 'turntableId': params['turntableId'],
        'optionId':params['optionId'],
        // 'optionName':params['optionName'],
      }
    )
      .then(res => {
        //data：true
        //操作成功

      })
      .catch((err: Error) => {
        IBestToast.show({
          message:err.message,
          duration:500
        })
      })
  }








}