import { buffer, util } from "@kit.ArkTS";
import axios, { AxiosHeaders, AxiosProgressEvent, AxiosResponse, FormData } from "@ohos/axios";
import { PgTokenModel } from "../model/resultModel/PgResultModel";
import AppConstants from "../app/AppConstant";
import http from "../request/HttpUtils"
import { BaseResultModel, PagingModel } from "../model/resultModel/BaseResultModel";
import { AppDataModel, AppGuideDetailsBean, ApplicationTypeModel } from "../model/resultModel/ApplicationResultModel";
import {
  AddFeedBackRequestModel,
  FeedBackBean,
  GetMsgListRequestModel
} from "../model/requestModel/MessageRequestModel";
import { MainMessageBean } from "../model/resultModel/MessageResultModel";
import { GetAppGuideRequestModel, GetAppListRequestModel, GuideRequest } from "../model/requestModel/AppRequestModel";
import { RuanseeAbilityStag } from "../app/RuanseeAbilityStag";
import { GetUserPhotoModel, UpdateUserInfoModel } from "../model/requestModel/UserInfoRequestModel";
import { AUTH_SYSCODE } from "../app/AppCache";
import fs from '@ohos.file.fs';
import { QuestionModel } from "../model/resultModel/QuestionModel";

import { request } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';

/*获取品高认证*/
export const getPgToken = (data?: ESObject) => {
  let byte = new Uint8Array(buffer.from(AppConstants.PG_APP_KEY_SECRET, 'utf-8').buffer);
  let ac = new util.Base64Helper().encodeToStringSync(byte);
  return http.postFromBody<PgTokenModel>("http://20.90.2.2/sso_out/oauth2/token?grant_type=client_credentials", data,
    new AxiosHeaders({
      'Authorization': 'Basic ' + ac,
      'Content-Type': 'application/x-www-form-urlencoded'
    }))
}

/**
 * 获取推荐应用
 */
export const getRecommendApplication = () => {
  return http.get<BaseResultModel<ApplicationTypeModel>>("app/v1/zamh/recommendApplication")
}

/**
 * 获取消息列表
 */
export const getMessageList = (state: number, page: number, pageSize: number) => {
  let param: GetMsgListRequestModel = {
    state: state,
    page: page,
    pageSize: pageSize
  }
  return http.get<BaseResultModel<PagingModel<MainMessageBean>>>("app/v1/zamh/getMessage", param)
}

/**
 * 获取应用列表
 */
export const getAppList = (name = "", page = 1, pageSize = 20) => {
  let param: GetAppListRequestModel = {
    name: name,
    page: page,
    pageSize: pageSize
  }
  return http.get<BaseResultModel<PagingModel<AppDataModel>>>("app/v1/zamh/getAllApplicationPage", param)
}

/**
 * 添加反馈
 */
export const addFeedBack = (appId: string, appName: string, selectType: number, title: string, content: string) => {
  let param: AddFeedBackRequestModel = {
    applicationId: appId,
    alarmSignal: RuanseeAbilityStag.userCache.getDepartmentCode,
    alarmName: RuanseeAbilityStag.userCache.getDepartmentName,
    type: selectType + "",
    title: title,
    content: content,
    applicationName: appName
  }
  return http.post<BaseResultModel<string>>("app/v1/zamh/addFeedBack", param)
}

/**
 * 获取我的反馈列表
 */
export const getMyFeedBackList = (page = 1, pageSize = 20) => {
  let param: GetAppListRequestModel = {
    name: "",
    page: page,
    pageSize: pageSize
  }
  return http.get<BaseResultModel<PagingModel<FeedBackBean>>>("app/v1/zamh/feedbackList", param)
}

/**
 * 获取应用指南列表
 */
export const getAppGuideList = (appName: string, cityName: string, page = 1, pageSize = 20) => {
  let param: GetAppGuideRequestModel = {
    name: appName,
    cityNumber: cityName,
    page: page,
    pageSize: pageSize
  }
  return http.get<BaseResultModel<PagingModel<AppDataModel>>>("app/v1/zamh/applicationHaveOperationGuide", param)
}

/**
 * 获取应用指南
 */
export const operationGuideList = (applicationId: string) => {
  let param: GuideRequest = {
    applicationId: applicationId
  }
  return http.get<BaseResultModel<Array<AppGuideDetailsBean>>>("app/v1/zamh/operationGuideList", param)
}

