const DETAIL_COMPARE_FIELDS = [
  "zdEn",
  "taZdMc",
  "zdCh",
  "zdType",
  "zdLength",
  "treeFlag",
  "referenceZd",
  "relationZd",
  "refServiceName",
  "toTaBmZd",
  "zdTypeValues",
  "required",
  "enabled",
  "generateCode",
  "atened",
  "updateIgnore",
  "codeType",
  "orders",
];

function isNull(val) {
  return val == null || val === "";
}

function isSameValue(val1, val2) {
  if (isNull(val1) && isNull(val2)) return true;
  return val1 === val2;
}

export function getDetailRowKey(row, index = 0) {
  if (!row) return `idx_${index}`;
  return row.zdEn || row.taZdMc || `idx_${row.orders ?? index}`;
}

export function buildDetailDiffMaps(preRows = [], curRows = []) {
  const preMap = new Map();
  const curMap = new Map();

  preRows.forEach((row, index) => {
    preMap.set(getDetailRowKey(row, index), row);
  });
  curRows.forEach((row, index) => {
    curMap.set(getDetailRowKey(row, index), row);
  });

  const preCellDiff = {};
  const curCellDiff = {};
  const allKeys = new Set([...preMap.keys(), ...curMap.keys()]);

  allKeys.forEach((key) => {
    const preRow = preMap.get(key);
    const curRow = curMap.get(key);

    if (!preRow) {
      DETAIL_COMPARE_FIELDS.forEach((field) => {
        curCellDiff[`${key}__${field}`] = "add";
      });
      return;
    }

    if (!curRow) {
      DETAIL_COMPARE_FIELDS.forEach((field) => {
        preCellDiff[`${key}__${field}`] = "delete";
      });
      return;
    }

    DETAIL_COMPARE_FIELDS.forEach((field) => {
      if (!isSameValue(preRow[field], curRow[field])) {
        preCellDiff[`${key}__${field}`] = "change";
        curCellDiff[`${key}__${field}`] = "change";
      }
    });
  });

  return { preCellDiff, curCellDiff };
}
