/*
 * 로그아웃
 */
const logout = function () {
  ajax_json({
    url: "/inc/common.ajax.php",
    type: "POST",
    data: { mode: "memberLogout" },
    success: function (data) {
      if (data.code) {
        kuls_alert("로그아웃 되었습니다.", function () {
          location.href = "/ksvc/";
        });
      }
    },
    error: function (request, status, error) {
      kuls_alert(error.message);
    },
  });
};

// 사이드메뉴
const side_menu_load = function (menu_code) {
  ajax_json({
    url: "/inc/common.ajax.php",
    type: "POST",
    data: {
      mode: "getSiteMenuList",
      menu_code: menu_code,
    },
    success: function (data) {
      if (data.code) {
        jQuery(".side-nav .side-menu").fancytree({
          activeVisible: true,
          clickFolderMode: 3,
          source: data.data,

          // activate: function(e, data){
          //   if( !data.node.folder ){
          //     location.href = data.node.data.href || '###';
          //   }
          // },

          // createNode: function(event, data) {
          //   // 노드 생성 후 span을 a로 변경
          //   // let node = data.node;
          //   // let spanTag = $(node.span);
          //   //
          //   // let aTag = $("<a href='http://hymes.kuls.co.kr/ksvc/base/worker/worker.php' class='fancytree-node fancytree-exp-n fancytree-ico-c'></a>").html(spanTag.find("> span.fancytree-title").html());
          //   // spanTag.find("> span.fancytree-title").replaceWith(aTag);
          // },
          click: function (event, data) {
            if (!data.node.folder) {
              location.href = data.node.data.href || "###";
            }
          },
        });
      }
    },
    error: function (request, status, error) {},
    complete: function (request, status) {

      jQuery(".side-nav").on("click", "a", function (e) {
        e.preventDefault();
      });

      
      jQuery(".side-nav").on("click", ".node-side-nav", function (e) {
        if (jQuery(this).find(".expand-icon").length == 0) {
          let href = jQuery(this).find("> a").attr("href");
          href && (location.href = href);
        };
      });
      
      if (jQuery(".fold-btn-container").length) {

        const container = jQuery(".container");
        // container 에 on 클래스: 메뉴가 접힌상태면, 서브메뉴는 하나씩만 열리고 평소에는 닫아주기
        if(container.hasClass("on")){
          jQuery(".side-nav .side-menu").fancytree("option", "autoCollapse", true);
          
          if (jQuery(".side-nav .side-menu").fancytree("instance")) {
            jQuery.ui.fancytree.getTree(".side-nav .side-menu").expandAll(false);
          }
        }else{
          jQuery(".side-nav .side-menu").fancytree("option", "autoCollapse", false);
        }
        
        // 닫힘 버튼 클릭하면, container에 on버튼 붙이고 서브메뉴는 위와 동일하게 작동
        jQuery(".fold-btn-container").on("click", function() {
          const sidevar = window.localStorage.getItem('sidevar');
          if(sidevar){
            window.localStorage.removeItem('sidevar');
            jQuery(".side-nav .side-menu").fancytree("option", "autoCollapse", false);
            container.removeClass("on");
          }else{
            window.localStorage.setItem('sidevar','on');
            jQuery(".side-nav .side-menu").fancytree("option", "autoCollapse", true);
  
            if (jQuery(".side-nav .side-menu").fancytree("instance")) {
              jQuery.ui.fancytree.getTree(".side-nav .side-menu").expandAll(false);
            }
            container.addClass("on");
          }

          // const container = jQuery(".container");

          // if (container.hasClass("on")) {

          //   container.removeClass("on");
          //   jQuery(".side-nav .side-menu").fancytree("option", "autoCollapse", false);

          // } else {

          //   container.addClass("on");
          //   jQuery(".side-nav .side-menu").fancytree("option", "autoCollapse", true);

          //   if (jQuery(".side-nav .side-menu").fancytree("instance")) {
          //     jQuery.ui.fancytree.getTree(".side-nav .side-menu").expandAll(false);
          //   }
          // }
        });
      }
    },
  });
};

const cont_hfix = function () {
  jQuery(".cont_hfix").css("height", 0);
  let win_h = jQuery(window).outerHeight();
  jQuery(".cont_hfix")
    .toArray()
    .forEach((tgt) => {
      let cont_y = jQuery(tgt).offset().top;
      let cont_height = win_h - cont_y - 20;
      jQuery(tgt).css("height", cont_height);
    });
};

const cont_hfix_page = function () {
  jQuery(".cont_hfix_page").css("height", 0);
  let win_h = jQuery(window).outerHeight();
  jQuery(".cont_hfix_page")
    .toArray()
    .forEach((tgt) => {
      let cont_y = jQuery(tgt).offset().top;
      let cont_height = win_h - cont_y - 20;
      jQuery(tgt).css("height", cont_height);
    });
};

const show_spinner = function () {
  document.getElementById("loading_div").classList.remove("d-none");
};

const hide_spinner = function () {
  document.getElementById("loading_div").classList.add("d-none");
};

const pop_filedown = function (file_url, file_ext) {
  let preview_type = [
    "pdf",
    "jpg",
    "jpeg",
    "png",
    "gif",
    "tiff",
    "jfif",
    "bmp",
  ];
  if (preview_type.indexOf(file_ext) !== -1) {
    vnLoad(
      "",
      "/ksvc/inc/popup.php",
      "#pop_file_preview",
      function (loadHtml) {
        previewModal = kuls_modal(loadHtml, {
          resizable: true,
          dontclose: true,
        });
        if (file_ext == "pdf") {
          document.querySelector("#preview_frame").src =
            "/include/vendor/pdfjs/web/viewer.html?file=" +
            encodeURIComponent(file_url);
        } else {
          document.querySelector("#preview_frame").src =
            "/include/vendor/pdfjs/web/imgviewer.php?file=" +
            encodeURIComponent(file_url);
        }
      }
    );
  } else {
    location.href = file_url;
  }
};

jQuery(document).ready(function () {
  // localstorage에 sidevar가 있으면 container에 on 클래스 붙이기. 
  const container = jQuery(".container");
  const sidevar = window.localStorage.getItem('sidevar');
  if(sidevar){
    container.addClass("on");
  }else{
    container.removeClass("on");
  }
  if (jQuery(".side-nav").length) {
    side_menu_load(menu_code);
  }

  cont_hfix();
  cont_hfix_page();
});

jQuery(window).on("resize", function () {
  cont_hfix();
  cont_hfix_page();
});

jQuery("#log_out_btn").on("click", function () {
  kuls_confirm("로그아웃", "정말 로그아웃 하시겠습니까?", () => {
    logout();
  });
});

jQuery(document).on("focus", ".timepicker", function (e) {
  jQuery(e.target).timepicker({
    show2400: true,
    timeFormat: "H:i",
    showOn: ["click"],
  });
});



// if (document.getElementById("hamburger_icon")) {
//   document.getElementById("hamburger_icon").addEventListener("click", () => {
//     if (
//       document.getElementById("frame_main").classList.contains("full_width")
//     ) {
//       document.getElementById("frame_main").classList.remove("full_width");
//     } else {
//       document.getElementById("frame_main").classList.add("full_width");
//     }
//   });
// }

/* tabulator 페이징 처리
 * 1. sp 변경
 * 2.1 ajax.php 에 $params 내 page 변수 추가,
 * 2.2 ajax.php 에 $row['LIST_NUM'] 추가
 * 3.1 tabulator 옵션에 footerElement 추가
 * 3.2 filter 무효화
 * 3.3 #bntListSearch 조회버튼 및 이벤트 추가
 * 3.4 getMainList  ajax 에 page 옵션추가
 * 3.5 success에 putPagiNation({}) 실행추가
 * 4. sort 기능
 * 4.1 columnDefaults //컬럼 공통 규칙에  sorter:()=>{}, headerSort: false, 속성부여
 * 4.2 columnSort 함수 추가 확인
 * 4.3 headerClick 이벤트에 columnSort 함수 설정
 * 4.4 sort 가능한 컬럼에 headerSort: true  속성 부여
 * */
const putPagiNation = function (conf) {
  if (!conf.TARGET) return false;
  conf.NOW_PAGE = conf.NOW_PAGE || 1;
  conf.PREB_PAGE = conf.PREB_PAGE || 1;
  conf.NEXB_PAGE = conf.NEXB_PAGE || 1;
  conf.LAST_PAGE = conf.LAST_PAGE || 1;
  conf.PAGE_LISTS = conf.PAGE_LISTS || [1];

  let ul = document.createElement("ul");
  ul.className = "pagination justify-content-center align-items-center";

  ul.appendChild(
    putPageButton({
      ...conf,
      NOW_PAGE: 1,
      text: '<i class="fa-solid fa-angles-left"></i>',
    })
  );

  ul.appendChild(
    putPageButton({
      ...conf,
      NOW_PAGE: conf.PREB_PAGE,
      class: "mr-3",
      text: '<i class="fa-solid fa-angle-left"></i>',
    })
  );

  for (let i = 0; i < conf.PAGE_LISTS.length; i++) {
    ul.appendChild(
      putPageButton({
        ...conf,
        NOW_PAGE: conf.PAGE_LISTS[i],
        active: conf.PAGE_LISTS[i] == conf.NOW_PAGE,
        text: conf.PAGE_LISTS[i],
      })
    );
  }

  ul.appendChild(
    putPageButton({
      ...conf,
      NOW_PAGE: conf.NEXB_PAGE,
      class: "ml-3",
      text: '<i class="fa-solid fa-angle-right"></i>',
    })
  );

  ul.appendChild(
    putPageButton({
      ...conf,
      NOW_PAGE: conf.LAST_PAGE,
      text: '<i class="fa-solid fa-angles-right"></i>',
    })
  );

  document.querySelector(conf.TARGET).innerHTML = "";
  document.querySelector(conf.TARGET).appendChild(ul);
};

const putPageButton = function (conf) {
  let li = document.createElement("li");
  let a = document.createElement("a");
  let span = document.createElement("span");
  span.className = "f_page";
  a.className = "pn_link npage btn btn-outline-secondary";
  ["click", "keypress"].forEach((evt) =>
    a.addEventListener(evt, () => {
      conf.callback(conf);
    })
  );

  if (conf.active) {
    a.classList.add("active");
  }
  span.innerHTML = conf.text;
  a.appendChild(span);
  li.appendChild(a);
  conf.class && li.classList.add(conf.class);
  return li;
};



// const popItemList = function (columns, tabrow) {
//   // 팝업 템플릿 로드 후 모달 출력
//   vnLoad("", "/ksvc/inc/popup.inc.php", "#pop_item_search", function (loadHtml) {
//     let partnerModal = kuls_modal(loadHtml);

//     const fields = [
//       {
//         formatter: "rownum",
//         title: "No",
//         width: 40,
//         headerSort: false,
//         hozAlign: "center",
//       },
//       { field: "ITEM_CD", title: "품목코드", width: 80 },
//     ];

//     const table_pop_item_search = new Tabulator("#popItemList", {
//       layout: "fitColumns",
//       data: [], // 기본 데이터
//       height: "100%",
//       columns: fields, // 컬럼 설정
//       columnDefaults: {
//         vertAlign: "middle",
//         hozAlign: "center",
//         resizable: "header", // Resize 는 헤더에서만 가능
//         headerHozAlign: "center", // 헤더 정렬
//         headerSortTristate: true, // 정렬 => 정/역/초기화
//       },
//       headerSortElement: "<i class='bi'></i>", // 정렬 아이콘
//     });

