const express = require("express");
const router = express.Router();
const { query } = require("../mods/dbconnection");
const config = require("../conf/config.json");
const moment = require("moment");

const authMiddleware = require("../middleware/authMiddleware");
const adminMiddleware = require("../middleware/adminMiddleware");

// 코드(숫자),의미,상세 설명
// 1000,SUCCESS,모든 작업 정상 처리
// 2001,EMPTY_INPUT,입력값이 없음
// 2002,NOT_FOUND,내용을 찾을 수 없음
// 2003,DUPLICATED,중복된 내용존재 존재함

router.get("/", authMiddleware, adminMiddleware, async (req, res) => {
  const q1 = `SELECT u.user_id, u.user_name FROM \`${config.dbName.boas_se}\`.tb_user AS u, \`${config.dbName.boas_se}\`.tb_dept AS d, \`${config.dbName.boas_se}\`.tb_account AS a WHERE u.dept_id = d.dept_id AND u.account_id = a.account_id AND u.account_id < 3 AND u.is_active = "Y";`;
  const q2 = `SELECT e.*, u.user_name, d.dept_name FROM \`${config.dbName.boas_se}\`.tb_eqpt AS e, \`${config.dbName.boas_se}\`.tb_user AS u, \`${config.dbName.boas_se}\`.tb_dept AS d WHERE e.user_id = u.user_id AND u.dept_id = d.dept_id;`;
  const userList = await query(q1);
  const eqptList = await query(q2);
  const ret = { userList, eqptList };
  console.log(ret);
  res.json(ret);
});

router.post("/info", authMiddleware, adminMiddleware, async (req, res) => {
  const eqpt_name = req.body.eqpt_name;
  const eqpt_info = req.body.eqpt_info;
  const reg_dt = moment().format("YYYY-MM-DD HH:mm:ss");
  const upt_dt = moment().format("YYYY-MM-DD HH:mm:ss");
  const eqpt_region = req.body.eqpt_region;
  const eqpt_bld = req.body.eqpt_bld;
  const eqpt_floor = req.body.eqpt_floor;
  const user_id = req.body.user_id;
  const is_active = req.body.is_active;

  console.log(
    eqpt_name,
    eqpt_info,
    reg_dt,
    upt_dt,
    eqpt_region,
    eqpt_bld,
    eqpt_floor,
    user_id,
    is_active,
  );

  let eqpt_id = "eqpt_001";

  try {
    // eqpt_ 형식의 ID만 조회
    const eqptList = await query(
      `
      SELECT eqpt_id
      FROM \`${config.dbName.boas_se}\`.tb_eqpt
      WHERE eqpt_id LIKE 'eqpt_%'
      ORDER BY CAST(SUBSTRING_INDEX(eqpt_id, '_', -1) AS UNSIGNED) DESC
      LIMIT 1;
      `
    );

    // 기존 eqpt_XXX 데이터가 존재하면 다음 번호 생성
    if (eqptList.length > 0) {
      const lastNumber = parseInt(
        eqptList[0].eqpt_id.split("_")[1],
        10
      );

      eqpt_id =
        "eqpt_" +
        String(lastNumber + 1).padStart(3, "0");
    }

    console.log(eqpt_id);

    const ist_param = {
      eqpt_id,
      reg_dt,
      upt_dt,
    };

    if (eqpt_name) ist_param.eqpt_name = eqpt_name;
    if (eqpt_info) ist_param.eqpt_info = eqpt_info;
    if (eqpt_region) ist_param.eqpt_region = eqpt_region;
    if (eqpt_bld) ist_param.eqpt_bld = eqpt_bld;
    if (eqpt_floor) ist_param.eqpt_floor = eqpt_floor;
    if (user_id) ist_param.user_id = user_id;

    // false, 0 값도 저장 가능하도록 수정
    if (is_active !== undefined) {
      ist_param.is_active = is_active;
    }

    const result = await query(
      `INSERT INTO \`${config.dbName.boas_se}\`.tb_eqpt SET ?;`,
      [ist_param],
    );

    console.log(result);

    res.json(result);

  } catch (error) {
    console.log(error);
    res.status(409).json(error);
  }
});

