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

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

const getOldMesData = async (tbName, pkName) => {
  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 pk = null;
  for (let idx in oldMesData) {
    pk = oldMesData[idx][`${pkName}`];
    if ((await checkExist(config.dbName.boas_se, tbName)) == false) {
      console.log(
        `The table[${config.dbName.boas_se}.${tbName}] does not exist!!`,
      );
      break;
    }

    const istParam = lodash.cloneDeep(oldMesData[idx]);
    delete istParam[`${pkName}`];

    try {
      await query(
        `INSERT INTO \`${config.dbName.boas_se}\`.${tbName} SET ?
        ON DUPLICATE KEY UPDATE ?;`,
        [oldMesData[idx], istParam],
      );
    } 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");
//   await getOldMesData("boxten_compen_main", "id");
//   await getOldMesData("boxten_order_main", "id");
//   await getOldMesData("boxten_unmeasurement_main", "id");
//   await getOldMesData("company_purchase", "pk");
//   await getOldMesData("company_sales", "pk");
//   await getOldMesData("compen_list", "id");
//   await getOldMesData("cutting_master", "id");
//   await getOldMesData("cutting_jobs", "no");
//   await getOldMesData("erp_cutting_details_new", "no");
//   await getOldMesData("erp_cutting_master", "id");
//   await getOldMesData("erp_cutting_jobs", "no");
//   await getOldMesData("hmi_login_log", "id");
//   await getOldMesData("install_list", "id");
//   await getOldMesData("maintenance_list", "id");
//   await getOldMesData("mes_log", "id");
//   await getOldMesData("receiving_orders", "id");
//   await getOldMesData("rope_cancels", "id");
//   await getOldMesData("rope_orders", "id");
//   await getOldMesData("rope_stock", "id");
//   await getOldMesData("rope_used_list", "id");
//   await getOldMesData("sales_orders", "id");
//   await getOldMesData("stop_log", "id");
//   await getOldMesData("sync_config", "task_key");
//   console.log("Pause cehckMes.");
// }, itv);

// getOldMesData("sync_config", "task_key");

// hmi_user : 키값 user_id가 varchar이고 sync_date가 겹치는 값이 많음. pk 없음
