import { openUniMP, releaseWgtToRunPath, UniMP } from '@dcloudio/uni-app-runtime'
import { AESDecrypt, PLATFORM, RELEASE_BASE_URL, Signature, TOKEN } from '../constants/AppConstants'
import { ToastUtils } from '../dialog/ToastUtils'
import { UniVersionEntity,TradeData, UniIconEntity } from '../viewmodel/DataBean'
import { downloadFile } from './DownloaderUtils'
import { isUniMpNeedDownload, isUniMpNeedDownloadForPath } from './KVManager'
import { KVStore } from './KVStore'
import { Logger } from './Logger'
import { bundleManager, common } from '@kit.AbilityKit'
import { DeviceUtil } from '@pura/harmony-utils'
import { deviceInfo } from '@kit.BasicServicesKit'
import { CHANNEL } from '../../../../BuildProfile'
import { CommonService } from '../viewmodel/CommonService'

/**
 * 下载并启动模拟器
 * @param context
 * @param entity
 * 注意：status: -1-失败, 0-默认, 1-进行中(progress为百分比), 2-成功(progress为0, path为路径), 3-启动, 4-释放成功, 5-释放失败
 */
export function downStartUp(context: UIContext, entity: UniVersionEntity, callback: (status: number, progress: number, path?: string) => void) {
  let uniMpId = entity.unimp_id;//'__UNI__D535736';
  let uniMpType = entity.unimp_type;
  let uniMpUrl =  entity.url;//'https://cdn.batiao8.com/flaunt/uni_mp/wgt/alipay/__UNI__D535736_2026-4-20-test4.wgt';
  let uniVersion = entity.version??'0.0.0';
  if(uniMpId){
    isUniMpNeedDownload(uniMpId, uniVersion).then(res => {
      if(res == true){
        callback(1, 0)
        //需要更新，则删除旧文件，重新下载wgt文件
        if(!uniMpId){
          ToastUtils.showToast(context, '加载失败，请重试或联系客服！')

          callback(-1, 0)
          return
        }

        //下载模拟器
        downloadFile(getContext(), uniMpUrl??'', uniMpId + '.wgt', (status, progress, path) => {
          if(status == 2){
            callback(status, progress,  path)
            //已下载完成，释放并启动
            releaseRunUniMp(context, uniMpId??'', '', (status) => {
              callback(status, progress,  path)
            })
          }else if(status == -1){
            ToastUtils.showToast(context, '加载失败，请重试或联系客服！')
            callback(status, progress,  path)
          }else{
            callback(status, progress,  path)
          }
          Logger.info('UniMp','downloadFile status:' + status + ', progress:' + progress)
        })
      }else{
        //不需要更新，已释放则直接打开模拟器，否则先释放，再打开
        runUniMp(context, uniMpId??'', '', (status) => {
          callback(status, 100)
        })
      }
    });
  }
  Logger.info('UniMp','uniMpId:'+uniMpId+ ', uniMpType:' + uniMpType + ', uniMpUrl:' + uniMpUrl + ', uniMpVersion:' + uniVersion)
}

export function downStartUpForPath(context: UIContext, uniMpVersions: UniVersionEntity[], uniIconEntity: UniIconEntity, callback: (status: number, progress: number, path?: string) => void) {
  const uniMpType = uniIconEntity.type
  const uniMpEntity = uniMpVersions.find((item: UniVersionEntity) => {
    return item.unimp_type === uniMpType;
  });

  const targetPath = uniIconEntity.url??''
  const uniMpUrl = uniMpEntity?.url??''//'https://cdn.batiao8.com/flaunt/uni_mp/wgt/alipay/__UNI__D535736_2026-4-20-test4.wgt';
  const uniMpId = uniMpEntity?.unimp_id??''
  isUniMpNeedDownloadForPath(uniMpId).then(res => {
    if(res == true){
      // 已释放，直接运行
      runUniMp(context, uniMpId??'', '', (status) => {
        callback(status, 100)
      })
    }else{
      // 未下载，先下载释放，再运行
      downloadFile(getContext(), uniMpUrl??'', uniMpId + '.wgt', (status, progress, path) => {
        if(status == 2){
          callback(status, progress,  path)
          //已下载完成，释放并启动
          releaseRunUniMp(context, uniMpId??'', targetPath, (status) => {
            callback(status, progress,  path)
          })
        }else if(status == -1){
          ToastUtils.showToast(context, '加载失败，请重试或联系客服！')
          callback(status, progress,  path)
        }else{
          callback(status, progress,  path)
        }
        Logger.info('UniMp','downloadFile status:' + status + ', progress:' + progress)
      })
    }
  });
}

