
const createOpt = function (optValue, optText) {
  const opt = document.createElement('option');
  opt.value = optValue;
  opt.text = optText;
  
  return opt;
}

/*
 * @Overview : 테이블이 있는 팝업
 * @Params : 팝업의 id또는 class, 테이블 field, ({팝업의 컬럼명 : 입력될 컬럼명 || id}), 데이터 조회에 사용할 vars000(기초코드), getMode(ajax), 데이터가 입력될 row, 더블클릭 허용여부, 조회조건
 * @Params2 : 추가적인 params(선택), 테이블 아이디(선택)
 */
class CreatePopup {
  constructor(options) {
    const {
      container,
      fields,
      columns,
      selectKey,
      mode,
      tabrow,
      dbClickable,
      setFilter,
      params,
      tableId,
    } = options;

    this.container = container;
    this.fields = fields;
    this.columns = columns;
    this.selectKey = selectKey;
    this.mode = mode;
    this.tabrow = tabrow;
    this.dbClickable = dbClickable;
    this.params = params?params:'';
    this.tableId = tableId?tableId:'.awn-popup-confirm .hy-table';


    // 콜백 함수
    this.setFilter = setFilter;
  }

  /*
   * 초기화
   * bool : 외부 클릭시 닫힘 방지 및 중복 팝업 여부
   */
  init(bool) {
    vnLoad('', '/ksvc/inc/popup.php', this.container, (loadHtml) => {
      
      if(bool){
        this.modal = kuls_modal(loadHtml, { dontclose: true});
        this.modal.el.classList.add("no-background");
      }else{
        this.modal = kuls_modal(loadHtml);
      }
      this.setSelectOption();
        
      //컬럼 공통 규칙
      const commonFieldData = {
        vertAlign: "middle",
        hozAlign: "center",
        resizable: "header",
        headerHozAlign: "center",
        headerSortTristate: true,
      };

      // 테이블 생성
      this.tbModal = new Tabulator(this.modal.el.querySelector(this.tableId), {
        layout: "fitColumns",
        columns: this.fields, //컬럼 설정
        columnDefaults: commonFieldData,
        headerSortElement: "<i class='bi'></i>", //정렬 아이콘
      });


      const addBtn = document.querySelector("#awn-popup-wrapper .add-btn") || "";
      const removeBtn = document.querySelector("#awn-popup-wrapper .remove-btn") || "";

      const ptResetBtn = document.querySelector("#awn-popup-wrapper #ptReset") || false;
      const textSearch = document.querySelector("#awn-popup-wrapper [name=stxt]") || false;
      const selectSearch = document.querySelector("#awn-popup-wrapper [name=sgrp]") || false;

      if (ptResetBtn) {
        ptResetBtn.addEventListener("click", () => {
          this.initData();
          this.modal.delete();
        });
      }

      if (textSearch) {
        textSearch.addEventListener("keyup", () => { //검색어 입력 이벤트
          this.setFilter(this.tbModal);
        });
      }

      if (this.selectKey) {
        selectSearch.addEventListener("change", () => { //영업분류 변경 이벤트
          this.setFilter(this.tbModal);
        });
      }

      this.tbModal.on("rowDblClick", (e, tgt) => {
        this.dbClickable && this.dbClick(e, tgt);

      });
      // 테이블 리스트 렌더링
      this.tbModal.on("tableBuilt", () => { //초기 데이터 불러오기 이벤트
        this.getPopList();
      });

      /*
       * @Overview cell 클릭시 체크 또는 팝업
       * @Parameter 이벤트, 셀
       */
      this.tbModal.on("cellClick", (e, tgt) => {
        this.cellClick && this.cellClick(e, tgt);
      });

      // 추가
      ["click", "keypress"].forEach((evt) => {
        addBtn.addEventListener && addBtn.addEventListener(evt, () => {
          this.addRow && this.addRow();
        });
      });
      // 삭제
      ["click", "keypress"].forEach((evt) => {
        removeBtn.addEventListener && removeBtn.addEventListener(evt, () => {
          // 삭제 함수
          this.removeRow && this.removeRow();
        });
      });

    })
    // vnload 끝

  }

