"use strict";

exports.__esModule = true;
exports.getNewSchemaState = getNewSchemaState;
exports.getPageTarge = getPageTarge;
exports.saveOldValueSchema = saveOldValueSchema;
var _type = require("../treeDataRelationFn/type");
var _lodash = require("lodash");
function saveOldValueSchema(target) {}
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
 */
function getNewSchemaState(schema, newValue, oldValue, type) {
  var lifeCycles = Object.assign({}, schema.lifeCycles || {});
  var stateObj = Object.assign({}, schema.newState || {});
  if (type === _type.TreeType.state) {
    stateObj = handleStateData(stateObj, newValue, oldValue);
  } else if (type === _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[_type.TreeType.state] = alterStateData(stateObj[_type.TreeType.state], newValue, oldValue);
  } else {
    stateObj[_type.TreeType.state] = {};
    stateObj[_type.TreeType.state][newValue] = "";
  }
  return stateObj;
}

/**
 * 处理数据源
 */
function handleDataSource(stateObj, newValue, oldValue) {
  if (stateObj[_type.TreeType.dataSourceMap] && Object.keys(stateObj[_type.TreeType.dataSourceMap]).length) {
    stateObj[_type.TreeType.dataSourceMap][newValue] = {};
  } else {
    stateObj[_type.TreeType.dataSourceMap] = {};
    stateObj[_type.TreeType.dataSourceMap][newValue] = {};
  }
  return stateObj;
}
function alterStateData(state, key, oldKey) {
  var result = state;
  if ((0, _lodash.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}"
  };
}