export const downLoadUserPhoto = (filePath: string) => {
  try {
    fs.accessSync(filePath);
    fs.unlinkSync(filePath);
  } catch (err) {

  }
  let param: GetUserPhotoModel = {
    id: RuanseeAbilityStag.userCache.getProfilePhoto,
    token: RuanseeAbilityStag.userCache.getAuthToken,
    clientType: "SERVER", //"SERVER",
    imsi1: "",
    deviceFlags: "",
    sysCode: AUTH_SYSCODE
  }
  return axios({
    url: 'http://20.90.2.2/UniAuth/api/sso/v1/download',
    method: 'post',
    params: param,
    headers: new AxiosHeaders({
      'Content-Type': `application/x-www-form-urlencoded;`
    }),
    filePath: filePath,
    onDownloadProgress: (progressEvent: AxiosProgressEvent) => {
      console.info("progress: ", progressEvent && progressEvent.loaded && progressEvent.total ?
      Math.ceil(progressEvent.total / progressEvent.total * 100) : 0);
    }
  })
}

/**
 * 修改手机号
 */
export const updateWorkPhone = (phone: string) => {
  let param: UpdateUserInfoModel = {
    token: RuanseeAbilityStag.userCache.getAuthToken,
    clientType: "SERVER", //"SERVER",
    imsi1: "",
    deviceFlags: "",
    sysCode: AUTH_SYSCODE,
    workPhone: phone
  }
  return http.postFromBody<BaseResultModel<string>>("http://20.90.2.2/UniAuth/api/sso/v1/updateUserInfo", param,
    new AxiosHeaders({
      'Content-Type': `application/x-www-form-urlencoded;`
    }),)
}

//上传文件
export const uploadUserPhoto = (filePath: string) => {
  let formData = new FormData();
  // 读取文件内容为ArrayBuffer
  try {
    let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
    let stat = fs.statSync(filePath);
    let fileName: ESObject = {};
    fileName['filename'] = file.name;
    fileName['contentType'] = 'image/jpeg';
    let arrayBuffer = new ArrayBuffer(stat.size);
    fs.readSync(file.fd, arrayBuffer);
    fs.closeSync(file);
    formData.append('file', arrayBuffer, fileName);
  } catch (e) {
    console.info("上传文件失败", e);
  }
  formData.append('token', RuanseeAbilityStag.userCache.getAuthToken);
  formData.append('clientType', 'SERVER');
  formData.append('sysCode', AUTH_SYSCODE);

  return http.post<BaseResultModel<string>>("http://20.90.2.2/UniAuth/api/sso/v1/uploadPhoto", formData,
    new AxiosHeaders({
      'Content-Type': 'multipart/form-data'
    }))
}

/**
 * 获取常见问题
 */
export const getQuestion = () => {
  return http.get<BaseResultModel<Array<QuestionModel>>>("app/v1/question")
}

/**
 * 获取应用列表
 */
export const applicationPage = (cityNumber: string, page: number, pageSize = 50, name?: string) => {
  let param: ESObject = {}
  param['cityNumber'] = cityNumber
  param['page'] = page
  param['pageSize'] = pageSize
  param['name'] = name
  param['attribution'] = 0
  return http.get<BaseResultModel<PagingModel<AppDataModel>>>("app/v1/zamh/applicationPage", param)
}

/**
 * 保存应用操作日志
 */
export const saveAppOperationLog = (appId: string, appName: string, type: string) => {
  let param: ESObject = {}
  param['appId'] = new String(appId)
  param['appName'] = appName
  param['operatorName'] = RuanseeAbilityStag.userCache.getUserName
  param['operatorPoliceNumber'] = RuanseeAbilityStag.userCache.getUserCode
  param['operatorIdCard'] = RuanseeAbilityStag.userCache.getIdCardNum
  param['deptId'] = RuanseeAbilityStag.userCache.getDeptCode
  param['deptName'] = RuanseeAbilityStag.userCache.getDeptName
  param['type'] = type

  let json = JSON.stringify(param)
  return http.postFromJson<BaseResultModel<string>>("app/v1/zamh/addOperationRecords", json)
}

//发送消息已读
export const readMessage = (messageId: string) => {
  let param: ESObject = {}
  param['id'] = new String(messageId)
  return http.get<BaseResultModel<string>>("app/v1/zamh/readMessage", param)
}

/**
 * 下载文件
 */
export const downLoadFile = (url: string, filePath: string, callback: (progressEvent: AxiosProgressEvent) => void) => {
  try {
    fs.accessSync(filePath);
    fs.unlinkSync(filePath);
  } catch (err) {
    console.error( err)
  }

  // return http.download(url,filePath,callback);
  return axios({
    url: url,
    method: 'get',
    headers: new AxiosHeaders({
      'User-Agent': 'Mozilla/5.0 (兼容浏览器标识)',
      'Content-Type': `application/x-www-form-urlencoded;`
    }),
    readTimeout:60000,
    responseType:"array_buffer",
    // context:getContext(this),
    filePath: filePath,
    onDownloadProgress:callback
    // onDownloadProgress: (progressEvent: AxiosProgressEvent) => {
    //   console.info("progress: ", progressEvent && progressEvent.loaded && progressEvent.total ?
    //   Math.ceil(progressEvent.total / progressEvent.total * 100) : 0);
    //
    // }
  })
}