import { AlipayProfile, CaptchaProfile, LoginProfile, UserInfo, UserProfile, UserProfileMapper } from "./DataBean";
import deviceInfo from "@ohos.deviceInfo";
import { DeviceUtil } from "@pura/harmony-utils";
import { Logger } from "../utils/Logger";
import { ApiManager } from "../provider/ApiManager";
import { DEVICE_OAID, LOGIN_PROFILE, TOKEN, TOKEN_LOGIN, USER_INFO, USER_PROFILE,
  WXAPPID} from "../constants/AppConstants";
import { KVStore } from "../utils/KVStore";
import { RequestCallback } from "../provider/Callback";
import { EVT_USER_INFO,EVT_USER_CONFIG_PROFILE } from "../constants/EventConstants";
import { emitter } from "@kit.BasicServicesKit";
import { AFAuthServiceResponse, AFService, AFServiceCenter, AFServiceParams, AFWantParams } from "@alipay/afservicesdk";
import { common } from "@kit.AbilityKit";
import { ToastUtils } from "../dialog/ToastUtils";

import * as wxopensdk from '@tencent/wechat_open_sdk';
// 注意：全局只能用同一个WXApi对象，否则无法监听回调
export const WXApi = wxopensdk.WXAPIFactory.createWXAPI(WXAPPID)

export class CommonService {
  private static userConfigEvent(isSuccess: boolean){
    const eventData: emitter.EventData = {
      data: { "result": isSuccess }
    };
    emitter.emit({ eventId: EVT_USER_CONFIG_PROFILE }, eventData);
  }
  /**
   * 请求用户配置信息 (带参请求)
   */
  static async getUserProfile(): Promise<UserProfile> {
    const osVersion: number = deviceInfo.sdkApiVersion;
    const oaid: string = AppStorage.get<string>(DEVICE_OAID)??'';
    const imei: string = DeviceUtil.getDeviceId();

    Logger.info('UserService',
      ` 请求参数：----> oaid:${oaid}---> osVersion:${osVersion}---> imei:${imei}`);
    const queryParams: Record<string, Object> = {
      'oaid': oaid,
      'os_version': osVersion,
      "imei": imei,
      "cid": ''
    };
    let result = await ApiManager.getInstance().requestForMapper<UserProfile>(
      '/api/user/config',
      queryParams,           // 传参，如有则传入
      UserProfileMapper      // 映射，数据映射器
    );
    AppStorage.setOrCreate<UserProfile>(USER_PROFILE, result);
    if (result.token && result.token.length > 0) {
      KVStore.getInstance().put(TOKEN, result.token)
    }

    CommonService.userConfigEvent(true)

    return result;
  }

  /**
   * 发送验证码
   * @param phone
   * @param callback
   */
  static async sendSmsCode(phone: string, callback?: RequestCallback) {
    try {
      const postParms: Record<string, string> = {
        "phone": phone
      };

      const result = await ApiManager.getInstance().request<CaptchaProfile>(
        'api/user/code',    // api
        undefined,          // get请求参数，会拼接到url中
        'post',             // 请求方式
        postParms           // post请求参数
      );

      if(result.code === 200 || result.code === 0){
        if (callback && callback.onSuccess) {
          callback.onSuccess(result.data.timestamp);
        }
      }else{
        if (callback && callback.onFailure) {
          callback.onFailure(result.message);
        }
      }
    } catch (err) {
      if (callback && callback.onError) {
        callback.onError(err as Error);
      }
    }
  }

  /**
   * 登录：验证码登录
   * @param phone
   * @param callback
   */
  static async loginForCaptcha(phone: string, captchaCode: string, captchaTimestamp: string, callback?: RequestCallback) {
    try {
      const jsonPhone: Record<string, string | number> = {
        "timestamp": captchaTimestamp, // 确保这个 value 是 string 或 number
        "phone": phone,
        "code": captchaCode
      };
      const postData: Record<string, Object> = {
        "login_type": "phone",
        "phone": jsonPhone
      };

      CommonService.login(postData, callback);
    } catch (err) {
      if (callback && callback.onError) {
        callback.onError(err as Error);
      }
    }
  }


  /**
   * 登录(通用)
   * @param requestData
   * @param callback
   */
  static async login(requestData: Record<string, Object>, callback?: RequestCallback) {
    try {
      let result = await ApiManager.getInstance().request<LoginProfile>(
        '/api/user/login',
        undefined,
        'post',
        requestData
      );

      if(result.code === 200 || result.code === 0){
        const token = result.data.token
        if(token && token.length > 0){
          //将登录信息持久化(const savedProfile = JSON.parse(rawJson) as LoginProfile;)
          const loginJson: string = JSON.stringify(result);
          KVStore.getInstance().put(LOGIN_PROFILE, loginJson);         //持久化登录信息
          KVStore.getInstance().put(TOKEN_LOGIN, token ?? '');         //持久化token
          KVStore.getInstance().put(TOKEN, token ?? '');               //持久化token
        }
        if (callback && callback.onSuccess) {
          callback.onSuccess(result.data);
        }
      }else{
        if (callback && callback.onFailure) {
          callback.onFailure(result.message);
        }
      }
    } catch (err) {
      if (callback && callback.onError) {
        callback.onError(err as Error);
      }
    }
  }