  setData(e, tgt) {
    let row = tgt._row;
    if (this.tabrow) {
      let uptjson = {_STATUS_: this.tabrow.getData()['_STATUS_'] || 'U'};
      Object.keys(this.columns).forEach(key => {
        uptjson[key] = row.data[this.columns[key]]; // 직접 할당
      });
      this.tabrow.update(uptjson);
    } else {
      Object.keys(this.columns).forEach(key => {
        document.querySelector("#" + this.columns[key]).value = row.data[key];
      })
    }
  };

  initData() {
    if (this.tabrow) {
      let uptjson = {_STATUS_: this.tabrow.getData()['_STATUS_'] || 'U'};
      Object.keys(this.columns).forEach(key => {
        uptjson[key] = ""; // 직접 할당
      });
      this.tabrow.update(uptjson);
    } else {
      Object.keys(this.columns).forEach(key => {
        document.querySelector("#" + this.columns[key]).value = "";
      })
    }
  };

  // 선택태그 옵션 생성
  setSelectOption() {
    // 선택태그 있으면
    if (this.selectKey) {
      const selectTag = document.querySelector('#sgrp');
      selectTag.options.length = 0;
      const opt = createOpt('', '- 전 체 -')
      selectTag.add(opt);

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

  // 데이터 렌더링
  getPopList() {
    console.log(this.params);
    ajax_json({
      url: "/ksvc/inc/common.ajax.php",
      data: {...this.params, mode: this.mode},
      success: (data) => {
        if (data.code) {
          // console.log(data.data)
          this.tbModal.setData(data.data);
          if (this.columns.tgt_filter && this.columns.txt_filter) {
            document.querySelector(this.columns.tgt_filter).value = this.columns.txt_filter;
            this.setFilter();
          }
        }
      },
      error: (request, status, error) => {
        kuls_alert(error.message);
      },
    });
  };

  /*
   * @Overview 테이블 행 추가 함수
   * @Parameter 없음
   * @function 기본키, _STATUS_:I 값을 넣은 행 추가
   */
  addRow() {
    this.tbModal.addRow({_STATUS_: "I"});
  }

  /*
   * @Overview 테이블 행 삭제 함수
   * @Parameter 없음
   * @function 선택된 모든 행 STATUS D
   */
  removeRow() {
    const selectedRows = this.tbModal.getSelectedRows(); // 선택된 모든 행 가져오기

    // 선택된 각 행 삭제
    selectedRows.forEach((row) => {
      // STAUS D로 바꾸기
      row.getData()._STATUS_ = row.getData()._STATUS_ == "I" ? null : "D";

      const rowElement = row.getElement();
      rowElement.classList.add("remove-row");
    });
  }

  /*
   * @Overview cell 클릭 함수
   * @Parameter 클릭한 cell
   * @Function 클릭한 cell의 filed 값에 따라 토글 상태 변경 또는 팝업
   */
  cellClick(e, tgt) {
    var editor = tgt.getColumn().getDefinition().editor;

    switch (tgt.getField()) {
      default:
        if (!editor) {
          this.rowClick && this.rowClick(e, tgt.getRow());
        }
        break;
    }
  }

  /*
   * @Overview 테이블 행 선택 함수
   * @Parameter 이벤트, 타겟 행
   */
  rowClick(e, tgt) {
    if (tgt.isSelected()) {
      tgt.deselect();
    } else {
      tgt.select();
    }
  }

  /*
   * @Overview 테이블 행 선택 함수
   * @Parameter 이벤트, 타겟 행
   */
  dbClick(e, tgt) {
    let rowData = tgt._row.data

    this.setData(e, tgt);

    this.modal.delete();
  }

}

/*
 * @Overview 거래처 코드 찾기 팝업 생성
 */
const popClient = function (columns, tabrow) {
  const fields = [
    {formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center',},
    // {field: "SALES_GRP", title: "영업구분", width: 100, 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: 100,},
    {field: "PUR_FLG", title: "매입처", width: 70, formatter: tb_common_funtions.formatterSelCircleIcon,},
    {field: "SAL_FLG", title: "매출처", width: 70, formatter: tb_common_funtions.formatterSelCircleIcon,},
  ];

  const setTableFilter = function (modal) {
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    // let sgrp = trim(document.querySelector("#awn-popup-wrapper select[name=sgrp]").value);
    modal.setFilter(function (data) {
      // return (!sgrp || data['SALES_GRP'] === sgrp) &&
      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 Tb_modal = new CreatePopup({
    container: '#popup_client_container',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "getPartnerList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
  });

  Tb_modal.init();
}

/*
 * @Overview 사업장 코드 찾기 팝업 생성
 */
const popBizArea = function (columns, tabrow) {
  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: 150,},
    {field: "HQ_FLG", title: "본사구분", width: 100,},
    {field: "WORK_STD_TIME", title: "기준시간", width: 100,},
    {field: "STD_CURRENCY_CD", title: "기준화폐", width: 100,},
  ];

  const setTableFilter = function (modal) { //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    modal.setFilter(function (data) {
      return (!stxt || data['BIZ_AREA_CD'].search(RegExp(stxt, "is")) !== -1 || data['BIZ_AREA_NM'].search(RegExp(stxt, "is")) !== -1)
    }, '=', true);
  };
  const Tb_modal = new CreatePopup({
    container: '#popup_bizarea_container',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "getBizareaList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
  });

  Tb_modal.init();

}

/*
 * @Overview 부서 코드 찾기 팝업 생성
 */
const popDept = function (columns, tabrow) {
  const fields = [
    {formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center',},
    {field: "DEPT_CD", title: "부서코드", width: 100,},
    {field: "DEPT_NM", title: "부서명", width: 150,},
    {field: "PAR_DEPT_CD", title: "상위부서코드", width: 100,},
    {field: "PAR_DEPT_NM", title: "상위부서명", width: 100,},
    {field: "BIZ_AREA_NM", title: "사업장명", width: 100,},
  ];

  const setTableFilter = function (modal) { //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    modal.setFilter(function (data) {
      return (!stxt || data['DEPT_NM'].search(RegExp(stxt, "is")) !== -1 || data['DEPT_NM'].search(RegExp(stxt, "is")) !== -1)
    }, '=', true);
  };
  const Tb_modal = new CreatePopup({
    container: '#popup_dept_container',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "getDeptList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
  });

  Tb_modal.init();
}

/*
 * @Overview 공정 코드 찾기 팝업 생성
 */
const popOper = function (columns, tabrow) {
  const fields = [
    {formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center',},
    {field: "OP_CD", title: "공정코드", width: 100,},
    {field: "OP_NM", title: "공정명", width: 100,},
    {field: "REMK", title: "비고", width: 300,},
  ];

  const setTableFilter = function (modal) { //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    modal.setFilter(function (data) {
      return (!stxt || data['OP_CD'].search(RegExp(stxt, "is")) !== -1 || data['OP_NM'].search(RegExp(stxt, "is")) !== -1)
    }, '=', true);
  };
  const Tb_modal = new CreatePopup({
    container: '#popup_oper_container',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "getOperList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
  });