//     const getPopItemList = function () {
//       // 리스트 불러오기
//       ajax_json({
//         url: "/ksvc/inc/common.ajax.php",
//         data: { mode: "getItemList" },
//         success: function (data) {
//           if (data.code) {
//             table_pop_item_search.setData(data.data);
//           }
//         },
//         error: function (request, status, error) {
//           // kuls_alert(error.message);
//         },
//       });
//     };

//     // const setTableFilter = function () {
//     //   // 검색어 필터 적용
//     //   let stxt = document.querySelector("#awn-popup-wrapper input[name=stxt]").value.trim();
//     //   let sgrp = document.querySelector("#awn-popup-wrapper select[name=sgrp]").value.trim();
//     //   table_pop_item_search.setFilter(function (data) {
//     //     return (
//     //       (!sgrp || data["SALES_GRP"] === sgrp) &&
//     //       (!stxt ||
//     //         data["ITEM_CD"].search(new RegExp(stxt, "i")) !== -1)
//     //     );
//     //   }, "=", true);
//     // };

//     const setPopPartnerData = function (e, tgt) {
//       // Row 더블클릭 실행
//       let row = tgt._row;
//       if (tabrow) {
//         let uptjson = { _STATUS_: tabrow.getData()["_STATUS_"] || "U" };
//         Object.keys(columns).forEach((key) => {
//           if (key === "tgt_id") {
//             uptjson[columns[key]] = row.data["ITEM_CD"];
//           }
//         });
//         tabrow.updateData(uptjson);
//       } else {
//         if (document.querySelector(columns.tgt_id))
//           document.querySelector(columns.tgt_id).value = row.data["ITEM_CD"];
        
//         if (document.querySelector(columns.tgt_name))
//           document.querySelector(columns.tgt_name).dispatchEvent(new Event("change"));
//       }
//       partnerModal.delete();
//     };

//     document.querySelector("#awn-popup-wrapper [name=stxt]").addEventListener("keyup", function () {
//       // 검색어 입력 이벤트
//       setTableFilter();
//     });

//     // document.querySelector("#awn-popup-wrapper .btnPopSearch").addEventListener("click", getPopPartnerList);
//     // document.querySelector("#awn-popup-wrapper .btnPopInit").addEventListener("click", initPopPartnerData);

//     table_pop_item_search.on("rowDblClick", setPopPartnerData); // Row 더블클릭 이벤트
//     table_pop_item_search.on("tableBuilt", getPopItemList); // 초기 데이터 불러오기 이벤트
//   });
// };



const popPartnerList = function (columns, tabrow) {
  //tabrow 존재하면 (tabulator 필드명), 그외는 거래처코드 selector=>tgt_id, 거래처명 selector => 거래처명
  //팝업 템플릿 로드 후 모달 출력
  vnLoad(
    "",
    "/ksvc/inc/popup.inc.php",
    "#pop_partner_search",
    function (loadHtml) {
      let partnerModal = kuls_modal(loadHtml);

      let selecttag = document.querySelector("#sgrp");
      selecttag.options.length = 0;
      let opt = document.createElement("option");
      opt.value = "";
      opt.text = "- 전 체 -";
      selecttag.add(opt);
      Object.keys(varsSALES_GRP).forEach((key) => {
        opt = document.createElement("option");
        opt.value = key;
        opt.text = varsSALES_GRP[key];
        selecttag.add(opt);
      });

      const fields = [
        {
          formatter: "rownum",
          title: "No",
          width: 40,
          headerSort: false,
          hozAlign: "center",
        },
        {
          field: "SALES_GRP",
          title: "영업구분",
          width: 80,
          formatter: (cell) => varsSALES_GRP[cell.getValue()],
        },
        { field: "BP_CD", title: "거래처", width: 80 },
        { field: "BP_NM", title: "거래처명", width: 150 },
        { field: "REPRESN_NM", title: "대표자명", width: 100 },
        { field: "CURRENCY_CD", title: "거래화폐", width: 90 },
        {
          field: "PUR_FLG",
          title: "매입처",
          width: 70,
          formatter: tb_common_funtions.formatterSelCircleIcon,
        },
        {
          field: "SAL_FLG",
          title: "매출처",
          width: 70,
          formatter: tb_common_funtions.formatterSelCircleIcon,
        },
      ];

      const table_pop_partner_search = new Tabulator("#pop_partner_list", {
        layout: "fitColumns",
        data: [], //기본 데이터
        height: "100%",
        columns: fields, //컬럼 설정
        columnDefaults: {
          //컬럼 공통 규칙
          vertAlign: "middle",
          hozAlign: "center",
          resizable: "header", //Resize 는 헤더에서만 가능
          headerHozAlign: "center", //헤더 정렬
          headerSortTristate: true, //정렬 => 정/역/초기화
        },
        headerSortElement: "<i class='bi'></i>", //정렬 아이콘
      });

      const getPopPartnerList = function () {
        //리스트 불러오기
        ajax_json({
          url: "/ksvc/inc/common.ajax.php",
          data: { mode: "getPartnerList" },
          success: function (data) {
            if (data.code) {
              table_pop_partner_search.setData(data.data);
              if (columns.tgt_filter && columns.txt_filter) {
                document.querySelector(columns.tgt_filter).value =
                  columns.txt_filter;
                setTableFilter();
              }
            }
          },
          error: function (request, status, error) {
            //kuls_alert(error.message);
          },
        });
      };
      const setTableFilter = function () {
        //검색어 필터 적용
        let stxt = trim(
          document.querySelector("#awn-popup-wrapper input[name=stxt]").value
        );
        let sgrp = trim(
          document.querySelector("#awn-popup-wrapper select[name=sgrp]").value
        );
        table_pop_partner_search.setFilter(
          function (data) {
            return (
              (!sgrp || data["SALES_GRP"] === sgrp) &&
              (!stxt ||
                data["BP_CD"].search(RegExp(stxt, "is")) !== -1 ||
                data["BP_NM"].search(RegExp(stxt, "is")) !== -1 ||
                data["BP_FULL_NM"].search(RegExp(stxt, "is")) !== -1)
            );
          },
          "=",
          true
        );
      };
      const setPopPartnerData = function (e, tgt) {
        //Row 더블클릭 실행
        let row = tgt._row;
        if (tabrow) {
          let uptjson = { _STATUS_: tabrow.getData()["_STATUS_"] || "U" };
          Object.keys(columns).forEach((key) => {
            switch (key) {
              case "tgt_id":
                uptjson[columns[key]] = row.data["BP_CD"];
                break;
              case "tgt_name":
                uptjson[columns[key]] = row.data["BP_NM"];
                break;
              case "tgt_full_name":
                uptjson[columns[key]] =
                  row.data["BP_FULL_NM"] || row.data["BP_NM"];
                break;
              case "tgt_addr":
                uptjson[columns[key]] = row.data["ADDR1"];
                break;
              case "tgt_currency":
                uptjson[columns[key]] = row.data["CURRENCY_CD"];
                break;
              case "tgt_chid":
                uptjson[columns[key]] = row.data["BP_PRSN_ID"];
                break;
              case "tgt_chname":
                uptjson[columns[key]] = row.data["BP_PRSN_NM"];
                break;
              case "tgt_chmail":
                uptjson[columns[key]] = row.data["BP_PRSN_EMAIL"];
                break;
              case "tgt_chtel":
                uptjson[columns[key]] = row.data["BP_PRSN_TEL_NO"];
                break;
              case "tgt_chcell":
                uptjson[columns[key]] = row.data["BP_PRSN_CELL_NO"];
                break;
              case "tgt_chfax":
                uptjson[columns[key]] = row.data["BP_PRSN_FAX_NO"];
                break;
              case "tgt_portnm":
                uptjson[columns[key]] = row.data["PORT_NM"];
                break;
              case "tgt_sales_grp":
                uptjson[columns[key]] = row.data["SALES_GRP"];
                break;
            }
          });
          tabrow.updateData(uptjson);
          // if( tgt_id       && tabrow.getCell(tgt_id) )      tabrow.getCell(tgt_id).setValue(row.data['BP_CD']);
          // if( tgt_name     && tabrow.getCell(tgt_name))     tabrow.getCell(tgt_name).setValue(row.data['BP_NM']);
          // if( tgt_addr     && tabrow.getCell(tgt_addr))     tabrow.getCell(tgt_addr).setValue(row.data['ADDR1']);
          // if( tgt_currency && tabrow.getCell(tgt_currency)) tabrow.getCell(tgt_currency).setValue(row.data['CURRENCY_CD']);
        } else {
          if (document.querySelector(columns.tgt_id))
            document.querySelector(columns.tgt_id).value = row.data["BP_CD"];
          if (document.querySelector(columns.tgt_name))
            document.querySelector(columns.tgt_name).value = row.data["BP_NM"];
          if (document.querySelector(columns.tgt_full_name))
            document.querySelector(columns.tgt_full_name).value =
              row.data["BP_FULL_NM"] || row.data["BP_NM"];
          if (document.querySelector(columns.tgt_addr))
            document.querySelector(columns.tgt_addr).value = row.data["ADDR1"];
          if (document.querySelector(columns.tgt_currency))
            document.querySelector(columns.tgt_currency).value =
              row.data["CURRENCY_CD"];
          if (document.querySelector(columns.tgt_chid))
            document.querySelector(columns.tgt_chid).value =
              row.data["BP_PRSN_ID"];
          if (document.querySelector(columns.tgt_chname))
            document.querySelector(columns.tgt_chname).value =
              row.data["BP_PRSN_NM"];
          if (document.querySelector(columns.tgt_chmail))
            document.querySelector(columns.tgt_chmail).value =
              row.data["BP_PRSN_EMAIL"];
          if (document.querySelector(columns.tgt_chtel))
            document.querySelector(columns.tgt_chtel).value =
              row.data["BP_PRSN_TEL_NO"];
          if (document.querySelector(columns.tgt_chcell))
            document.querySelector(columns.tgt_chcell).value =
              row.data["BP_PRSN_CELL_NO"];
          if (document.querySelector(columns.tgt_chfax))
            document.querySelector(columns.tgt_chfax).value =
              row.data["BP_PRSN_FAX_NO"];
          if (document.querySelector(columns.tgt_portnm))
            document.querySelector(columns.tgt_portnm).value =
              row.data["PORT_NM"];
          if (document.querySelector(columns.tgt_sales_grp))
            document.querySelector(columns.tgt_sales_grp).value =
              row.data["SALES_GRP"];

          document.querySelector(columns.tgt_name) &&
            document
              .querySelector(columns.tgt_name)
              .dispatchEvent(new Event("change"));
        }
        partnerModal.delete();
      };
      const initPopPartnerData = function () {
        //Row 더블클릭 실행
        if (tabrow) {
          kuls_warning("거래처는 필수항목 입니다.");
        } else {
          if (document.querySelector(columns.tgt_id))
            document.querySelector(columns.tgt_id).value = "";
          if (document.querySelector(columns.tgt_name))
            document.querySelector(columns.tgt_name).value = "";
          if (document.querySelector(columns.tgt_addr))
            document.querySelector(columns.tgt_addr).value = "";
          if (document.querySelector(columns.tgt_currency))
            document.querySelector(columns.tgt_addr).value = "";
          if (document.querySelector(columns.tgt_chname))
            document.querySelector(columns.tgt_chname).value = "";
          if (document.querySelector(columns.tgt_chmail))
            document.querySelector(columns.tgt_chmail).value = "";
          if (document.querySelector(columns.tgt_chtel))
            document.querySelector(columns.tgt_chtel).value = "";
          if (document.querySelector(columns.tgt_chcell))
            document.querySelector(columns.tgt_chcell).value = "";
          if (document.querySelector(columns.tgt_chfax))
            document.querySelector(columns.tgt_chfax).value = "";
          if (document.querySelector(columns.tgt_portnm))
            document.querySelector(columns.tgt_portnm).value = "";
        }
        partnerModal.delete();
      };

      //document.querySelector("#awn-popup-wrapper .btnPopSearch").addEventListener("click",function() { //조회버튼 클릭 이벤트
      //  getPopPartnerList();
      //});
      //document.querySelector("#awn-popup-wrapper .btnPopInit").addEventListener("click",function() { //조회버튼 클릭 이벤트
      //  initPopPartnerData();
      //});
      document
        .querySelector("#awn-popup-wrapper [name=stxt]")
        .addEventListener("keyup", function () {
          //검색어 입력 이벤트
          setTableFilter();
        });
      document
        .querySelector("#awn-popup-wrapper [name=sgrp]")
        .addEventListener("change", function () {
          //영업분류 변경 이벤트
          setTableFilter();
        });
      ["click", "keypress"].forEach((evt) =>
        document
          .querySelector("#awn-popup-wrapper #ptReset")
          .addEventListener(evt, function () {
            //검색어 입력 이벤트
            initPopPartnerData();
          })
      );

      table_pop_partner_search.on("rowDblClick", setPopPartnerData); //Row 더블클릭 이벤트
      table_pop_partner_search.on("tableBuilt", function () {
        //초기 데이터 불러오기 이벤트
        getPopPartnerList();
      });
    }
  );
};

