import { buildComponents, AssetLoader } from '@leanwo/lowcode-utils';
import LowcodeWindowResource from '../api/dic/LowcodeWindowResource.js';
import { Notify, Uuid } from 'pc-component-v3';

/**
 * 从服务器端获取 Project Schema
 * @param {*} lowcodeWindowNo 
 * @returns 
 */
const getProjectSchema = async lowcodeWindowNo => {
  let baseObjectResponse = await LowcodeWindowResource.readJson(lowcodeWindowNo);
  
  if(baseObjectResponse.errorCode === 0){
    let projectSchema = JSON.parse(baseObjectResponse.data);
    return projectSchema;
  }else{
    let lowcodeJSON = {};
    Notify.error('提示', baseObjectResponse.errorMessage, false);
  }
};


/**
 * 从服务器端获取 Lowcode Window
 * @param {*} lowcodeWindowNo 
 * @returns 
 */
const getLowcodeWidnow = async lowcodeWindowNo => {
  let baseObjectResponse = await LowcodeWindowResource.uniqueByNo(lowcodeWindowNo);
  
  if(baseObjectResponse.errorCode === 0){
    return baseObjectResponse.data;
  }else{
    Notify.error('提示', baseObjectResponse.errorMessage, false);
    return null;
  }
};

const init = async lowcodeWindowNo => {
  // const packages = [{'package':'lowcode-engine-vue-material-dashboard','version':'1.0.0','library':'lowcode-engine-vue-material-dashboard',
  // 'urls':['http://127.0.0.1:9002\\index.js']}];
  // const packages = JSON.parse(window.localStorage.getItem('packages') || '[]');
  // const projectSchema = JSON.parse(window.localStorage.getItem('projectSchema') || '{}');



  const lowcodeWindow = await getLowcodeWidnow(lowcodeWindowNo);
  const projectSchema = await getProjectSchema(lowcodeWindowNo);
  let materialInfos = lowcodeWindow.materialInfos;
  const { componentsMap: componentsMapArray = [], componentsTree = [] } = projectSchema;

  const componentsMap = {};
  componentsMapArray.forEach(component => {
    componentsMap[component.componentName] = component;
  });

  const libraryMap = {};
  const libraryAsset = [];
  // packages.forEach(({ package: _package, library, urls, renderUrls }) => {
  //   libraryMap[_package] = library;
  //   if (renderUrls) {
  //     libraryAsset.push(renderUrls);
  //   } else if (urls) {
  //     libraryAsset.push(urls);
  //   }
  // });

  if(materialInfos == null || materialInfos.length == 0){
    Notify.error('错误', '低代码定义中缺少物料的定义，请在低代码编辑器选择使用到的物料。', false);
    return;
  }

  for(let i = 0, size = materialInfos.length; i < size; i ++) {
    let materialInfo = materialInfos[i];
    const assets = await fetch(materialInfo.url).then(res =>
      res.json(),
    );
    let packages = assets.packages;
    console.log(packages);
    if(packages != null && packages.length > 0){
      packages.forEach(item => {
        libraryMap[item.package] = item.library;
        if (item.renderUrls) {
          libraryAsset.push(item.renderUrls);
        } else if (item.urls) {
          libraryAsset.push(item.urls);
        }
      });
    }
  }


  await new AssetLoader().load(libraryAsset);
  const components = await buildComponents(libraryMap, componentsMap);

  return { schema: componentsTree[0], components };
};

export {
  init,
};