  Tb_modal.init();
}

/*
 * @Overview 특정 품목에 대한 공정 코드 찾기 팝업 생성
 */
// const popItemOper = function( columns, tabrow ){
//
//   const fields = [
//     { formatter:"rownum", title: "No",           width: 50,  headerSort: false, hozAlign:'center', },
//     { field: "OP_CD",     title: "공정코드",     width: 100, },
//     { field: "OP_NM",     title: "공정명",       width: 100, },
//     { field: "OP_GRP",    title: "공정그룹",     width: 100, },
//     { field: "REMK",      title: "비고",         width: 200, },
//   ];
//
//   const setTableFilter = function(modal){ //검색어 필터 적용
//     let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
//     modal.setFilter(function(data){
//       return (!stxt || data['OP_CD'].search(RegExp(stxt,"is")) !== -1  || data['OP_NM'].search(RegExp(stxt,"is")) !== -1)
//     }, '=', true);
//   };
//   const Tb_modal = new CreatePopup({
//     container: '#popup_oper_container',
//     fields: fields,
//     columns: columns,
//     selectKey: false,
//     mode: "getItemOperList",
//     tabrow: tabrow,
//     dbClickable: true,
//     setFilter: setTableFilter,
//   });
//
//   Tb_modal.init();
// }


/*
 * @Overview 설비 코드 찾기 팝업 생성
 */