const popBizareaList = function (tgt_id, tgt_name, tabrow) {
  //tabrow 존재하면 (tabulator 필드명), 그외는 거래처코드 selector=>tgt_id, 거래처명 selector => 거래처명
  //팝업 템플릿 로드 후 모달 출력
  vnLoad(
    "",
    "/ksvc/inc/popup.inc.php",
    "#pop_bizarea_search",
    function (loadHtml) {
      let bizareaModal = kuls_modal(loadHtml);

      const fields = [
        {
          formatter: "rownum",
          title: "No",
          width: 50,
          headerSort: false,
          hozAlign: "center",
        },
        { field: "BIZ_AREA_CD", title: "사업장코드", width: 100 },
        { field: "BIZ_AREA_NM", title: "사업장명", width: 160 },
        { field: "HQ_FLG", title: "본사구분", width: 90 },
        { field: "WORK_STD_TIME", title: "기준시간", width: 90 },
        { field: "STD_CURRENCY_CD", title: "기준화폐", width: 90 },
      ];

      const table_pop_bizarea_search = new Tabulator("#pop_bizarea_list", {
        layout: "fitColumns",
        data: [], //기본 데이터
        height: "100%",
        columns: fields, //컬럼 설정
        columnDefaults: {
          //컬럼 공통 규칙
          vertAlign: "middle",
          hozAlign: "center",
          resizable: "header", //Resize 는 헤더에서만 가능
          headerHozAlign: "center", //헤더 정렬
          headerSortTristate: true, //정렬 => 정/역/초기화
        },
        headerSortElement: "<i class='bi'></i>", //정렬 아이콘
      });

      const getPopBizareaList = function () {
        //리스트 불러오기
        ajax_json({
          url: "/ksvc/inc/common.ajax.php",
          data: { mode: "getBizareaList" },
          success: function (data) {
            if (data.code) {
              table_pop_bizarea_search.setData(data.data);
            }
          },
          error: function (request, status, error) {
            //kuls_alert(error.message);
          },
        });
      };
      const setTableFilter = function () {
        //검색어 필터 적용
        let stxt = trim(
          document.querySelector("#awn-popup-wrapper input[name=stxt]").value
        );
        table_pop_bizarea_search.setFilter(
          function (data) {
            return (
              !stxt ||
              data["BP_CD"].search(RegExp(stxt, "is")) !== -1 ||
              data["BP_NM"].search(RegExp(stxt, "is")) !== -1 ||
              data["BP_FULL_NM"].search(RegExp(stxt, "is")) !== -1
            );
          },
          "=",
          true
        );
      };
      const setPopBizareaData = function (e, tgt) {
        //Row 더블클릭 실행
        let row = tgt._row;
        if (tabrow) {
          tabrow.updateData({
            [tgt_id]: row.data["BIZ_AREA_CD"],
            [tgt_name]: row.data["BIZ_AREA_NM"],
            _STATUS_: tabrow.getData()["_STATUS_"] || "U",
          });
        } else {
          if (document.querySelector(tgt_id))
            document.querySelector(tgt_id).value = row.data["BIZ_AREA_CD"];
          if (document.querySelector(tgt_name))
            document.querySelector(tgt_name).value = row.data["BIZ_AREA_NM"];
        }
        bizareaModal.delete();
      };
      const initPopBizareaData = function () {
        //Row 더블클릭 실행
        if (tabrow) {
          kuls_warning("Bizarea is neccessary field!");
        } else {
          if (document.querySelector(tgt_id))
            document.querySelector(tgt_id).value = "";
          if (document.querySelector(tgt_name))
            document.querySelector(tgt_name).value = "";
        }
        bizareaModal.delete();
      };

      //document.querySelector("#awn-popup-wrapper .btnPopSearch").addEventListener("click",function() { //조회버튼 클릭 이벤트
      //  getPopBizareaList();
      //});
      //document.querySelector("#awn-popup-wrapper .btnPopInit").addEventListener("click",function() { //조회버튼 클릭 이벤트
      //  initPopBizareaData();
      //});
      document
        .querySelector("#awn-popup-wrapper [name=stxt]")
        .addEventListener("keyup", function () {
          //검색어 입력 이벤트
          setTableFilter();
        });

      table_pop_bizarea_search.on("rowDblClick", setPopBizareaData); //Row 더블클릭 이벤트
      table_pop_bizarea_search.on("tableBuilt", function () {
        //초기 데이터 불러오기 이벤트
        getPopBizareaList();
      });
    }
  );
};

const popMemberList = function (tgt_id, tgt_name, tabrow) {
  //tabrow 존재하면 (tabulator 필드명), 그외는 거래처코드 selector=>tgt_id, 거래처명 selector => 거래처명
  //팝업 템플릿 로드 후 모달 출력
  vnLoad(
    "",
    "/ksvc/inc/popup.inc.php",
    "#pop_member_search",
    function (loadHtml) {
      let bizareaModal = kuls_modal(loadHtml);

      const fields = [
        {
          formatter: "rownum",
          title: "No",
          width: 50,
          headerSort: false,
          hozAlign: "center",
        },
        { field: "EMP_NO", title: "사 번", width: 100 },
        { field: "EMP_NM", title: "이 름", width: 160 },
        { field: "DEPT_NM", title: "부서명", width: 90 },
        { field: "BIZ_AREA_NM", title: "사업장", width: 90 },
      ];

      const table_pop_bizarea_search = new Tabulator("#pop_bizarea_list", {
        layout: "fitColumns",
        data: [], //기본 데이터
        height: "100%",
        columns: fields, //컬럼 설정
        columnDefaults: {
          //컬럼 공통 규칙
          vertAlign: "middle",
          hozAlign: "center",
          resizable: "header", //Resize 는 헤더에서만 가능
          headerHozAlign: "center", //헤더 정렬
          headerSortTristate: true, //정렬 => 정/역/초기화
        },
        headerSortElement: "<i class='bi'></i>", //정렬 아이콘
      });

      const getPopBizareaList = function () {
        //리스트 불러오기
        ajax_json({
          url: "/ksvc/inc/common.ajax.php",
          data: { mode: "getBizareaList" },
          success: function (data) {
            if (data.code) {
              table_pop_bizarea_search.setData(data.data);
            }
          },
          error: function (request, status, error) {
            //kuls_alert(error.message);
          },
        });
      };
      const setTableFilter = function () {
        //검색어 필터 적용
        let stxt = trim(
          document.querySelector("#awn-popup-wrapper input[name=stxt]").value
        );
        table_pop_bizarea_search.setFilter(
          function (data) {
            return (
              !stxt ||
              data["BP_CD"].search(RegExp(stxt, "is")) !== -1 ||
              data["BP_NM"].search(RegExp(stxt, "is")) !== -1 ||
              data["BP_FULL_NM"].search(RegExp(stxt, "is")) !== -1
            );
          },
          "=",
          true
        );
      };
      const setPopBizareaData = function (e, tgt) {
        //Row 더블클릭 실행
        let row = tgt._row;
        if (tabrow) {
          tabrow.updateData({
            [tgt_id]: row.data["BIZ_AREA_CD"],
            [tgt_name]: row.data["BIZ_AREA_NM"],
            _STATUS_: tabrow.getData()["_STATUS_"] || "U",
          });
        } else {
          if (document.querySelector(tgt_id))
            document.querySelector(tgt_id).value = row.data["BIZ_AREA_CD"];
          if (document.querySelector(tgt_name))
            document.querySelector(tgt_name).value = row.data["BIZ_AREA_NM"];
        }
        bizareaModal.delete();
      };
      const initPopBizareaData = function () {
        //Row 더블클릭 실행
        if (tabrow) {
          kuls_warning("Bizarea is neccessary field!");
        } else {
          if (document.querySelector(tgt_id))
            document.querySelector(tgt_id).value = "";
          if (document.querySelector(tgt_name))
            document.querySelector(tgt_name).value = "";
        }
        bizareaModal.delete();
      };

      //document.querySelector("#awn-popup-wrapper .btnPopSearch").addEventListener("click",function() { //조회버튼 클릭 이벤트
      //  getPopBizareaList();
      //});
      //document.querySelector("#awn-popup-wrapper .btnPopInit").addEventListener("click",function() { //조회버튼 클릭 이벤트
      //  initPopBizareaData();
      //});
      document
        .querySelector("#awn-popup-wrapper [name=stxt]")
        .addEventListener("keyup", function () {
          //검색어 입력 이벤트
          setTableFilter();
        });

      table_pop_bizarea_search.on("rowDblClick", setPopBizareaData); //Row 더블클릭 이벤트
      table_pop_bizarea_search.on("tableBuilt", function () {
        //초기 데이터 불러오기 이벤트
        getPopBizareaList();
      });
    }
  );
};

const popDeptListLive = function (tgt_id, tgt_name, tab) {
  //팝업 템플릿 로드 후 모달 출력
  vnLoad(
    "",
    "/ksvc/inc/popup.inc.php",
    "#pop_dept_search",
    function (loadHtml) {
      let bizareaModal = kuls_modal(loadHtml);
      document.querySelector(".awn-popup-confirm.awn-dept .s_fld").innerHTML =
        ""; //사업장 Select 태그 제거
      let row = tab._row;
      let tree_data = tab.getTable().getData();
      let row_data = row.getData();
      let BIZ_AREA_CD = row_data["BIZ_AREA_CD"];
      if (!BIZ_AREA_CD) {
        kuls_alert("사업장 코드를 선택하지 않았습니다.");
        return;
      }

      jQuery("#pop_dept_tree").fancytree({
        clickFolderMode: 3,
        source: tree_by_parent(tree_data, "DEPT_CD", "PAR_DEPT_CD", ""),
        dblclick: function (event, data) {
          let node = data.node;
          if (
            ("|" + node.data["DEPT_PATH_CD"] + "|").indexOf(
              "|" + row.data["DEPT_CD"] + "|"
            ) !== -1
          ) {
            kuls_alert("해당부서 또는 하위부서를 상위부서로 선택하였습니다.");
            return false;
          }
          row.updateData({
            [tgt_id]: node.data["DEPT_CD"],
            [tgt_name]: node.data["DEPT_NM"],
            _STATUS_: row.getData()["_STATUS_"] || "U",
          });
          bizareaModal.delete();
        },
      });
    }
  );
};

