const { query } = require("../mods/dbconnection");
const { checkExist, createTable } = require("../mods/common");
const config = require("../conf/config.json");
const moment = require("moment");

// const itv = 1 * 60 * 1000    // 1분;
const itv = 5 * 1000; // 10초;

const getOldMesData = async (tbName, pkName, cehckColumn) => {
  const dbName = config.dbName.jinsungmes;
  const caputreLog = await query(
    `SELECT check_key FROM \`${config.dbName.boas_se}\`.tb_capture_log WHERE db_name = '${dbName}' AND tb_name = '${tbName}';`,
  );
  console.log(
    `getErpCuttingMaster : ${dbName}-${tbName}, caputreLog = `,
    caputreLog,
  );

  let oldMesData = null;

  if (caputreLog.length == 0) {
    oldMesData = await query(
      `SELECT * FROM \`${dbName}\`.${tbName} ORDER BY ${pkName} ASC LIMIT 100;`,
    );
  } else {
    oldMesData = await query(
      `SELECT * FROM \`${dbName}\`.${tbName} WHERE ${pkName} > ? ORDER BY ${pkName} ASC LIMIT 100;`,
      [parseInt(caputreLog[0].check_key)],
    );
  }

  if (oldMesData.length == 0) {
    console.log(`The table[${dbName}.${tbName}]'s oldMesData is empty!!`);
    return;
  }

  let tempDt = null;
  let pk = null;
  for (let idx in oldMesData) {
    pk = oldMesData[idx][`${pkName}`];
    if (!oldMesData[idx][cehckColumn]) {
      console.log(`${cehckColumn} is NULL!!`);
      break;
    }

    let curDt = moment(oldMesData[idx][cehckColumn]).format("YYYYMMDD");
    let newTbName = `${tbName}_${curDt}`;
    // console.log(newTbName);

    if (tempDt == null || curDt != tempDt) {
      tempDt = curDt;
      await createTable(config.dbName.boas_se, newTbName, `${tbName}_ref`);

      if ((await checkExist(config.dbName.boas_se, newTbName)) == false) {
        console.log(
          `The table[${config.dbName.boas_se}.${newTbName}] does not exist!!`,
        );
        break;
      }
    }

    try {
      await query(
        `INSERT INTO \`${config.dbName.boas_se}\`.${newTbName} SET ?;`,
        [oldMesData[idx]],
      );
    } catch (error) {
      console.log(error);
      return;
    }
  }

  try {
    let istDt = moment().format("YYYY-MM-DD HH:mm:ss");
    await query(
      `INSERT INTO \`${config.dbName.boas_se}\`.tb_capture_log VALUES (?, ?, ?, ?, ?)
      ON DUPLICATE KEY UPDATE check_key = ?, upt_dt = ?;`,
      [dbName, tbName, pk.toString(), istDt, istDt, pk.toString(), istDt],
    );
  } catch (error) {
    console.log(error);
  }
  console.log("Done.");
};

// setInterval(async () => {
//   console.log("Start cehckMes.");
//   await getOldMesData("alarm_log", "id", "created_at");
//   await getOldMesData("boxten_compen_main", "id", "updated_at");
//   await getOldMesData("boxten_order_main", "id", "updated_at");
//   await getOldMesData("boxten_unmeasurement_main", "id", "updated_at");
//   await getOldMesData("company_purchase", "pk", "updated_at");
//   await getOldMesData("company_sales", "pk", "updated_at");
//   await getOldMesData("compen_list", "id", "compen_dt");
//   await getOldMesData("cutting_jobs", "no", "structure_dt");
//   await getOldMesData("cutting_master", "id", "updated_at");
//   await getOldMesData("erp_cutting_details_new", "no", "updated_at");
//   await getOldMesData("erp_cutting_jobs", "no", "structure_dt");
//   await
//   await
//   await
//   await
//   await getOldMesData("erp_cutting_master", "id", "updated_at");
//   console.log("Pause cehckMes.");
// }, itv);

getOldMesData("erp_cutting_jobs", "no", "structure_dt");