const popFacility = function (columns, tabrow) {
  const fields = [
    {formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center',},
    {field: "FACLT_CD", title: "설비코드", width: 150,},
    {field: "FACLT_NM", title: "설비명", width: 150,},
    {field: "FACLT_MNG_NO", title: "관리번호", width: 100,},
    {field: "MAJR_EMP_NO", title: "담당자정", width: 100,},
    {field: "PURPOS_USAGE", title: "용도", width: 200,},
  ];

  const setTableFilter = function (modal) { //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    // let sgrp = trim(document.querySelector("#awn-popup-wrapper select[name=sgrp]").value);
    // (!sgrp || data["ITEM_GRP"] === sgrp) &&
    modal.setFilter(function (data) {
      return (!stxt || data['FACLT_NM'].search(RegExp(stxt, "is")) !== -1 || data['FACLT_NM'].search(RegExp(stxt, "is")) !== -1)
    }, '=', true);
  };
  const Tb_modal = new CreatePopup({
    container: '#popup_facility_container',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "getFacilityList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
  });

  Tb_modal.init();
}

/*
 * @Overview 사원 코드 찾기 팝업 생성
 */
const popWorker = function (columns, tabrow) {
  const fields = [
    {formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center',},
    {field: "EMP_NO", title: "사번", width: 100,},
    {field: "EMP_NM", title: "성명", width: 100,},
    {field: "EMP_SHORT_NM", title: "영문명", width: 150,},
    {field: "WRK_TEAM", title: "부서", width: 100,},
    {
      field: "JOB_POS", title: "직위", width: 100,
      formatter: tb_common_funtions.formatterSelect,
      formatterParams: {values: varsPosition},
    },
    {
      field: "JOB_FUNC", title: "현장직", width: 50,
      formatter : tb_common_funtions.formatterSelCircleIcon,
    },
    // {field: "EMPLM_TYPE", title: "고용형태", width: 100,},
    // {field: "MAIL_ID", title: "이메일", width: 200,},
    // {field: "ENT_DT", title: "입사일", width: 150,},
  ];

  const setTableFilter = function (modal) { //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    modal.setFilter(function (data) {
      return ((!stxt || data['EMP_NM'].search(RegExp(stxt, "is")) !== -1))
    }, '=', true);
  };
  const Tb_modal = new CreatePopup({
    container: '#popup_worker_container',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "getWorkerList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
  });

  Tb_modal.init();
}

/*
 * @Overview 거래처 수정 팝업
 */