/* 위는 수정/추가가 반영되는 라이브 상태로 진행되며, 아래 코드는 DB 내용만 가져오는것. */
const popDeptList = function (tgt_id, tgt_name, tgt_intnl, BIZ_AREA_CD, tab) {
  //팝업 템플릿 로드 후 모달 출력
  vnLoad(
    "",
    "/ksvc/inc/popup.inc.php",
    "#pop_dept_search",
    function (loadHtml) {
      let bizareaModal = kuls_modal(loadHtml);
      let row = tab._row;
      const cfunc = function (data) {
        let node = data.node;
        row.updateData({
          [tgt_id]: node.data["DEPT_CD"],
          [tgt_name]: node.data["DEPT_NM"],
          [tgt_intnl]: node.data["INTNL_DEPT_CD"],
          _STATUS_: row.getData()["_STATUS_"] || "U",
        });
        bizareaModal.delete();
      };
      ajax_json({
        url: "/inc/common.ajax.php",
        type: "POST",
        data: {
          mode: "getBizareaList",
        },
        success: function (data) {
          if (data.code) {
            let selecttag = document.querySelector(
              ".s_fld select[name=BIZ_AREA_CD]"
            );
            selecttag.options.length = 0;
            data.data.forEach((row) => {
              let opt = document.createElement("option");
              opt.value = row["BIZ_AREA_CD"];
              opt.text = row["BIZ_AREA_NM"];
              selecttag.add(opt);
            });
            selecttag.value = BIZ_AREA_CD;
          }
        },
        error: function (request, status, error) {},
        complete: function (request, status) {
          getDeptList(tgt_id, tgt_name, BIZ_AREA_CD, cfunc);
        },
      });
      document
        .querySelector(".s_fld select[name=BIZ_AREA_CD]")
        .addEventListener("change", function () {
          getDeptList(tgt_id, tgt_name, this.value, cfunc);
        });
    }
  );
};

const getDeptList = function (tgt_id, tgt_name, BIZ_AREA_CD, cfunc) {
  document.querySelector(
    ".awn-popup-confirm.awn-dept .awn-popup-content"
  ).innerHTML = "<div id='pop_dept_tree' class='poptree'></div>";
  ajax_json({
    url: "/inc/common.ajax.php",
    type: "POST",
    data: {
      mode: "getDeptTree",
      BIZ_AREA_CD,
    },
    success: function (data) {
      if (data.code) {
        jQuery("#pop_dept_tree").fancytree({
          clickFolderMode: 3,
          source: tree_by_parent(data.data, "DEPT_CD", "PAR_DEPT_CD", ""),
          dblclick: function (event, data) {
            cfunc && cfunc(data);
          },
        });
      }
    },
    error: function (request, status, error) {},
    complete: function (request, status) {},
  });
};

const popEmployeeList = function (tgt_id, tgt_name, BIZ_AREA_CD, tabrow) {
  //팝업 템플릿 로드 후 모달 출력
  vnLoad(
    "",
    "/ksvc/inc/popup.inc.php",
    "#pop_employee_search",
    function (loadHtml) {
      let bizareaModal = kuls_modal(loadHtml);

      const cfunc = function (e, tgt) {
        let row = tgt._row;
        if (tabrow) {
          tabrow.updateData({
            [tgt_id]: row.data["EMP_NO"],
            [tgt_name]: row.data["EMP_NM"],
            _STATUS_: tabrow.getData()["_STATUS_"] || "U",
          });
        } else {
          if (document.querySelector(tgt_id))
            document.querySelector(tgt_id).value = row.data["EMP_NO"];
          if (document.querySelector(tgt_name))
            document.querySelector(tgt_name).value = row.data["EMP_NM"];
        }
        bizareaModal.delete();
      };
      ajax_json({
        url: "/inc/common.ajax.php",
        type: "POST",
        data: {
          mode: "getBizareaList",
        },
        success: function (data) {
          if (data.code) {
            let selecttag = document.querySelector(
              ".s_fld select[name=BIZ_AREA_CD]"
            );
            selecttag.options.length = 0;
            data.data.forEach((row) => {
              let opt = document.createElement("option");
              opt.value = row["BIZ_AREA_CD"];
              opt.text = row["BIZ_AREA_NM"];
              selecttag.add(opt);
            });
            selecttag.value = BIZ_AREA_CD;
          }
        },
        error: function (request, status, error) {},
        complete: function (request, status) {
          getEmployeeList(tgt_id, tgt_name, BIZ_AREA_CD, cfunc);
        },
      });
      document
        .querySelector(".s_fld select[name=BIZ_AREA_CD]")
        .addEventListener("change", function () {
          getEmployeeList(tgt_id, tgt_name, this.value, cfunc);
        });
    }
  );
};

const getEmployeeList = function (tgt_id, tgt_name, BIZ_AREA_CD, cfunc) {
  const fields = [
    {
      formatter: "rownum",
      title: "No",
      width: 50,
      headerSort: false,
      hozAlign: "center",
    },
    { field: "EMP_NO", title: "사 번", width: 100 },
    { field: "EMP_NM", title: "이 름", width: 160 },
    { field: "DEPT_NM", title: "부서명", width: 120 },
    { field: "BIZ_AREA_NM", title: "사업장", width: 150 },
  ];

  const table_pop_employee_search = new Tabulator("#pop_employee_list", {
    layout: "fitColumns",
    data: [], //기본 데이터
    height: "100%",
    columns: fields, //컬럼 설정
    columnDefaults: {
      //컬럼 공통 규칙
      vertAlign: "middle",
      hozAlign: "center",
      resizable: "header", //Resize 는 헤더에서만 가능
      headerHozAlign: "center", //헤더 정렬
      headerSortTristate: true, //정렬 => 정/역/초기화
    },
    headerSortElement: "<i class='bi'></i>", //정렬 아이콘
  });

  const getPopEmployeeList = function () {
    //리스트 불러오기
    ajax_json({
      url: "/ksvc/inc/common.ajax.php",
      data: { mode: "getEmployeeList", BIZ_AREA_CD },
      success: function (data) {
        if (data.code) {
          table_pop_employee_search.setData(data.data);
        }
      },
      error: function (request, status, error) {
        //kuls_alert(error.message);
      },
    });
  };

  table_pop_employee_search.on("rowDblClick", (e, tgt) => {
    cfunc && cfunc(e, tgt);
  }); //Row 더블클릭 이벤트
  table_pop_employee_search.on("tableBuilt", function () {
    //초기 데이터 불러오기 이벤트
    getPopEmployeeList();
  });

  ["change", "keyup"].forEach((evt) =>
    document
      .querySelector(".s_fld input[name=stxt]")
      .addEventListener(evt, function () {
        table_pop_employee_search.setFilter(
          function (data) {
            //필터링
            return (
              true &&
              data.EMP_NM.indexOf(
                document.querySelector(".s_fld input[name=stxt]").value
              ) !== -1
            );
          },
          "=",
          true
        );
      })
  );
};