router.put("/info", authMiddleware, adminMiddleware, async (req, res) => {
  const eqpt_id = req.body.eqpt_id;
  const eqpt_name = req.body.eqpt_name;
  const eqpt_info = req.body.eqpt_info;
  const upt_dt = moment().format("YYYY-MM-DD HH:mm:ss");
  const eqpt_region = req.body.eqpt_region;
  const eqpt_bld = req.body.eqpt_bld;
  const eqpt_floor = req.body.eqpt_floor;
  const user_id = req.body.user_id;
  const is_active = req.body.is_active;
  console.log(
    eqpt_id,
    eqpt_name,
    eqpt_info,
    upt_dt,
    eqpt_region,
    eqpt_bld,
    eqpt_floor,
    user_id,
    is_active,
  );

  var upt_param = {};
  if (!eqpt_id) {
    const msg = "Equipment ID is required.";
    console.log(msg);
    res.status(500).json(msg);
    return;
  }
  if (eqpt_name) upt_param.eqpt_name = eqpt_name;
  if (eqpt_info) upt_param.eqpt_info = eqpt_info;
  if (eqpt_region) upt_param.eqpt_region = eqpt_region;
  if (eqpt_bld) upt_param.eqpt_bld = eqpt_bld;
  if (eqpt_floor) upt_param.eqpt_floor = eqpt_floor;
  if (user_id) upt_param.user_id = user_id;
  if (is_active) upt_param.is_active = is_active;

  const eqpt_cnt = await query(
    `SELECT * FROM \`${config.dbName.boas_se}\`.tb_eqpt WHERE eqpt_id = ?;`,
    [eqpt_id],
  );

  if (eqpt_cnt == 0) {
    const msg = `Equipment[${eqpt_id}] not found.`;
    console.log(msg);
    res.status(404).json({ msg });
    return;
  }

  console.log(upt_param);

  try {
    const result = await query(
      `UPDATE \`${config.dbName.boas_se}\`.tb_eqpt SET ? WHERE eqpt_id = ?;`,
      [upt_param, eqpt_id],
    );
    console.log(result);
    res.json(result);
  } catch (error) {
    console.log(error);
    res.status(409).json(error);
  }
});

router.get("/simpleEqptList", async (req, res) => {
  const q1 = 
    `SELECT * FROM \`${config.dbName.boas_se}\`.tb_eqpt;`;

  const eqptList = await query(q1);

  const ret = { eqptList };
  console.log(ret);
  res.json(ret);
});

router.post("/check", authMiddleware, adminMiddleware, async (req, res) => {
  const eqpt_name = req.body.eqpt_name;

  const dept_cnt = await query(
    `SELECT * FROM \`${config.dbName.boas_se}\`.tb_eqpt WHERE eqpt_name = ?;`,
    [eqpt_name],
  );

  var msg = "";
  var ret_code = 1000;

  if (dept_cnt == 0) {
    msg = `Available Name`;
  } else {
    msg = `This name[${eqpt_name}] is already taken.`;
    ret_code = 0;
    res.status(409);
  }

  console.log(ret_code, msg);
  res.json({ ret_code, msg });
});

router.delete("/delete", authMiddleware, adminMiddleware, async (req, res) => {
  const eqpt_id = req.body.eqpt_id;

  try {
    const eqpt_cnt = await query(
      `SELECT * FROM \`${config.dbName.boas_se}\`.tb_eqpt WHERE eqpt_id = ?;`,
      [eqpt_id],
    );

    if(eqpt_cnt === 0){
      const msg = `Eqpt[${eqpt_id}] not found.`;
      console.log(msg);
      res.status(404).json({ msg });
      return;
    }

    const result = await query(
      `DELETE FROM \`${config.dbName.boas_se}\`.tb_eqpt WHERE eqpt_id = ?;`,
      [eqpt_id],
    );
    console.log(result);
    res.json(result);
  } catch (error) {
    console.log(error);
    res.status(409).json(error);
  }
});
module.exports = router;