const popClientEditor = function (columns, tabrow) {

  const fields = [
    {formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center',},
    {field: "", title: "담당자명", width: 100,},
    {field: "", title: "이메일", width: 200,},
    {field: "", title: "연락처", width: 150,},
    {field: "", title: "휴대폰", width: 150,},
    {field: "", title: "FAX NO", width: 150,},
    {field: "", title: "비고", width: 300,},
    {
      field: "",
      title: "메인",
      width: 50,
      formatter: tb_common_funtions.formatterCheckIcon2,
      formatterParams: {checkval: 'Y'}
    },
  ];

  // 검색기능 필터
  const setTableFilter = function (modal) { //검색어 필터 적용
  };

  const Tb_modal = new CreatePopup({
    container: '#popup_client_editor',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "",
    tabrow: tabrow,
    dbClickable: false,
    setFilter: setTableFilter,
  });

  Tb_modal.init();
}


/*
* @Overview 품목 찾기 팝업 생성
*/
const popItem = function (columns, tabrow) {
  const fields = [
    {formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center',},
    {field: "ITEM_CD", title: "품목 코드", width: 100,},
    {field: "ITEM_NM", title: "품목 이름", width: 250, hozAlign: 'left'},
    // {field: "DRAW_NO", title: "도면번호", width: 150,},
    {field: "ITEM_GRP", title: "품목그룹", width: 100, formatter: tb_common_funtions.formatterSelect, formatterParams: {values: varsITEM_GRP} },
    // {field: "DRAW_VER", title: "도면버전", width: 100,},
  ];

  const setTableFilter = function (modal) { //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    let sgrp = trim(document.querySelector("#awn-popup-wrapper select[name=sgrp]").value);
    modal.setFilter(function (data) {
      return (!sgrp || data["ITEM_GRP"] === sgrp) &&
             (!stxt || data['ITEM_CD'].search(RegExp(stxt, "is")) !== -1 || data['ITEM_NM'].search(RegExp(stxt, "is")) !== -1)
    }, '=', true);
  };
    // let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    // modal.setFilter(function (data) {
    //   return (!stxt || data['ITEM_CD'].search(RegExp(stxt, "is")) !== -1 || data['ITEM_NM'].search(RegExp(stxt, "is")) !== -1)
    // }, '=', true);
  // };
  const Tb_modal = new CreatePopup({
    container: '#popup_item_container',
    fields: fields,
    columns: columns,
    selectKey: varsITEM_GRP,
    mode: "getItemList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
  });

  Tb_modal.init();
}

/*
* @Overview 품목 라우팅
*/
const popRouting = function (columns, ITEM_CD) {
  const fields = [
    { field: "OP_SEQ", title: "공순", width: 65},
    { title: "공정", cssClass:"width-200", columns:[
        {field:"OP_CD", width:100},
        {field:"OP_NM", width:100}
      ]
    },
    { field: "STD_SETUP_TM", title: "준비시간</br>(분)", width: 80, 
      formatterParams:{
        decimal:".",
        precision:0
      },
    },
    { field: "CYCLE_TM", title: "공정시간</br>(분)", width: 80, 
      formatterParams:{
        decimal:".",
        precision:0
      }
    },
    { field: "STD_OP_AMT", title: "공정 단가</br>(원)", width: 80 ,
      formatter:"money",
      formatterParams:{
        decimal:".",
        precision:0
      }
    },
  ];

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

  const Tb_modal = new CreatePopup({
    container: "#popup_routing_container",
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "getRoutingList",
    tabrow: false,
    dbClickable: false,
    setFilter: setTableFilter,
    params : { ITEM_CD : ITEM_CD},
  });

  Tb_modal.init(true);

}

/*
 * @Overview 검사항목검색
 */
const popInsp = function (columns, tabrow) {
  const fields = [
    {formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center',},
    {field: "INSP_ITEM", title: "검사항목", width: 100,},
    {field: "INSP_NAME", title: "검사항목명", width: 150,},
    {field: "INSP_METH", title: "검사방법", width: 150, formatter: tb_common_funtions.formatterSelect, formatterParams: {values: varsINSP_METH}},
  ];

  const setTableFilter = function (modal) { //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    let sgrp = trim(document.querySelector("#awn-popup-wrapper select[name=sgrp]").value);
    modal.setFilter(function (data) {
      return (!sgrp || data["INSP_METH"] === sgrp) &&
             (!stxt || data['INSP_NAME'].search(RegExp(stxt, "is")) !== -1)
    }, '=', true);
  };
  const Tb_modal = new CreatePopup({
    container: '#popup_insp_container',
    fields: fields,
    columns: columns,
    selectKey: varsINSP_METH,
    mode: "getInspList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
  });

  Tb_modal.init();
}
/*
 * @Overview 검사항목검색
 */
const popInspItem = function (columns, tabrow, params) {
  const fields = [
    {formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center',},
    {field: "INSP_ITEM", title: "검사항목", width: 100,},
    {field: "INSP_NAME", title: "검사항목명", width: 150,},
    {field: "INSP_METH", title: "검사방법", width: 150, formatter: tb_common_funtions.formatterSelect, formatterParams: {values: varsINSP_METH}},
    {field: "SPEC_VAL", title: "기준값", width: 150,},
    {field: "TOL_UPPER", title: "상한값", width: 150,},
    {field: "TOL_LOWER", title: "하한값", width: 150,},
  ];
  
  const setTableFilter = function (modal) { //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    let sgrp = trim(document.querySelector("#awn-popup-wrapper select[name=sgrp]").value);
    modal.setFilter(function (data) {
      return (!sgrp || data["INSP_METH"] === sgrp) &&
      (!stxt || data['INSP_NAME'].search(RegExp(stxt, "is")) !== -1)
    }, '=', true);
  };
  const Tb_modal = new CreatePopup({
    container: '#popup_insp_item',
    fields: fields,
    columns: columns,
    selectKey: varsINSP_METH,
    mode: "getInspItem",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
    params: params,
    tableId: '#insp_item'
  });
  
  Tb_modal.init();
  console.log(Tb_modal)
}


/*
 * @Overview 생산 오더별 공정 검색
 */
const popOrder = function (columns, tabrow) {
  const fields = [
    {field: "WO_SEQ", formatter: "rownum", title: "No", width: 40, headerSort: false, hozAlign: 'center',},
    {field: "WO_NO", title: "생산오더", width: 60,},
    {field: "OP_CD", title: "공정", width: 40,},
    // {field: "FACLT_CD", title: "설비", width: 100,},
    {field: "ITEM_CD", title: "품목", width: 100,},
    {field: "ITEM_NM", title: "품명", width: 400, hozAlign:"left"},
    {field: "ORD_QTY", title: "지시수량", width: 60, formatter: "money", formatterParams: {decimal: ",", precision: 0}},
    {field: "WRK_QTY", title: "생산수량", width: 60, formatter: "money", formatterParams: {decimal: ",", precision: 0}},
    {field: "PLANT_CD", title: "공장", width: 60,},
  ];

  const setTableFilter = function (modal) { //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    modal.setFilter(function (data) {
      // return (!stxt || data['INSP_ITEM'].search(RegExp(stxt,"is")) !== -1  || data['INSP_NAME'].search(RegExp(stxt,"is")) !== -1) 
      return (!stxt || data['ITEM_NM'].search(RegExp(stxt, "is")) !== -1)
    }, '=', true);
  };
  const Tb_modal = new CreatePopup({
    container: '#popup_order_container',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "getOrderList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
  });

  Tb_modal.init();
}


/*
 * @Overview 불량선택
 */
const popDef = function (columns, tabrow) {
  const fields = [
    {formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center',},
    // { field: "DEF_FACLT_CD",    title: "불량설비",      width: 100, },
    {field: "DEF_OP_CD", title: "공정", width: 150,},
    {field: "DEF_CD", title: "불량코드", width: 150,},
    // { field: "DEF_QTY", title: "불량수량", width: 150, },


  ];

  const setTableFilter = function (modal) { //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    modal.setFilter(function (data) {
      // return (!stxt || data['INSP_ITEM'].search(RegExp(stxt,"is")) !== -1  || data['INSP_NAME'].search(RegExp(stxt,"is")) !== -1) 
      return (!stxt || data['DEF_FACLT_CD'].search(RegExp(stxt, "is")) !== -1)
    }, '=', true);
  };
  const Tb_modal = new CreatePopup({
    container: '#popup_def_container',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "getDefList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
  });

  Tb_modal.init();
}

/*
 * @Overview 생산실적 오더별 공정 검색
 */
const popRegOrder = function (columns, tabrow) {
  const fields = [
    {field: "WO_SEQ", formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center',},
    {field: "WO_NO", title: "생산오더", width: 100,},
    {field: "ITEM_CD", title: "품목", width: 100,},
    {field: "ITEM_NM", title: "품명", width: 400,},
    {field: "DRAW_NO", title: "도면번호", width: 150,},
    {field: "OP_SEQ", title: "공순", width: 100,},
    {field: "OP_CD", title: "공정", width: 100,},
    {field: "ORD_QTY", title: "지시수량", width: 100, formatter: "money", formatterParams: {decimal: ",", precision: 0}},
    {field: "PRV_OP_CD", title: "이전공정", width: 100,},
    {
      field: "OP_WRK_QTY",
      title: "이전공정실적",
      width: 100,
      formatter: "money",
      formatterParams: {decimal: ",", precision: 0}
    }
  ];

  const setTableFilter = function (modal) { //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    modal.setFilter(function (data) {
      // return (!stxt || data['INSP_ITEM'].search(RegExp(stxt,"is")) !== -1  || data['INSP_NAME'].search(RegExp(stxt,"is")) !== -1) 
      return (!stxt || data['ITEM_CD'].search(RegExp(stxt, "is")) !== -1)
    }, '=', true);
  };
  const Tb_modal = new CreatePopup({
    container: '#popup_reg_order_container',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "getRegOrderList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
  });

  Tb_modal.init();
}