const popBasecodeList = function (tgt_id, tgt_name, Bran_Uid, tabrow, rtgt) {
  //팝업 템플릿 로드 후 모달 출력
  vnLoad(
    "",
    "/ksvc/inc/popup.inc.php",
    "#pop_basecode_search",
    function (loadHtml) {
      let basecodeModal = kuls_modal(loadHtml);

      if (rtgt) {
        //Routing 전용
        let basecodes = [
          //{Bran_Uid: 'SHAPE_TYPE', Code_Exp: '형상관리'},
          { Bran_Uid: "ITEM_SPEC", Code_Exp: "스펙항목관리" },
          { Bran_Uid: "OP_PART", Code_Exp: "가공부위관리" },
          { Bran_Uid: "INSP_ITEM", Code_Exp: "검사항목관리" },
        ];

        let selecttag = document.querySelector(".s_fld select[name=BASECODE]");
        selecttag.options.length = 0;
        basecodes.forEach((row) => {
          let opt = document.createElement("option");
          opt.value = row["Bran_Uid"];
          opt.text = row["Code_Exp"];
          selecttag.add(opt);
        });
        Bran_Uid = Bran_Uid || basecodes[0].Bran_Uid;
        selecttag.value = Bran_Uid;

        document
          .querySelector(".s_fld select[name=BASECODE]")
          .addEventListener("change", function () {
            getPopBasecodeList(this.value);
            switch (this.value) {
              case "SHAPE_TYPE":
                tabrow = Tb_funcs_Spec.arefunc;
                break;
              case "ITEM_SPEC":
                tabrow = Tb_funcs_Spec.brefunc;
                break;
              case "OP_PART":
                tabrow = Tb_funcs_Cond.refunc;
                break;
              case "INSP_ITEM":
                tabrow = Tb_funcs_Insp.refunc;
                break;
            }
          });
      }
      const fields = [
        {
          formatter: "rownum",
          title: "No",
          width: "10%",
          minWidth: 50,
          headerSort: false,
          hozAlign: "center",
        },
        {
          field: "Code_Uid",
          title: "코드",
          width: "30%",
          minWidth: 100,
          editor: "input",
          editable: (cell) => {
            let val = cell.getData();
            return val._STATUS_ === "I";
          },
        },
        {
          field: "Code_Val",
          title: "명칭",
          width: "40%",
          minWidth: 160,
          editor: "input",
        },
        {
          field: "Code_Active",
          title: "사용",
          width: "20%",
          minWidth: 60,
          cssClass: "user-editable",
          formatter: tb_common_funtions.formatterToggleboxGreenIcon,
          formatterParams: { checkval: "Y" },
        },
      ];

      const table_pop_basecode_search = new Tabulator("#pop_basecode_list", {
        layout: "fitColumns",
        data: [], //기본 데이터
        height: "100%",
        columns: fields, //컬럼 설정
        columnDefaults: {
          //컬럼 공통 규칙
          vertAlign: "middle",
          hozAlign: "center",
          resizable: "header", //Resize 는 헤더에서만 가능
          headerHozAlign: "center", //헤더 정렬
          headerSortTristate: true, //정렬 => 정/역/초기화
        },
        movableRows: true,
        headerSortElement: "<i class='bi'></i>", //정렬 아이콘
      });

      const getPopBasecodeList = function (Bran_Uid) {
        //리스트 불러오기
        ajax_json({
          url: "/ksvc/inc/common.ajax.php",
          data: { mode: "getBasecodeList", Bran_Uid },
          success: function (data) {
            if (data.code) {
              table_pop_basecode_search.setData(data.data);
            }
          },
          error: function (request, status, error) {
            //kuls_alert(error.message);
          },
          complete: function () {
            setFilter();
          },
        });
      };

      const setFilter = () => {
        table_pop_basecode_search.setFilter(
          function (data) {
            //필터링
            return (
              true &&
              (!document.getElementById("P_USE_FLG") ||
                !document.getElementById("P_USE_FLG").checked ||
                data.Code_Active === "Y")
            );
          },
          "=",
          true
        );
      };

      //Row 추가
      const addRow = () => {
        table_pop_basecode_search.addRow({
          _STATUS_: "I",
          Bran_Uid,
          Group_Uid: Bran_Uid,
          Code_Active: "Y",
        });
      };

      //Cell 클릭 콜백
      const cellClick = (e, tgt) => {
        switch (tgt.getField()) {
          case "Code_Active":
            tgt.setValue(tgt.getValue() == "Y" ? "N" : "Y");
            break;
        }
      };

      //Cell 변경 콜백
      const cellEdited = (cell) => {
        let _this = this;
        cell.getData()._STATUS_ = cell.getData()._STATUS_ || "U";
      };

      const putItem = () => {
        let pdata = table_pop_basecode_search.getData();
        let dupdata = pdata.map((data) => data["Code_Uid"]);
        if (
          dupdata.filter((data, idx) => dupdata.indexOf(data) !== idx).length >
          0
        ) {
          kuls_alert("코드가 중복됩니다.");
          return false;
        }
        let postdata = {
          mode: "putBasecode",
          reqdata: JSON.stringify(
            table_pop_basecode_search.getData().filter((row) => row._STATUS_)
          ),
        };
        ajax_json({
          url: "/ksvc/inc/common.ajax.php",
          data: postdata,
          success: function (data) {
            if (data.code) {
              kuls_success("적용 되었습니다.");
              if (typeof tabrow == "function") {
                tabrow(pdata, null);
                basecodeModal.delete();
              }
            } else {
              kuls_alert(data.mesg);
            }
          },
          error: function (request, status, error) {
            kuls_alert(error.message);
          },
        });
        return true;
      };

      table_pop_basecode_search.on("rowDblClick", (e, tgt) => {
        return false;

        let row = tgt._row;
        document.ttt = tgt;
        if (typeof tabrow == "function") {
          tabrow(tgt.getTable().getData(), tgt.getData());
        } else if (tabrow) {
          tabrow.updateData({
            [tgt_id]: row.data["Code_Uid"],
            [tgt_name]: row.data["Code_Val"],
            _STATUS_: tabrow.getData()["_STATUS_"] || "U",
          });
        } else {
          if (document.querySelector(tgt_id))
            document.querySelector(tgt_id).value = row.data["Code_Uid"];
          if (document.querySelector(tgt_name))
            document.querySelector(tgt_name).value = row.data["Code_Val"];
        }
        basecodeModal.delete();
      }); //Row 더블클릭 이벤트

      table_pop_basecode_search.on("cellClick", (e, tgt) => {
        //Tabulator cell Click
        cellEdited && cellClick(e, tgt);
      });
      table_pop_basecode_search.on("cellEdited", (cell) => {
        //Tabulator cell Edited
        cellEdited && cellEdited(cell);
      });
      table_pop_basecode_search.on("rowMoved", (row, a, b) => {
        //Tabulator Row Moved
        let Code_Uid = row.getData()["Code_Uid"];
        let n_idx = row
          .getTable()
          .getData()
          .findIndex((v) => v.Code_Uid === Code_Uid);
        do {
          //현재 이하 순서 변경
          row._row.updateData({
            Code_Idx: ++n_idx,
            _STATUS_: row.getData()["_STATUS_"] || "U",
          });
        } while ((row = row.getNextRow()));
      });
      ["click", "keypress"].forEach((evt) =>
        document.querySelector("#btnAddBcode").addEventListener(evt, () => {
          addRow();
        })
      );
      ["click", "keypress"].forEach((evt) =>
        document.querySelector("#btnPutBcode").addEventListener(evt, () => {
          putItem();
        })
      );
      ["change", "keydown", "keyup"].forEach((evt) =>
        document.querySelectorAll("#P_USE_FLG").forEach((tgt) =>
          tgt.addEventListener(evt, () => {
            setFilter();
          })
        )
      );
      table_pop_basecode_search.on("tableBuilt", function () {
        //초기 데이터 불러오기 이벤트
        getPopBasecodeList(Bran_Uid);
      });
    }
  );
};

const popBasegroupList = function (
  tgt_id,
  tgt_name,
  Bran_Uid,
  Group_Uid,
  refunc,
  rtgt
) {
  //팝업 템플릿 로드 후 모달 출력
  vnLoad(
    "",
    "/ksvc/inc/popup.inc.php",
    "#pop_basecode_search",
    function (loadHtml) {
      let basegroupModal = kuls_modal(loadHtml);

      if (rtgt) {
        //Routing 전용
        let basegroups = Object.keys(varsSHAPE_GRP).map((key) => {
          return { Group_Uid: key, Code_Exp: varsSHAPE_GRP[key].Code_Exp };
        });
        let selecttag = document.querySelector(".s_fld select[name=BASECODE]");
        selecttag.options.length = 0;
        basegroups.forEach((row) => {
          let opt = document.createElement("option");
          opt.value = row["Group_Uid"];
          opt.text = row["Code_Exp"];
          selecttag.add(opt);
        });
        Group_Uid = Group_Uid || basegroups[0].Group_Uid;
        selecttag.value = Group_Uid;

        document
          .querySelector(".s_fld select[name=BASECODE]")
          .addEventListener("change", function () {
            getPopBasegroupList(this.value);
          });
      }
      const fields = [
        {
          formatter: "rownum",
          title: "No",
          width: "10%",
          minWidth: 50,
          headerSort: false,
          hozAlign: "center",
        },
        {
          field: "Code_Uid",
          title: "코드",
          width: "30%",
          minWidth: 100,
          editor: "input",
          editable: (cell) => {
            let val = cell.getData();
            return val._STATUS_ === "I";
          },
        },
        {
          field: "Code_Val",
          title: "명칭",
          width: "40%",
          minWidth: 160,
          editor: "input",
        },
        {
          field: "Code_Active",
          title: "사용",
          width: "20%",
          minWidth: 60,
          cssClass: "user-editable",
          formatter: tb_common_funtions.formatterToggleboxGreenIcon,
          formatterParams: { checkval: "Y" },
        },
      ];

      const table_pop_basegroup_search = new Tabulator("#pop_basecode_list", {
        layout: "fitColumns",
        data: [], //기본 데이터
        height: "100%",
        columns: fields, //컬럼 설정
        columnDefaults: {
          //컬럼 공통 규칙
          vertAlign: "middle",
          hozAlign: "center",
          resizable: "header", //Resize 는 헤더에서만 가능
          headerHozAlign: "center", //헤더 정렬
          headerSortTristate: true, //정렬 => 정/역/초기화
        },
        movableRows: true,
        headerSortElement: "<i class='bi'></i>", //정렬 아이콘
      });

      const getPopBasegroupList = function (G_Uid) {
        //리스트 불러오기
        Group_Uid = G_Uid || Group_Uid;
        ajax_json({
          url: "/ksvc/inc/common.ajax.php",
          data: { mode: "getBasecodeList", Bran_Uid, Group_Uid: Group_Uid },
          success: function (data) {
            if (data.code) {
              table_pop_basegroup_search.setData(data.data);
            }
          },
          error: function (request, status, error) {
            //kuls_alert(error.message);
          },
          complete: function () {
            setFilter();
          },
        });
      };

      const setFilter = () => {
        table_pop_basegroup_search.setFilter(
          function (data) {
            //필터링
            return (
              true &&
              (!document.getElementById("P_USE_FLG") ||
                !document.getElementById("P_USE_FLG").checked ||
                data.Code_Active === "Y")
            );
          },
          "=",
          true
        );
      };

      //Row 추가
      const addRow = () => {
        table_pop_basegroup_search.addRow({
          _STATUS_: "I",
          Bran_Uid,
          Group_Uid: Group_Uid,
          Code_Active: "Y",
        });
      };

      //Cell 클릭 콜백
      const cellClick = (e, tgt) => {
        switch (tgt.getField()) {
          case "Code_Active":
            tgt.setValue(tgt.getValue() == "Y" ? "N" : "Y");
            break;
        }
      };

      //Cell 변경 콜백
      const cellEdited = (cell) => {
        let _this = this;
        cell.getData()._STATUS_ = cell.getData()._STATUS_ || "U";
      };

      const putItem = () => {
        let pdata = table_pop_basegroup_search.getData();
        let dupdata = pdata.map((data) => data["Code_Uid"]);
        if (
          dupdata.filter((data, idx) => dupdata.indexOf(data) !== idx).length >
          0
        ) {
          kuls_alert("코드가 중복됩니다.");
          return false;
        }
        let postdata = {
          mode: "putBasecode",
          reqdata: JSON.stringify(
            table_pop_basegroup_search.getData().filter((row) => row._STATUS_)
          ),
        };
        ajax_json({
          url: "/ksvc/inc/common.ajax.php",
          data: postdata,
          success: function (data) {
            if (data.code) {
              kuls_success("적용 되었습니다.");
              if (typeof tabrow == "function") {
                tabrow(pdata, null);
                basegroupModal.delete();
              }
            } else {
              kuls_alert(data.mesg);
            }
          },
          error: function (request, status, error) {
            kuls_alert(error.message);
          },
        });
        return true;
      };

      table_pop_basegroup_search.on("rowDblClick", (e, tgt) => {
        return false;

        let row = tgt._row;
        document.ttt = tgt;
        if (typeof tabrow == "function") {
          tabrow(tgt.getTable().getData(), tgt.getData());
        } else if (tabrow) {
          tabrow.updateData({
            [tgt_id]: row.data["Code_Uid"],
            [tgt_name]: row.data["Code_Val"],
            _STATUS_: tabrow.getData()["_STATUS_"] || "U",
          });
        } else {
          if (document.querySelector(tgt_id))
            document.querySelector(tgt_id).value = row.data["Code_Uid"];
          if (document.querySelector(tgt_name))
            document.querySelector(tgt_name).value = row.data["Code_Val"];
        }
        basegroupModal.delete();
      }); //Row 더블클릭 이벤트

      table_pop_basegroup_search.on("cellClick", (e, tgt) => {
        //Tabulator cell Click
        cellEdited && cellClick(e, tgt);
      });
      table_pop_basegroup_search.on("cellEdited", (cell) => {
        //Tabulator cell Edited
        cellEdited && cellEdited(cell);
      });
      table_pop_basegroup_search.on("rowMoved", (row, a, b) => {
        //Tabulator Row Moved
        let Code_Uid = row.getData()["Code_Uid"];
        let n_idx = row
          .getTable()
          .getData()
          .findIndex((v) => v.Code_Uid === Code_Uid);
        do {
          //현재 이하 순서 변경
          row._row.updateData({
            Code_Idx: ++n_idx,
            _STATUS_: row.getData()["_STATUS_"] || "U",
          });
        } while ((row = row.getNextRow()));
      });
      ["click", "keypress"].forEach((evt) =>
        document.querySelector("#btnAddBcode").addEventListener(evt, () => {
          addRow();
        })
      );
      ["click", "keypress"].forEach((evt) =>
        document.querySelector("#btnPutBcode").addEventListener(evt, () => {
          putItem();
        })
      );
      ["change", "keydown", "keyup"].forEach((evt) =>
        document.querySelectorAll("#P_USE_FLG").forEach((tgt) =>
          tgt.addEventListener(evt, () => {
            setFilter();
          })
        )
      );
      table_pop_basegroup_search.on("tableBuilt", function () {
        //초기 데이터 불러오기 이벤트
        getPopBasegroupList();
      });
    }
  );
};

