import { TreeType } from "../treeDataRelationFn/type";
import { isObject } from "lodash";
export function saveOldValueSchema(target) {}
export function getPageTarge(item) {
  var result;
  if (item.isPage || item.node.isPage) {
    result = item;
  } else if (item.node.parent) {
    result = getPageTarge(item.node.parent);
  }
  return result;
}

/**
 * 该设置器具备更改schema中的state数据
 * @param field
 */
export function getNewSchemaState(schema, newValue, oldValue, type) {
  var lifeCycles = Object.assign({}, schema.lifeCycles || {});
  var stateObj = Object.assign({}, schema.newState || {});
  if (type === TreeType.state) {
    stateObj = handleStateData(stateObj, newValue, oldValue);
  } else if (type === TreeType.dataSourceMap) {
    stateObj = handleDataSource(stateObj, newValue, oldValue);
  }
  lifeCycles.constructor = createNewStateData(stateObj);
  schema.lifeCycles = lifeCycles;
  schema.newState = stateObj;
  if (schema.originCode !== undefined) {
    delete schema.originCode;
  }
  return schema;
}

/**
 * 处理state
 * @param stateObj 
 * @param newValue 
 * @param oldValue 
 * @returns 
 */
function handleStateData(stateObj, newValue, oldValue) {
  if (Object.keys(stateObj).length) {
    stateObj[TreeType.state] = alterStateData(stateObj[TreeType.state], newValue, oldValue);
  } else {
    stateObj[TreeType.state] = {};
    stateObj[TreeType.state][newValue] = "";
  }
  return stateObj;
}

/**
 * 处理数据源
 */
function handleDataSource(stateObj, newValue, oldValue) {
  if (stateObj[TreeType.dataSourceMap] && Object.keys(stateObj[TreeType.dataSourceMap]).length) {
    stateObj[TreeType.dataSourceMap][newValue] = {};
  } else {
    stateObj[TreeType.dataSourceMap] = {};
    stateObj[TreeType.dataSourceMap][newValue] = {};
  }
  return stateObj;
}
function alterStateData(state, key, oldKey) {
  var result = state;
  if (isObject(state)) {
    // 删除老数据
    if (result[oldKey] !== undefined) {
      delete result[oldKey];
    }
    result[key] = "";
  }
  return result;
}
function createNewStateData(state) {
  var data = JSON.stringify(state);
  return {
    source: "function constructor() {\n  this.state =" + data + ";\n}",
    type: "JSFunction",
    value: "function constructor() {\n  this.state =" + data + ";\n}"
  };
}