/*
 * @Overview 생산실적 오더별 공정 검색
 */
const pop_excel_item = function (columns, tabrow) {
  const fields = [
    {field: "WO_SEQ", formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center',},
    {field: "WO_NO", title: "생산오더", width: 100,},
    {field: "ITEM_CD", title: "품목", width: 100,},
    {field: "ITEM_NM", title: "품명", width: 400,},
    {field: "DRAW_NO", title: "도면번호", width: 150,},
    {field: "OP_SEQ", title: "공순", width: 100,},
    {field: "OP_CD", title: "공정", width: 100,},
    {field: "ORD_QTY", title: "지시수량", width: 100, formatter: "money", formatterParams: {decimal: ",", precision: 0}},
    {field: "PRV_OP_CD", title: "이전공정", width: 100,},
    {
      field: "OP_WRK_QTY",
      title: "이전공정실적",
      width: 100,
      formatter: "money",
      formatterParams: {decimal: ",", precision: 0}
    }
  ];


  const Tb_modal = new CreatePopup({
    container: '#pop_item',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
  });

  Tb_modal.init();
}

/*
 * @Overview 생산오더등록 공정별 검사항목 팝업
 */
const popOperCheck = function( columns, tabrow ){
  const fields = [
    { formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center', }, 
    { field: "INSP_NAME",         title: "검사항목",   width: '45%' },
    { field: "INSP_METH",        title: "검사방법",     width: '45%', formatter: tb_common_funtions.formatterSelect, formatterParams: {values: varsINSP_METH,}},

  ];

  const setTableFilter = function(modal){ //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    modal.setFilter(function(data){
      return (!stxt || data['INSP_NAME'].search(RegExp(stxt,"is")) !== -1  || data['INSP_NAME'].search(RegExp(stxt,"is")) !== -1) 
    }, '=', true);
  };
  const Tb_modal = new CreatePopup({
    container: '#popup_oper_check_container',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "getItemOperCheckList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
  });

  Tb_modal.init();
}