class drawManager {
  constructor() {
    let _this = this;
    _this.tblList = "";
    _this.prow = "";
    _this.ajax_url = "/order/registration/registration.ajax.php";
    _this.upload_ajax_url = "/order/registration/attfile.ajax.php";
    _this.download_url = "/include/getFile.php";
    _this.drawModal = null;
  }

  init(row) {
    let _this = this;

    _this.prow = row;
    _this.parData = Object.assign({}, row.getData());
    if (!_this.parData.SO_SEQ) {
      kuls_alert(
        "저장되지 않은 수주상세입니다.<br/>수주상세 저장 후 도면등록이 가능합니다."
      );
      return;
    }

    vnLoad("", "/order/registration/draw.pop.inc.php", "", function (loadHtml) {
      _this.drawModal = kuls_modal(loadHtml);
      _this.initload();
    });
  }

  //리스트 로드
  getMainList() {
    let _this = this;

    let introw = ["ORD_QTY", "SO_QTY"];
    let fltrow = ["OUT_DIA", "IN_DIA", "THICK", "WIDTH", "LENGTH"];

    Object.keys(_this.parData).forEach((key) => {
      if (introw.indexOf(key) !== -1) {
        _this.parData[key] = parseInt(_this.parData[key]);
      }
      if (fltrow.indexOf(key) !== -1) {
        _this.parData[key] = currency(_this.parData[key], { precision: 3 });
      }
      if (key === "SHAPE_TYPE")
        _this.parData[key] = varsSHAPE_TYPE[_this.parData[key]];
      if (key === "ITEM_CD")
        _this.parData[key] = varsSHAPE_GRP[_this.parData[key]]?.Code_Exp;

      if (document.getElementById("pop_" + key))
        document.getElementById("pop_" + key).innerHTML = _this.parData[key];
    });
    let talert = window.setTimeout(function () {
      _this.tblList.alert("Loading ...");
    }, 1000); //1초 이상 지연되면 로딩 출력

    ajax_json({
      url: _this.upload_ajax_url,
      data: {
        mode: "getDrawList",
        nid: _this.parData["SO_NO"] || "",
        sid: _this.parData["SO_SEQ"] || "",
      },
      success: function (data) {
        if (data.code) {
          if (data.data.length) {
            _this.tblList.setData(
              data.data.map((sd) => {
                return { ...sd, _OLD_STATUS_: sd._STATUS_ };
              })
            );
            _this.prow.update({
              ASS_DRAW: data.data.sort((a, b) =>
                a.file_id < b.file_id ? 1 : -1
              )[0].file_exp,
            });
          }
        } else {
          kuls_alert(data.mesg);
        }
      },
      error: function (request, status, error) {
        kuls_alert(error.message);
      },
      complete: function () {
        window.clearTimeout(talert);
        _this.tblList.clearAlert();
        //멀티파일 업로더
        if (!_this.uploader) {
          _this.uploader = FilePond.create(
            document.getElementById("drawfilepond"),
            {
              ...filepond_ko_KR,
              name: "upfile",
              allowMultiple: true,
              maxParallelUploads: 3,
              allowProcess: false,
              instantUpload: true,
              server: {
                url: _this.upload_ajax_url + "?mode=putTempFile",
                process: {
                  onload: function (data) {
                    data = JSON.parse(data);
                    let fdata = data.data;
                    let file_name = fdata["file_name"];
                    let tmp_name = fdata["tmp_name"];
                    let file_size = fdata["file_size"];
                    let file_type = fdata["file_type"];
                    _this.tblList.addRow({
                      _STATUS_: "I",
                      nid: _this.parData["SO_NO"],
                      sid: _this.parData["SO_SEQ"],
                      file_name,
                      tmp_name,
                      file_size,
                      file_type,
                      gubun: "temp",
                    });
                  },
                },
              },
              allowFileSizeValidation: true,
              maxFileSize: 100000000,
              credits: {},
            }
          );

          // document.addEventListener('FilePond:processfile', (e)=>{
          //   let data = e.detail.file;
          //   let name = data.filename;
          //   let ext = data.fileExtension;
          //   let size = data.fileSize;
          //   let type = data.fileType;
          //   let file_url = _this.download_url+"?gubun=temp&tmp_name="+1+"&name="+name+"&size="+size;
          //
          //   _this.tblList.addRow({_STATUS_:'I', file_name:name, url:file_url});
          // });

          document
            .getElementById("drawfilepond")
            .addEventListener("FilePond:addfilestart", (e) => {
              _this.tblList.alert("미리보기 작성중...");
              document.querySelector(
                "#pop_draw_search .btn_prim"
              ).disabled = true;
            });
          document
            .getElementById("drawfilepond")
            .addEventListener("FilePond:processfiles", (e) => {
              _this.tblList.clearAlert();
              document.querySelector(
                "#pop_draw_search .btn_prim"
              ).disabled = false;
            });
        }
      },
    });
    return true;
  }

  setFilter() {
    let _this = this;
  }

  //Row 추가
  addRow() {
    let _this = this;
  }

  //Cell 클릭 콜백
  cellClick(e, tgt) {
    let _this = this;
    let rowData = tgt.getData();
    switch (tgt.getField()) {
      case "file_url":
        let file_url =
          _this.download_url +
          "?gubun=" +
          rowData["gubun"] +
          "&nid=" +
          rowData["nid"] +
          "&sid=" +
          rowData["sid"] +
          "&file_id=" +
          rowData["file_id"] +
          "&tmp_name=" +
          rowData["tmp_name"] +
          "&name=" +
          rowData["file_name"] +
          "&size=" +
          rowData["file_size"];
        pop_filedown(file_url, rowData["file_name"].split(".").pop());
        break;

      case "DEL_FLG":
        tgt.setValue(tgt.getValue() == "Y" ? "N" : "Y");
        break;
    }
  }

  //Cell 변경 콜백
  cellEdited(cell) {
    let _this = this;

    cell.getData()._STATUS_ = cell.getData()._STATUS_ || "U";
  }

  //등록
  uploadDraw() {
    let _this = this;

    _this.uploader.browse();
  }

  //등록
  putDraw() {
    let _this = this;
    /* 삭제를 토글로 처리시, 복구를 위해 DEL_FLG가 추가될 경우에 사용.
    let rowData = _this.tblList.getData().map( row => {
      if( row['DEL_FLG'] === "Y" ){
        row['_STATUS_'] = "D";
      }
      return row;
    }).filter(row => row['_STATUS_'] && (row['_STATUS_'] !== "D" || row['file_id']) );
    */
    let rowData = _this.tblList.getData().filter((row) => row["_STATUS_"]);

    ajax_json({
      url: _this.upload_ajax_url,
      data: { mode: "putDraw", reqdata: JSON.stringify(rowData) },
      success: function (data) {
        if (data.code) {
          kuls_success("저장되었습니다.");
          //Tb_funcs_Detail.drawModal.delete();
          _this.getMainList();
        } else {
          kuls_alert(data.mesg);
        }
      },
      error: function (request, status, error) {
        kuls_alert(error.message);
      },
      complete: function () {},
    });
  }

  rowDelete() {
    let _this = this;
    _this.tblList.getSelectedRows().forEach((row) => {
      row.getData()["_STATUS_"] = "D";
      row.getElement().classList.add("del-row");
    });
  }

  revokeData(row) {
    let _this = this;
    row.update({ _STATUS_: row.getData()["_OLD_STATUS_"] });
    row.getElement().classList.remove("del-row");
  }

  //시작 실행
  initload() {
    let _this = this;

    const fields = [
      //{ formatter: "rownum", title: "No", width: "8%",  minWidth:80, },
      {
        formatter: "rowSelection",
        title: "No",
        width: "10%",
        headerSort: false,
      },
      {
        field: "file_exp",
        title: "도면번호",
        width: "40%",
        minWidth: 200,
        editor: "input",
      },
      { field: "file_name", title: "도면파일", width: "40%", minWidth: 200 },
      {
        field: "file_url",
        title: "<i class='fa-solid fa-compass-drafting'></i>",
        width: "10%",
        minWidth: 80,
        formatter: () => '<i class="fa-solid fa-download"></i>',
      },
      //{ field: "DEL_FLG",    title: "삭제", width: "8%", minWidth:80, cssClass:'user-editable', formatter: tb_common_funtions.formatterToggleboxRedIcon, formatterParams: {checkval:'Y'}},
    ];

    _this.tblList = new Tabulator("#pop_draw", {
      layout: "fitColumns",
      height: "100%",
      data: [], //기본 데이터
      columns: fields, //컬럼 설정
      columnDefaults: {
        //컬럼 공통 규칙
        vertAlign: "middle",
        hozAlign: "center",
        resizable: "header", //Resize 는 헤더에서만 가능
        headerHozAlign: "center", //헤더 정렬
        headerSortTristate: true, //데이터 정렬 => 정/역/초기화
      },
      headerSortElement: "<i class='bi'></i>", //정렬 아이콘
    });

    _this.tblList.on("tableBuilt", () => {
      //Tabulator 초기 데이터 불러오기 이벤트
      _this.getMainList();
    });

    _this.tblList.on("cellClick", (e, tgt) => {
      //Tabulator cell Click
      _this.cellClick && _this.cellClick(e, tgt);
    });
    _this.tblList.on("cellEdited", (cell) => {
      //Tabulator cell Edited
      _this.cellEdited && _this.cellEdited(cell);
    });
    _this.tblList.on("rowDeselected", (row) => {
      //Tabulator cell Deslected
      _this.revokeData && _this.revokeData(row);
    });

    ["click", "keypress"].forEach((evt) =>
      document
        .querySelector("#pop_draw_search #btnAddDraw")
        .addEventListener(evt, () => {
          _this.uploadDraw();
        })
    );
    ["click", "keypress"].forEach((evt) =>
      document
        .querySelector("#pop_draw_search #btnDelDraw")
        .addEventListener(evt, () => {
          _this.rowDelete();
        })
    );
    ["click", "keypress"].forEach((evt) =>
      document
        .querySelector("#pop_draw_search .btn_prim")
        .addEventListener(evt, () => {
          _this.putDraw();
        })
    );
    ["click", "keypress"].forEach((evt) =>
      document
        .querySelector("#pop_draw_search .btn_close")
        .addEventListener(evt, () => {
          _this.drawModal.delete();
        })
    );
  }
}

class planrouteManager {
  constructor() {
    let _this = this;
    _this.tblList = "";
    _this.ajax_url = "/order/planing/planing_ready.ajax.php";
  }

  init(row) {
    let _this = this;

    vnLoad(
      "",
      "/order/planing/planing_ready.pop.inc.php",
      "",
      function (loadHtml) {
        _this.routeModal = kuls_modal(loadHtml);

        _this.initload(row);
      }
    );
  }

