import { ImageInfo, ServiceProfile, UserProfileMapper } from "./DataBean";
import { ApiManager } from '@ohos/common/src/main/ets/provider/ApiManager';
import { FormData } from '@ohos/axios';
import { BaseResponse } from "@ohos/common/src/main/ets/provider/BaseResponse";
import { RequestCallback } from "@ohos/common/src/main/ets/provider/Callback";
import { fileUri } from '@kit.CoreFileKit';
import { FeedbackRequest } from "./Request";
import { LoginProfile, UserInfo } from "@ohos/common/src/main/ets/viewmodel/DataBean";
import { Logger } from "@ohos/common";
import { KVStore } from "@ohos/common/src/main/ets/utils/KVStore";
import { LOGIN_PROFILE, TOKEN, TOKEN_LOGIN } from "@ohos/common/src/main/ets/constants/AppConstants";

export class MainService {
 /**
  * 文件上传（反馈图片）
  * @param fileUri
  */
  static async uploadFile(fileUri: string, callback?: RequestCallback) {
    try {
      // 1. 准备数据
      const fd = new FormData();
      fd.append('file', fileUri);
      fd.append('type', 'feedback');

      // 2. 调用封装好的 request
      const result = await ApiManager.getInstance().request<ImageInfo>(
        '/api/user/upload',
        undefined,
        'POST',
        fd
      );

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

  /**
   * 图片上传（反馈图片，目前受阻于签名）
   * @param uri 图片URI
   * @param callback
   */
  static async uploadImage(uri: string, callback?: RequestCallback) {
    try {
      //拿到uri后构建FormData参数，此处有两种方式
      //第一种，获取直接放沙箱路径，axios支持这种
      const fileUriObject = new fileUri.FileUri(uri)
      const path = fileUriObject.path
      const name = MainService.getFileNameFromUri(uri);

      //第二种是internal://协议的地址
      // const filePath: string = uri;
      // const resFile = fs.openSync(filePath, fs.OpenMode.READ_ONLY)
      // let newPath = getContext().cacheDir + "/" + resFile.name;
      // fs.copyFileSync(resFile.fd, newPath)
      // const path = "internal://cache/" + resFile.name;

      let formData = new FormData()
      formData.append('file', path, { filename: name, type: 'image/jpeg' })

      const result = await ApiManager.getInstance().upload<BaseResponse<ImageInfo>>(
        '/api/user/upload',
        formData,
        { "scene": "feedback" }
      );

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

  /**
   * 图片上传（反馈图片）
   * @param base64
   * @param callback
   */
  static async uploadImageBase64(base64: string, callback?: RequestCallback) {
    try {
      const postData: Record<string, string> = {
        'file': base64
      }
      const params: Record<string, string> = {
        'type': 'base64',
        'scene': 'feedback'
      }

      // 3. 发送请求 (使用你 ApiManager 的 request 方法)
      const result = await ApiManager.getInstance().request<ImageInfo>(
        '/api/user/upload',
        params,
        'post',
        postData
      );

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

  /**
   * 图片删除
   * @param id
   * @param callback
   */
  static async deleteImage(id: string, callback?: RequestCallback){
    try {
      const postData: Record<string, string> = {
        'id': id
      }
      const result = await ApiManager.getInstance().request<ImageInfo>(
        '/api/user/upload',
        undefined,
        'delete',
        postData
      );

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

  /**
   * 用户反馈
   * @param id
   * @param callback
   */
  static async feedback(type: string, content:string, contact: string, images: string[], callback?: RequestCallback){
    try {
      const postData: FeedbackRequest = {
        'type': type,
        'content': content,
        'contact': contact,
        'images': images
      };
      const result = await ApiManager.getInstance().request<ImageInfo>(
        '/api/user/feedback',
        undefined,
        'post',
        postData
      );

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

  /**
   * 联系客服（获取客服连接）
   */
  static async getService(): Promise<ServiceProfile> {
    const result = await ApiManager.getInstance().requestForMapper<ServiceProfile>(
      '/api/weixin/service',
      undefined,                // 传参，如有则传入
      UserProfileMapper         // 映射，数据映射器
    );

    return result;
  }

  /**
   * 获取账号列表
   */
  static async getAccount(): Promise<Array<UserInfo>> {
    const queryParams: Record<string, Object> = {
      'scene': 'account'
    };
    const result = await ApiManager.getInstance().request<Array<UserInfo>>(
      '/api/user/account',
      queryParams,                // 传参，如有则传入
      undefined                   // 映射，数据映射器
    );

    return result.data;
  }

  /**
   * 用户注销
   * @param callback
   */
  static async deleteAccount(callback?: RequestCallback){
    try {
      const result = await ApiManager.getInstance().request<string>(
        '/api/user/destroy',
        undefined,
        'post'
      );

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

  /**
   * 绑定：验证码绑定
   * @param phone
   * @param callback
   */
  static async bindForCaptcha(phone: string, captchaCode: string, captchaTimestamp: string, callback?: RequestCallback) {
    try {
      const jsonPhone: Record<string, string | number> = {
        "timestamp": captchaTimestamp,
        "phone": phone,
        "code": captchaCode
      };
      const postData: Record<string, Object> = {
        "type": "phone",
        "bind": "1",
        "data": jsonPhone
      };

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

  /**
   * 解绑：手机号
   * @param phone
   * @param callback
   */
  static async unBindPhone(phone: string, callback?: RequestCallback) {
    try {
      const jsonPhone: Record<string, string | number> = {
        "phone": phone,
      };
      const postData: Record<string, Object> = {
        "type": "phone",
        "bind": "2",
        "data": jsonPhone
      };

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

  /**
   * 绑定：微信
   * @param authCode
   * @param callback
   */
  static async wxBind(authCode: string, callback?: RequestCallback) {
    try {
      const jsonWxAuth: Record<string, string | number> = {
        "code": authCode,
        "code_type": ''
      };
      const postData: Record<string, Object> = {
        "type": "weixin",
        "bind": "1",
        "data": jsonWxAuth
      };

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

  /**
   * 解绑：微信
   * @param wechatCode
   * @param callback
   */
  static async unBindWechat(wechatCode: string, callback?: RequestCallback) {
    try {
      const jsonWechat: Record<string, string | number> = {
        "code": wechatCode,
        "code_type": ''
      };
      const postData: Record<string, Object> = {
        "type": "weixin",
        "bind": "2",
        "data": jsonWechat
      };

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

  /**
   * 绑定/解绑：适用于手机验证、一键和微信
   * @param phone
   * @param callback
   */
  static async bind(data: Record<string, Object>, callback?: RequestCallback) {
    Logger.info('loginInteface', 'wxBind: ------------->' + JSON.stringify(data));
    let result = await ApiManager.getInstance().request<LoginProfile>(
      '/api/user/login',
      undefined,
      'post',
      data
    );

    if(result.code === 200 || result.code === 0){
      if (callback && callback.onSuccess) {
        callback.onSuccess(result.data);
      }
    }else{
      if (callback && callback.onFailure) {
        callback.onFailure(result.message);
      }
    }
  }

  /**
   * 切换账号
   * @param userId
   * @param callback
   */
  static async switchAccount(userId: string, callback?: RequestCallback) {
    try {
      const jsonSwitch: Record<string, string | number> = {
        "user_id": userId
      };
      const data: Record<string, Object> = {
        "type": "device",
        "data": jsonSwitch
      };

      let result = await ApiManager.getInstance().request<LoginProfile>(
        '/api/user/login',
        undefined,
        'post',
        data
      );

      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);
      }
    }
  }

  /**
   * 退出登录
   */
  static async logout(callback?: RequestCallback) {
    let result = await ApiManager.getInstance().request<string>(
      '/api/user/logout',
      undefined,
      'post'
    );

    if(result.code === 200 || result.code === 0){
      if (callback && callback.onSuccess) {
        callback.onSuccess(result.data);
      }
    }else{
      if (callback && callback.onFailure) {
        callback.onFailure(result.message);
      }
    }
  }


  /**
   * 从 URI 中获取文件名
   * @param uri
   * @returns
   */
  static getFileNameFromUri(uri: string): string {
    if (!uri) return 'unknown_file';

    // 兼容斜杠 / 和反斜杠 \
    const parts = uri.split(/[\\\/]/);
    const fileName = parts[parts.length - 1];

    // 如果 URI 以 / 结尾，处理一下
    return fileName || 'default_name';
  }

}