/*
 * @Overview 공정 코드 찾기 팝업 생성 (각 생산오더에 대한 값만 출력)
 */
const popOper2 = function (columns, tabrow, WO_NO) {
  const fields = [
    {formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center',},
    {field: "OP_CD", title: "공정코드", width: 100,},
    {field: "OP_NM", title: "공정명", width: 100,},
    {field: "REMK", title: "비고", width: 300,},
  ];

  const setTableFilter = function (modal) { //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    modal.setFilter(function (data) {
      return (!stxt || data['OP_CD'].search(RegExp(stxt, "is")) !== -1 || data['OP_NM'].search(RegExp(stxt, "is")) !== -1)
    }, '=', true);
  };
  const Tb_modal = new CreatePopup({
    container: '#popup_oper_container',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "getRegOperList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
    params: {WO_NO : WO_NO}
  });

  Tb_modal.init();
}

/*
 * @Overview 생산오더등록 공정별 검사항목 팝업 (각 공정에 대한 값만 출력)
 */
const popOperCheck2 = function( columns, tabrow, OP_CD ){
  const fields = [
    { formatter: "rownum", title: "No", width: 50, headerSort: false, hozAlign: 'center', }, 
    { field: "INSP_NAME",         title: "검사항목",   width: '45%' },
    { field: "INSP_METH",        title: "검사방법",     width: '45%', formatter: tb_common_funtions.formatterSelect, formatterParams: {values: varsINSP_METH,}},

  ];

  const setTableFilter = function(modal){ //검색어 필터 적용
    let stxt = trim(document.querySelector("#awn-popup-wrapper input[name=stxt]").value);
    modal.setFilter(function(data){
      return (!stxt || data['INSP_NAME'].search(RegExp(stxt,"is")) !== -1  || data['INSP_NAME'].search(RegExp(stxt,"is")) !== -1) 
    }, '=', true);
  };
  const Tb_modal = new CreatePopup({
    container: '#popup_oper_check_container',
    fields: fields,
    columns: columns,
    selectKey: false,
    mode: "getItemOperCheckList",
    tabrow: tabrow,
    dbClickable: true,
    setFilter: setTableFilter,
    // params: OP_CD
  });

  Tb_modal.init();
}