  //리스트 로드
  getMainList(row) {
    let _this = this;

    let introw = ["ORD_QTY", "SO_QTY"];
    let fltrow = ["OUT_DIA", "IN_DIA", "THICK", "WIDTH", "LENGTH"];
    let rowData = Object.assign({}, row);
    Object.keys(rowData).forEach((key) => {
      switch (key) {
        case "SHAPE_TYPE":
          rowData[key] = varsSHAPE_TYPE[rowData[key]];
          break;
        case "ITEM_CD":
          rowData[key] = varsSHAPE_GRP[rowData[key]]?.Code_Exp;
          break;
        case "ORD_QTY":
        case "SO_QTY":
          rowData[key] = parseInt(rowData[key]);
          break;
        case "OUT_DIA":
        case "IN_DIA":
        case "THICK":
        case "WIDTH":
        case "LENGTH":
          rowData[key] = currency(rowData[key], { precision: 1 });
          break;
      }

      if (document.getElementById("pop_" + key))
        document.getElementById("pop_" + key).innerHTML = rowData[key];
    });

    let talert = window.setTimeout(function () {
      _this.tblList.alert("Loading ...");
    }, 1000); //1초 이상 지연되면 로딩 출력
    ajax_json({
      url: _this.ajax_url,
      data: { mode: "getRouteList", MNG_NO: rowData["MNG_NO"] },
      success: function (data) {
        if (data.code) {
          _this.tblList.setData(
            data.data.map((r) => {
              r["ORD_QTY"] = parseInt(r["ORD_QTY"]);
              return r;
            })
          );
        } else {
          kuls_alert(data.mesg);
        }
      },
      error: function (request, status, error) {
        kuls_alert(error.message);
      },
      complete: function () {
        window.clearTimeout(talert);
        _this.tblList.clearAlert();
        //Tb_funcs.setFilter();
      },
    });
    return true;
  }

  setFilter() {
    let _this = this;
  }

  //Row 추가
  addRow() {
    let _this = this;
  }

  //Cell 클릭 콜백
  cellClick(e, tgt) {
    let _this = this;
    let row = tgt.getRow();
    let rowData = row.getData();
    //if( rowData['ORD_STATUS'] === "Y" ) return; //작업지시가 내려진 상태에서는 클릭 불가
    if (varsOPSTATUS["WORK"].includes(rowData["PLN_STATUS"])) return; //작업지시가 내려진 상태에서는 클릭 불가

    switch (tgt.getField()) {
      case "btn_branch": //분할
        if (rowData["REL"] === "S") {
          if (rowData["_STATUS_"] === "D") {
            //STATUS 토글
            row
              .update({ _STATUS_: tgt.getData()["_OLD_STATUS_"] })
              .then(() => _this.callbackRowPartitial(row));
          } else {
            row.update({ _OLD_STATUS_: tgt.getData()["_STATUS_"] });
            row
              .update({ _STATUS_: "D" })
              .then(() => _this.callbackRowPartitial(row));
          }
        } else {
          let childRow = [];
          let childData = {
            ...rowData,
            REL: "S",
            _children: null,
            ORD_QTY: 0,
            CT: rowData["CT"],
            PLN_TERM_TM: "",
            WO_FACLT_NO: "",
          };
          if (rowData["_children"]) {
            childRow = rowData["_children"];
            childData["_STATUS_"] = "I"; //추가 분할 값
          }
          childRow.push(childData);
          row.update({ _children: childRow });
          row.treeExpand();
        }

        _this.callbackPatitial(_this.tblList, row);
        break;
    }
  }

  //Cell 변경 콜백
  cellEditing(cell) {
    let _this = this;
    //let per_period = 6; //10분단위
    let per_period = 1; //1시간 단위

    switch (cell.getField()) {
      case "PLN_ST_TM":
        if (!jQuery(cell.getElement()).find(".dtime_picker").length) {
          jQuery(cell.getElement())
            .off()
            .on("focus", "input", function (e) {
              jQuery(e.target)
                .datetimepicker({
                  allowTimes: [...Array(24 * per_period).keys()].map(
                    (idx) =>
                      Math.floor(idx / per_period)
                        .toString()
                        .padStart(2, "0") +
                      ":" +
                      (idx % per_period).toString().padEnd(2, "0")
                  ),
                  format: "Y-m-d H:i",
                  defaultTime:
                    luxon.DateTime.now().toFormat("HH:") +
                    Math.floor(luxon.DateTime.now().toFormat("mm") / 10)
                      .toString()
                      .padEnd(2, "0"),
                })
                .addClass("dtime_picker");
              jQuery(cell.getElement())
                // .on('change',function(){
                //   _this.setTimeCalc(cell);
                // })
                .before()
                .on("click focus", function () {
                  jQuery(cell.getElement())
                    .find("input")
                    .datetimepicker("show");
                });
            });
        }
        break;
    }
  }

  //Cell 변경 콜백
  cellEdited(cell) {
    let _this = this;

    switch (cell.getField()) {
      case "PLN_ST_TM":
        _this.setTimeCalc(cell);
        break;

      case "ORD_QTY":
        _this.setTimeCalc(cell);
        break;
    }

    _this.callbackPatitial(_this.tblList);
    cell.getData()._STATUS_ = cell.getData()._STATUS_ || "U";
  }

  //등록
  putPlanRoute() {
    let _this = this;

    let tblData = _this.tblList
      .getData()
      .filter((row) => row["WO_MAKE_FLG"] === "Y");
    let scs = tblData.reduce((chk, row) => {
      if (chk && row["_children"] && row["_children"].length) {
        let subSum = row["_children"].reduce(
          (rev, r) => rev + (r["_STATUS_"] === "D" ? 0 : r["ORD_QTY"]),
          0
        );
        if (row["ORD_QTY"] !== subSum) {
          chk = false;
        }
      }
      return chk;
    }, true);

    if (!scs) {
      kuls_alert("작업분할된 수량이 일치하지 않습니다.");
      return false;
    }

    let postdata = {
      mode: "putPlanRoute",
      reqdata: JSON.stringify(tblData),
    };
    ajax_json({
      url: _this.ajax_url,
      data: postdata,
      success: function (data) {
        if (data.code) {
          kuls_success("적용 되었습니다.");
          //닫기처리
        } else {
          kuls_alert(data.mesg);
        }
      },
      error: function (request, status, error) {
        kuls_alert(error.message);
      },
      complete: function () {},
    });
    return true;
  }

  setTimeCalc(cell) {
    //종료시간 계산
    let rowData = cell.getData();
    let sutime = Number(rowData["ST"]) || 0; //셋업시간
    let dgtime = Number(rowData["CT"]) || 0; //단위가공시간
    let pnum = Number(rowData["ORD_QTY"]) || 0; //수량
    let pcnt = Number(rowData["OP_COUNT"]) || 1; //가공횟수
    let termtm = dgtime * pnum * pcnt + sutime;
    let fdate = luxon.DateTime.fromFormat(
      rowData["PLN_ST_TM"],
      "y-MM-dd HH:mm"
    ).plus({ minutes: termtm });
    if (fdate.c)
      cell.getRow().update({
        PLN_ED_TM: fdate.toFormat("y-MM-dd HH:mm"),
        PLN_TERM_TM: termtm,
      });
  }

  formatterExpaned(tgt, params) {
    //분할 formatter
    let rowData = tgt.getData();
    if (rowData["REL"] === "S") {
      return "<i class='fa-regular fa-circle-xmark text-danger'></i>";
    } else {
      return "<i class='fa-solid fa-code-branch'></i>";
    }
  }

  formatterSelect(tgt, params) {
    let rowData = tgt.getData();
    if (
      rowData["REL"] === "S" ||
      !rowData["_children"] ||
      rowData["_children"].filter((sr) => sr["_STATUS_"] !== "D").length === 0
    ) {
      return tb_common_funtions.formatterSelect(tgt, params);
    } else {
      return "";
    }
  }

  formatterHiddenMVal(tgt, params) {
    //값 숨김 formatter
    let rowData = tgt.getData();
    if (
      rowData["REL"] === "S" ||
      !rowData["_children"] ||
      rowData["_children"].filter((sr) => sr["_STATUS_"] !== "D").length === 0
    ) {
      if (params.func) {
        return params.func(tgt, params);
      } else {
        return tgt.getValue();
      }
    } else {
      return "";
    }
  }

  formatterHiddenSVal(tgt, params) {
    //값 숨김 formatter
    let rowData = tgt.getData();
    if (rowData["REL"] === "S") {
      return "";
    } else {
      if (params.func) {
        return params.func(tgt, params);
      } else {
        return tgt.getValue();
      }
    }
  }

  formatterTotNum(tgt) {
    //수량 formatter
    let rowData = tgt.getData();
    let childRowData = rowData["_children"]
      ? rowData["_children"].filter((sr) => sr["_STATUS_"] !== "D")
      : [];
    let theVal = rowData["ORD_QTY"];
    if (rowData["REL"] !== "S") {
      let subSum = childRowData.length
        ? childRowData.reduce((rev, r) => rev + r["ORD_QTY"], 0)
        : theVal;
      if (theVal != subSum) {
        tgt.getElement().classList.add("warn-cell");
      } else {
        tgt.getElement().classList.remove("warn-cell");
      }
    }
    return theVal;
  }

  formatterRow(row) {
    //Row formatter
    let rowData = row.getData();
    if (rowData["_STATUS_"] === "D") {
      row.getElement().classList.add("del-row");
    } else {
      row.getElement().classList.remove("del-row");
    }

    //if( rowData['WO_MAKE_FLG'] !== 'Y' || rowData['ORD_STATUS'] === 'Y' ){
    if (
      rowData["WO_MAKE_FLG"] !== "Y" ||
      varsOPSTATUS["WORK"].includes(rowData["PLN_STATUS"])
    ) {
      row.getElement().classList.add("text-secondary");
      row.getElement().classList.add("bg-light");
      row.selectable = false;
    }
  }

  callbackPatitial(tbl, trow) {
    //테이블 전체 수량 formmater
    tbl.getRows().forEach((row) => {
      let rowData = row.getData();
      let fld = ["FACLT_CD", "PLN_ST_TM"];

      if (
        !rowData["_children"] ||
        rowData["_children"].filter((sr) => sr["_STATUS_"] !== "D").length === 0
      ) {
        fld.forEach((tgt) => row.getCell(tgt).setValue(rowData[tgt]));
        fld.forEach((tgt) =>
          row.getCell(tgt).getElement().classList.add("tabulator-editable")
        );
      } else {
        fld.forEach((tgt) => row.getCell(tgt).setValue(""));
        fld.forEach((tgt) =>
          row.getCell(tgt).getElement().classList.remove("tabulator-editable")
        );
      }

      row.getCell("ORD_QTY").setValue(rowData["ORD_QTY"]); //수량 트리거
      rowData = row.getData();
      row
        .getCell("PLN_TERM_TM")
        .setValue(
          rowData["_children"]
            ? rowData["_children"]
                .filter((sr) => sr["_STATUS_"] !== "D")
                .reduce((subsum, r) => subsum + Number(r.PLN_TERM_TM), 0)
            : rowData["PLN_TERM_TM"]
        ); //가공시간 트리거
    });
  }

  callbackRowPartitial(row) {
    let rowData = row.getData();
    let fld = ["FACLT_CD", "PLN_ST_TM", "ORD_QTY"];

    if (rowData["_STATUS_"] !== "D") {
      fld.forEach((tgt) =>
        row.getCell(tgt).getElement().classList.add("tabulator-editable")
      );
    } else {
      fld.forEach((tgt) =>
        row.getCell(tgt).getElement().classList.remove("tabulator-editable")
      );
    }
  }