  private static userInfoEvent(isSuccess: boolean){
    const eventData: emitter.EventData = {
      data: { "result": isSuccess }
    };
    emitter.emit({ eventId: EVT_USER_INFO }, eventData);
  }

  /**
   * 获取用户信息
   */
  static async getUserInfo(): Promise<UserInfo> {
    const result = await ApiManager.getInstance().request<UserInfo>(
      '/api/user',
      undefined,
      undefined
    );
    const userInfo = result.data

    //将用户信息持久化(const savedProfile = JSON.parse(rawJson) as UserInfo;)
    const userInfoJson: string = JSON.stringify(userInfo);
    KVStore.getInstance().put(USER_INFO, userInfoJson);         //持久化用户信息

    CommonService.userInfoEvent(true)
    return result.data;
  }

  /**
   * 拉起微信，获取微信授权
   * @param context
   */
  static async wxAuthorize(context: common.UIAbilityContext, isBindAuth: boolean){
    const isInstalled = WXApi.isWXAppInstalled()
    if(!isInstalled){
      const uiContext = context.windowStage.getMainWindowSync().getUIContext();
      ToastUtils.showToast(uiContext, '您没有安装微信客户端,请先下载安装')
    }else{
      const bundleName: string = context.abilityInfo.bundleName;
      let req = new wxopensdk.SendAuthReq;
      req.isOption1 = false
      req.nonAutomatic = true
      req.scope = 'snsapi_userinfo';// 只能填 snsapi_userinfo
      req.state = bundleName + Math.random() * 1000 + "_phone";
      req.transaction = isBindAuth ? 'rabbit_bind' : 'rabbit_login'

      WXApi.sendReq(context, req)
    }
  }

  static async wxLogin(authCode: string, callback?: RequestCallback) {
    try {
      const jsonWxAuth: Record<string, string | number> = {
        "code": authCode,
        "code_type": ''
      };
      const postData: Record<string, Object> = {
        "login_type": "weixin",
        "weixin": jsonWxAuth
      };

      CommonService.login(postData, callback);
    } catch (err) {
      if (callback && callback.onError) {
        callback.onError(err as Error);
      }
    }
  }

  /**
   * 获取支付宝登录参数
   */
  static async getAlipayLoginParams(): Promise<AlipayProfile> {
    const result = await ApiManager.getInstance().request<AlipayProfile>(
      'api/alipay/app_param',
      undefined,
      undefined
    );

    return result.data;
  }

  static async aliAuthorize(profile: AlipayProfile, callback: (result: string) => void) {
    const queryStr: string = profile.param??'';
    const match: RegExpMatchArray | null = queryStr.match(/app_id=([^&]*)/);
    let appId: string = '';
    if (match !== null && match[1]) {
      appId = match[1];
    }
    // 获取支付宝登录参数
    //1. 构建参数
    let bizParams = new Map<string, string>()
    let url = encodeURIComponent('https://authweb.alipay.com/auth?auth_type=PURE_OAUTH_SDK&app_id='+appId+'&scope=auth_user&state=init')
    bizParams.set("url", url);

    let backWant: AFWantParams = {
      bundleName: "com.img.rabbit",
      moduleName: "app",
      abilityName: "AppAbility"
    }

    let params = new AFServiceParams(bizParams, false, true, '', backWant, (response: AFAuthServiceResponse) => {
      //授权返回值
      let result = response.result
      if (result) {
        let parameters = result['parameters']
        if (parameters) {
          let authCode: string = parameters['auth_code']
          callback(authCode);
        }
      }
    })
    AFServiceCenter.call(AFService.AFServiceAuth, params);
  }

  static async aliLogin(authCode: string, callback?: RequestCallback) {
    try {
      const jsonAliAuth: Record<string, string | number> = {
        "auth_code": authCode
      };
      const postData: Record<string, Object> = {
        "type": "alipay",
        "bind": "",
        "data": jsonAliAuth
      };

      CommonService.login(postData, callback);
    } catch (err) {
      if (callback && callback.onError) {
        callback.onError(err as Error);
      }
    }
  }


  static startUniPay(context: common.UIAbilityContext, weixinMpOriId: string, outTradeNo: string) {
    const req: wxopensdk.LaunchMiniProgramReq = new wxopensdk.LaunchMiniProgramReq();

    req.userName = weixinMpOriId;
    req.path = `pages/index/index?outTradeNo=${outTradeNo}`;
    req.miniprogramType = 0;

    WXApi.sendReq(context, req)
  }
}