import { ProjectInfo } from "#/project";
import  { update, isArray, isPlainObject, get, isEqual } from 'lodash';
/**
 * 批量恢复记录
 * 
 * @param projectInfo 项目信息
 * @param path 路径
 * @param changeValue 修改值
 * @returns 
 */
export const recoverRecord = (projectInfo: ProjectInfo, path: string = '', changeValue: any) => {
  const target = get(projectInfo, path);
  // 数组处理
  if (isArray(changeValue)) {
    // 判断两个数组是否一致
    const originKeys = target.map((item: any) => item.key);
    const changeKeys = changeValue.map((item: any) => item.key);
    if(!isEqual(originKeys, changeKeys)) {
      // 两个数组不一致时，移除原数组多余的数据
      target.forEach((item: any) => {
        if(!changeKeys.includes(item.key)) {
          const index = target.findIndex((val: any) => val.key === item.key);
          target.splice(index, 1);
        }
      });
      // 添加新的数据
      changeValue.forEach((item: any) => {
        if(!originKeys.includes(item.key)) {
          target.push(item);
        }
      });
    }

    // 遍历更新
    changeValue.forEach((item: any) => {
      const index = target.findIndex((val: any) => val.key === item.key);
      recoverRecord(projectInfo, `${path}[${index}]`, item);
    });

    return;
  }

  // 对象处理
  if (isPlainObject(changeValue)) {
    // 删除多余的属性
    if(path && Object.keys(changeValue).length < Object.keys(target || {}).length) {
      Object.keys(target).forEach((key) => {
        if(!Object.keys(changeValue).includes(key)) {
          delete target[key];
          update(projectInfo, path, () => target);
        }
      });
    }
    Object.keys(changeValue).forEach((key) => {
      recoverRecord(projectInfo, `${path}${path && '.'}${key}`, changeValue[key]);
    });
    return;
  }

  // 其他
  const originValue = get(projectInfo, path);
  if(originValue !== changeValue) {
    update(projectInfo, path, () => changeValue);
  }
}