/**
 * 运行模拟器
 * 1、如已释放，直接运行
 * 2、如未释放，先释放，再运行
 * @param uniMpId 小程序ID
 * @param targetPath 跳转小程序路径
 * 注意：status: -1-失败, 0-默认, 1-进行中(progress为百分比), 2-成功(progress为0, path为路径), 3-启动, 4-释放成功, 5-释放失败
 */
export function runUniMp(context: UIContext, uniMpId: string, targetPath:string, callback: (status: number) => void){
  releaseRunUniMp(context, uniMpId, targetPath, callback)
}
/**
 * 释放并运行，需要先释放，再运行
 * 1、删除旧文件
 * 2、先释放，再运行
 * @param uniMpId 小程序ID
 * @param targetPath 跳转小程序路径
 * 注意：status: -1-失败, 0-默认, 1-进行中(progress为百分比), 2-成功(progress为0, path为路径), 3-启动, 4-释放成功, 5-释放失败
 */
export function releaseRunUniMp(context: UIContext, uniMpId: string, targetPath: string, callback: (status: number) => void){
  let path = getContext().filesDir + "/"+uniMpId+".wgt"
  uniMpConfig().then(res => {
    releaseWgtToRunPath(uniMpId, path, (code: 1 | -1, _) =>{
      if(code === 1){
        callback(4)
        // 释放成功，运行
        const mp = openUniMP(uniMpId, {
          redirectPath: targetPath,
          extraData: res,
          showCapsuleButton: false,
          showSplashScreen: true,
        }) as UniMP

        mp.on('close',()=>{
          console.log('UniMP-close')
        })
        mp.on('show',()=>{
          console.log('UniMP-show')
          callback(3)
        })
        mp.on('hide',()=>{
          console.log('UniMP-hide')
        })
        mp.on('uniMPEvent', (event: string, data: object, _notify: boolean) => {
          Logger.info('UniMp', 'uniMPEvent:' + event + ', data:' + data)

          if(event === 'start_combo_pay'){
            const jsonStr = typeof data === 'string' ? data : JSON.stringify(data);
            const obj = JSON.parse(jsonStr) as TradeData;

            const weixinMpOriId: string = obj.weixinMpOriId ?? "";
            const outTradeNo: string = obj.outTradeNo ?? "";
            CommonService.startUniPay(getContext() as common.UIAbilityContext, weixinMpOriId, outTradeNo)
          }else if(event === 'closeUniAPP'){
            mp.close()
          }
        })
      }else{
        // 释放失败，提示用户
        ToastUtils.showToast(context, '加载失败，请重试或联系客服！')
        callback(5)
      }
    })
  })
}

async function uniMpConfig(): Promise<Record<string, string>>{
  let extraData: Record<string, string> = {};

  const bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
  const versionName = bundleInfo.versionName;
  const bundleName = bundleInfo.name;

  const accessToken: string = KVStore.getInstance().getSync(TOKEN, '');
  const deviceId: string = DeviceUtil.getDeviceId();
  const brand: string = deviceInfo.brand;
  const model: string = deviceInfo.productModel;

  extraData["x-token"] = accessToken;
  extraData["x-version"] = versionName;
  extraData["x-platform"] = PLATFORM;
  extraData["x-device-id"] = deviceId;
  extraData["x-mobile-brand"] = brand;
  extraData["x-mobile-model"] = model;
  extraData["x-channel"] = CHANNEL;
  extraData["x-package"] = bundleName;
  extraData["x-click-id"] = '';
  extraData["host"] = RELEASE_BASE_URL + '/';
  extraData["decrypt"] = AESDecrypt;
  extraData["encrypt"] = Signature;
  extraData["isCombo"] = 'ok';

  return extraData
}
