import { isExistsUniMP } from '@dcloudio/uni-app-runtime';
import { UNIMP_DATA_VERSION, WX_AUTH_CODE } from '../constants/AppConstants'
import { UniMpLocalVersion } from '../viewmodel/LocalBean';
import { KVStore } from './KVStore'
import { StringUtils } from './StringUtils';

/**
 * 判断小程序是否需要下载(跳转指定路径)
 * @param uniId
 * @returns
 */
export async function isUniMpNeedDownloadForPath(uniId: string): Promise<boolean>{
  let uniMpVersions = await getUniMpNeedDownload();
  let uniMpVersion = uniMpVersions.find(item => {return item.id === uniId;});

  let isExists = false;
  if(uniMpVersion !== undefined && isExistsUniMP(uniId)){
    isExists = true
  } else {
    isExists = false
  }

  return isExists;
}

/**
 * 判断小程序是否需要下载（默认，目标版本判断）
 * @param uniId
 * @returns
 */
export async function isUniMpNeedDownload(uniId: string, targetVersion: string|undefined): Promise<boolean> {
  if(!targetVersion){
    true
  }
  let uniMpVersions = await getUniMpNeedDownload();
  let uniMpVersion = uniMpVersions.find(item => {return item.id === uniId});
  if(!StringUtils.checkVersionLegal(uniMpVersion?.version??'0.0.0', targetVersion??'0.0.0') || !StringUtils.isNewVersionAvailable(uniMpVersion?.version??'0.0.0', targetVersion??'0.0.0')){
    return false;
  }else{
    return true;
  }
}

export async function getUniMpNeedDownload(): Promise<UniMpLocalVersion[]> {
  // 注意：JSON 内部必须使用双引号 ""，单引号会引发解析错误
  const defaultJson = '[]';//'[{"id":"","type":"","version":"1.0.0","path":""},{"id":"","type":"","version":"1.0.0","path":""}]';

  let storeJson = await KVStore.getInstance()
    .get(UNIMP_DATA_VERSION, defaultJson);
  let uniMpVersions = JSON.parse(storeJson) as UniMpLocalVersion[];
  return uniMpVersions
}

export async function setUniMpNeedDownload(id: string, type: string, version: string, path: string): Promise<void> {
  let uniMpVersions = await getUniMpNeedDownload();
  let uniMpVersion = uniMpVersions.find(item => {return item.id === id});
  if(uniMpVersion){
    uniMpVersion.type = type;
    uniMpVersion.version = version;
    uniMpVersion.path = path;
  }else{
    uniMpVersions.push({
      id: id,
      type: type,
      version: version,
      path: path
    });
  }
  KVStore.getInstance().put(UNIMP_DATA_VERSION, JSON.stringify(uniMpVersions))
}

export function setWechatAuthCode(wechatCode: string): void {
  KVStore.getInstance().put(WX_AUTH_CODE, wechatCode)
}

export async function getWechatAuthCode(): Promise<string> {
  return await KVStore.getInstance().get(WX_AUTH_CODE, '')
}