  chkEditable(tgt) {
    //수정 가능여부 체크
    let rowData = tgt.getData();
    //return rowData['WO_MAKE_FLG'] === 'Y' && rowData['_STATUS_'] !== "D" && rowData['ORD_STATUS'] !== "Y" && (!rowData['_children'] || rowData['_children'].filter( sr => sr['_STATUS_'] !== 'D' ).length === 0 );
    return (
      rowData["WO_MAKE_FLG"] === "Y" &&
      rowData["_STATUS_"] !== "D" &&
      //rowData['ORD_STATUS']  !== "Y" &&
      !varsOPSTATUS["WORK"].includes(rowData["PLN_STATUS"]) &&
      (!rowData["_children"] ||
        rowData["_children"].filter((sr) => sr["_STATUS_"] !== "D").length ===
          0)
    );
  }

  chkEditable2(tgt) {
    //수정 가능여부 체크2
    let rowData = tgt.getData();
    return (
      rowData["REL"] === "S" &&
      rowData["_STATUS_"] !== "D" &&
      //rowData['ORD_STATUS'] !== "Y"
      !varsOPSTATUS["WORK"].includes(rowData["PLN_STATUS"])
    );
  }

  //시작 실행
  initload(row) {
    let _this = this;
    let factlist = varsFactInfo.reduce((nval, val) => {
      nval[val.FACLT_CD] = val.FACLT_NM;
      return nval;
    }, {});
    const fields = [
      {
        field: "OP_SEQ",
        title: "공순",
        width: "5%",
        minWidth: 50,
        formatter: _this.formatterHiddenSVal,
      },
      {
        field: "OP_CD",
        title: "공정명",
        width: "15%",
        minWidth: 100,
        formatter: _this.formatterHiddenSVal,
        formatterParams: {
          values: varOPGRP.reduce((r, v) => {
            return Object.assign(
              r,
              v.OPTIONS.reduce((rev, vo) => {
                rev[vo.OP_CD] = vo.OP_NM;
                return rev;
              }, {})
            );
          }, {}),
          func: tb_common_funtions.formatterSelect,
        },
      },
      {
        field: "FACLT_CD",
        title: "설비",
        width: "16%",
        minWidth: 100,
        editor: "list",
        editorParams: { clearable: true, values: factlist },
        formatter: _this.formatterSelect,
        formatterParams: { values: factlist },
        editable: _this.chkEditable,
      },
      {
        field: "PLN_ST_TM",
        title: "시작시간",
        width: "18%",
        minWidth: 150,
        editor: "input",
        editable: _this.chkEditable,
        formatter: _this.formatterHiddenMVal,
      },
      {
        field: "PLN_ED_TM",
        title: "종료시간",
        width: "16%",
        minWidth: 120,
        visible: false,
        formatter: _this.formatterHiddenMVal,
      },
      {
        field: "ORD_QTY",
        title: "수량",
        width: "6%",
        minWidth: 50,
        editor: "number",
        editorParams: { min: 0 },
        editable: _this.chkEditable2,
        formatter: _this.formatterTotNum,
      },
      { field: "ST", title: "셋업시간<br>(분)", width: "10%", minWidth: 90 },
      {
        field: "CT",
        title: "단위가공시간<br>(분)",
        width: "12%",
        minWidth: 90,
      },
      //{ field: "OP_COUNT",    title: "가공횟수",             width: "8%",  minWidth:70,  },
      {
        field: "PLN_TERM_TM",
        title: "가공시간<br>(분)",
        width: "10%",
        minWidth: 90,
      },
      {
        field: "btn_branch",
        title: "분할",
        width: "6%",
        minWidth: 50,
        formatter: _this.formatterExpaned,
      },
    ];

    _this.tblList = new Tabulator("#pop_plan_route", {
      layout: "fitColumns",
      height: "100%",
      data: [], //기본 데이터
      columns: fields, //컬럼 설정
      dataTree: true,
      dataTreeStartExpanded: true,
      dataTreeElementColumn: "OP_CD",
      columnDefaults: {
        //컬럼 공통 규칙
        headerSort: false,
        vertAlign: "middle",
        hozAlign: "center",
        resizable: "header", //Resize 는 헤더에서만 가능
        headerHozAlign: "center", //헤더 정렬
        headerSortTristate: true, //데이터 정렬 => 정/역/초기화
      },
      headerSortElement: "<i class='bi'></i>", //정렬 아이콘
      rowFormatter: _this.formatterRow,
    });

    _this.tblList.on("tableBuilt", () => {
      //Tabulator 초기 데이터 불러오기 이벤트
      _this.getMainList(row);
    });

    _this.tblList.on("cellClick", (e, tgt) => {
      //Tabulator cell Click
      _this.cellClick(e, tgt);
    });
    _this.tblList.on("cellEdited", (cell) => {
      //Tabulator cell Edited
      _this.cellEdited(cell);
    });
    _this.tblList.on("cellEditing", (cell) => {
      //Tabulator cell Edited
      _this.cellEditing(cell);
    });

    ["click", "keypress"].forEach((evt) =>
      document
        .querySelector("#pop_plan_search .btn_prim")
        .addEventListener(evt, () => {
          _this.putPlanRoute();
        })
    );
    ["click", "keypress"].forEach((evt) =>
      document
        .querySelector("#pop_plan_search .btn_close")
        .addEventListener(evt, () => {
          _this.routeModal.delete();
        })
    );
  }
}

class conditionRemkManager {
  constructor() {
    let _this = this;
    _this.tblList = "";
    _this.ajax_url = "/order/condition/condition.ajax.php";
  }

  init(tcell) {
    let _this = this;

    vnLoad("", "/order/condition/remk.pop.inc.php", "", function (loadHtml) {
      _this.remkModal = kuls_modal(loadHtml);

      _this.initload(tcell);
    });
  }

  //리스트 로드
  getMainList(tcell) {
    let _this = this;

    let rowData = Object.assign({}, tcell.getData());
    Object.keys(rowData).forEach((key) => {
      if (document.getElementById("pop_" + key))
        document.getElementById("pop_" + key).innerHTML = rowData[key];
    });

    let talert = window.setTimeout(function () {
      _this.tblList.alert("Loading ...");
    }, 1000); //1초 이상 지연되면 로딩 출력
    ajax_json({
      url: _this.ajax_url,
      data: {
        mode: "getRouteList2",
        MNG_NO: rowData["MNG_NO"],
        OP_CD: rowData["OP_CD"],
      },
      success: function (data) {
        if (data.code) {
          _this.tblList.setData(data.data);
        } else {
          kuls_alert(data.mesg);
        }
      },
      error: function (request, status, error) {
        kuls_alert(error.message);
      },
      complete: function () {
        window.clearTimeout(talert);
        _this.tblList.clearAlert();
      },
    });
    return true;
  }

  //Cell 변경 콜백
  cellEdited(cell) {
    let _this = this;

    cell.getData()._STATUS_ = cell.getData()._STATUS_ || "U";
  }

  //등록
  putRemk(tcell) {
    let _this = this;
    let tblData = _this.tblList.getData();
    tcell.getRow().update({ REMK: tblData[0].REMK });
    _this.remkModal.delete();
    // let tblData = _this.tblList.getData();
    // let postdata = {
    //   'mode': 'putRouteList',
    //   'reqdata': JSON.stringify(tblData),
    // };
    // ajax_json({
    //   url: _this.ajax_url,
    //   data: postdata,
    //   success: function (data) {
    //     if (data.code) {
    //       kuls_success("저장되었습니다.");
    //       _this.remkModal.delete();
    //     }else{
    //       kuls_alert(data.mesg);
    //     }
    //   },
    //   error: function (request, status, error) {
    //     kuls_alert(error.message);
    //   },
    //   complete: function () {
    //   }
    // });
    return true;
  }

  //시작 실행
  initload(tcell) {
    let _this = this;
    const fields = [
      { field: "OP_SEQ", title: "공순", width: "10%" },
      {
        field: "OP_CD",
        title: "공정명",
        width: "20%",
        formatter: tb_common_funtions.formatterSelect,
        formatterParams: {
          values: varOPGRP.reduce((r, v) => {
            return Object.assign(
              r,
              v.OPTIONS.reduce((rev, vo) => {
                rev[vo.OP_CD] = vo.OP_NM;
                return rev;
              }, {})
            );
          }, {}),
        },
      },
      {
        field: "REMK",
        title: "지시사항",
        width: "70%",
        formatter: "textarea",
        editor: "textarea",
        editorParams: {
          elementAttributes: { maxlength: "500" },
          verticalNavigation: "editor",
        },
        hozAlign: "left",
      },
    ];

    _this.tblList = new Tabulator("#pop_condition_remk", {
      layout: "fitColumns",
      height: "100%",
      rowHeight: 450,
      data: [], //기본 데이터
      columns: fields, //컬럼 설정
      columnDefaults: {
        //컬럼 공통 규칙
        headerSort: false,
        vertAlign: "middle",
        hozAlign: "center",
        resizable: "header", //Resize 는 헤더에서만 가능
        headerHozAlign: "center", //헤더 정렬
        headerSortTristate: true, //데이터 정렬 => 정/역/초기화
        height: "100%",
      },
      headerSortElement: "<i class='bi'></i>", //정렬 아이콘
    });

    _this.tblList.on("tableBuilt", () => {
      //Tabulator 초기 데이터 불러오기 이벤트
      _this.tblList.setData([tcell.getData()]);
      //_this.getMainList(tcell);
    });
    _this.tblList.on("cellEdited", (cell) => {
      //Tabulator cell Edited
      _this.cellEdited(cell);
    });

    ["click", "keypress"].forEach((evt) =>
      document
        .querySelector("#pop_remk_search .btn_prim")
        .addEventListener(evt, () => {
          _this.putRemk(tcell);
        })
    );
    ["click", "keypress"].forEach((evt) =>
      document
        .querySelector("#pop_remk_search .btn_close")
        .addEventListener(evt, () => {
          _this.remkModal.delete();
        })
    );
  }
}

document.querySelectorAll("#mtop_search input").forEach((tgt) => {
  tgt.addEventListener("keypress", (e) => {
    if (e.key == "Enter") {
      document
        .querySelector("#mtop_search button.btn_prim")
        .dispatchEvent(new Event("click"));
    }
  });
});

jQuery(document).on("focus", ".user-editable input", function () {
  jQuery(this).attr("readonly", true);
  jQuery(this).trigger("click");
});






  // 선택태그 옵션 생성
function setSelectOption(selectKey, tag, name){
  // 옵션값 자동 렌더링
  const createOpt = function(optValue, optText){
    const opt = document.createElement('option');
    opt.value = optValue;
    opt.text = optText;

    return opt;
  }
  // 선택태그 있으면
  const selectTag = document.querySelector(tag);
  if(selectTag){
    selectTag.options.length = 0;
    const opt = createOpt('',`- ${name} -`)
    selectTag.add(opt);

    Object.keys(selectKey).forEach(key => {
      selectTag.add(createOpt(key, selectKey[key]));
    });

  }
}

setSelectOption(varsITEM_GRP,'select#ITEM_GRP', '품목그룹');
setSelectOption(varsWH_TYPE,'select#WH_TYPE', '창고유형');
setSelectOption(varsWO_STATUS,'select#WO_STATUS', '지시상태');

// 인풋에서 엔터하면 조회버튼 CLICK효과
document.querySelectorAll('.search-container input').forEach((input)=>{
  input.addEventListener("keyup",function(e){
    if(e.key === 'Enter'){
      e.preventDefault();
      document.querySelector('#filter_btn').click();
    }
  })
})