import { project } from "@alilc/lowcode-engine";
import { IPublicEnumTransformStage } from "@clc/lowcode-types";
import { PageStateFlag } from "../treeDataRelationFn/type";
import { get, set } from "lodash";
/**
 * 该设置器具备更改schema中的state数据
 * @param field
 */
export function setSchemaState(props, oldValue, type) {
  var _schema$componentsTre;
  var schema = project.exportSchema(IPublicEnumTransformStage.Save);
  var state = Object.assign({}, ((_schema$componentsTre = schema.componentsTree[0]) === null || _schema$componentsTre === void 0 ? void 0 : _schema$componentsTre.state) || {});
  var newState = handleStateData(state, props.value, oldValue, type);
  if (newState) {
    var _project$simulatorHos;
    schema.componentsTree[0].state = newState;
    if (schema.componentsTree[0].originCode !== undefined) {
      delete schema.componentsTree[0].originCode;
    }
    project.importSchema(schema);
    (_project$simulatorHos = project.simulatorHost) === null || _project$simulatorHos === void 0 ? void 0 : _project$simulatorHos.rerender();
  }
}

/**
 * 配置给mate中设置数据注入能注入到schema中的state数据里面
 * @param target 
 * @param value 
 */
export function setSchemaStateInMeta(target, value, type) {
  // const schema = project.exportSchema(IPublicEnumTransformStage.Save);
  // console.log('pageProject', schema)

  // let state = Object.assign({}, schema.componentsTree[0].state || {});
  // let newState = handleStateDataNew(state, value, type)

  // if (newState) {
  //     schema.componentsTree[0].state = newState;
  //     if (schema.componentsTree[0].originCode !== undefined) {
  //         delete schema.componentsTree[0].originCode;
  //     }
  //     project.importSchema(schema);
  //     // project.simulatorHost?.rerender();
  //     setTimeout(() => {
  //         target.node.document?.modalNodesManager?.setVisible(target.node)
  //     },100)
  // }
}
function handleStateData(state, newValue, oldValue, type) {
  if (type === PageStateFlag.State || type === PageStateFlag.Modal) {
    var stateStr = get(state, type + ".value") || '';
    var stateObj = stateStr.length ? JSON.parse(stateStr) : {};
    if (get(stateObj, "" + oldValue) !== undefined) {
      delete stateObj[oldValue];
    }
    var data = '';
    if (type === PageStateFlag.Modal) {
      // 弹框的数据初始化
      var dataValue = {
        visible: false,
        params: {}
      };
      data = dataValue;
    }
    set(stateObj, "" + newValue, data);
    var expObj = {
      "type": "JSExpression",
      "value": JSON.stringify(stateObj)
    };
    set(state, "" + type, expObj);
    return state;
  }
  return null;
}