// 검사항목 추가 클래스
class PopTbAddInspClass {
  constructor(data){
    this.ajaxUrl = "./reg_insp_qc.ajax.php";
    console.log(data['isInsp'])
    this.data = data['isInsp'] === undefined ? data : data['isInsp'].formData ;
    this.modal = "";
    this.container = "";
    this.table = "";
    this.tableClass = data;
    this.addBtn = "";
  }
  /*
   * @Overview 테이블 행 추가 함수
   * @Parameter 없음
   * @function 기본키, _STATUS_:I 값을 넣은 행 추가
   */
  addRow() {
    this.tbList.addRow({ _STATUS_: "I" });
  }

    /*
   * @Overview 추가, 수정 저장
   * @Parameter 없음
   * @Function _STATUS_ : U, I Row 인 것 php 처리.
   */
    putData() {
      let pdata = this.tbList.getData();

      //
      if (pdata.filter((row) => row._STATUS_).length == 0) {
        return false;
      }
  
      let postdata = {
        mode: "putCheck",
        reqdata: JSON.stringify(
            this.tbList.getData().filter((row) => row._STATUS_ && row.OP_CD && row.INSP_NAME)
        ),
      };
      this.savebreaker = true;
        ajax_json({
          url: "../../prod/reg_order/reg_order.ajax.php",
          data: postdata,
          success: (data) => {
            if (data.code) {
              kuls_success("저장되었습니다.");
              // this.getMainList();

              //검사실적 화면 list 업데이트
              try{
                Tb_insp_reg.getMainList(Tb_order.tbList.getSelectedData()[0].WO_NO);//
              }catch(err){
              //현장장업자 검사실적 화면 list 업데이트
              //   console.log(this.tableClass['isInsp']);
                this.tableClass['isInsp'].getMainList(this.tableClass['isInsp'].compactData);
              }


              this.modal.delete();
            } else {
              kuls_alert(data.mesg);
            }
          },
          error: (request, status, error) => {
            kuls_alert(error.message);
          },
        });
  
  
      return true;
    }

  /*
   * @Overview cell 클릭 함수
   * @Parameter 클릭한 cell
   * @Function 클릭한 cell의 filed 값에 따라 토글 상태 변경 또는 팝업
   */
  cellClick(e, tgt) {
    switch (tgt.getField()) {
      case "OP_CD":
        popOper2( { WO_NO:"WO_NO",OP_SEQ:"OP_SEQ",OP_CD: "OP_CD",WO_SEQ: "WO_SEQ" }, tgt.getRow(), this.data.WO_NO );
        break;
    case "INSP_NAME":
      if(tgt.getData().OP_CD){
        popOperCheck2({
          INSP_NAME : "INSP_NAME",
          INSP_METH: "INSP_METH",
        },tgt.getRow(), tgt.getData().OP_CD);

      }else{
        kuls_alert("공정을 먼저 선택해주세요.")
      }
      break;
    case "OKNG_FLG":
      tgt.setValue(tgt.getValue() == "Y" ? "N" : "Y");

      if(tgt.getValue() === "Y"){
        tgt.getRow().update({SPEC_VAL:"",TOL_UPPER:"",TOL_LOWER:""});
      }else{
        tgt.getRow().getCell("SPEC_VAL").getElement().classList.add("tabulator-editable");
        tgt.getRow().getCell("TOL_UPPER").getElement().classList.add("tabulator-editable");
        tgt.getRow().getCell("TOL_LOWER").getElement().classList.add("tabulator-editable");
      }
      tgt.getElement().classList.add("tabulator-editable");
      break;
    }
  }

  getMainList(){
    let talert = window.setTimeout(() => {this.tbList.alert("Loading ...");}, 1000);
    ajax_json({
      url: this.ajaxUrl,
      data: { 
        mode: "",
        WO_NO: this.data.WO_NO
      },

      success: (data) => {
        if (data.code) {
          this.tbList.setData(data.data);
        } else {
          kuls_alert(data.mesg);
        }
      },
      error: (req, status, err) => {
        kuls_alert(err.message);
      },
      complete: () => {
        window.clearTimeout(talert);
        this.tbList.clearAlert();
      },
    });
  }

  integerMutator = function(value) {

    return value ? parseInt(value, 10) : null;
  };
  init(){

    const fields = [
      // { formatter: "rownum", title: "NO", width: 40 },
      // { field: "OP_SEQ", title: "공순", width: 40 },
      {formatter:"rownum", title:"NO", width:40},
      {field:"WO_NO",visible:false},
      {field:"OP_CD",title:"공정", width:40, cssClass: "editable-cell"},
      {field:"OP_SEQ",title:"공순", width:40},
      {field:"WO_SEQ", visible:false},
      {field:"INSP_ITEM", title:"검사항목",visible: false,width:20},
      {field:"INSP_NAME", title:"검사항목명", width:70,editor: "input",
        cellDblClick:function(e, tgt){
          popOperCheck({
            // WO_NO:Tb_order.tbList.getSelectedData()[0].WO_NO,
            ITEM_CD: Tb_order.tbList.getSelectedData()[0].ITEM_CD,
            INSP_NAME : "INSP_NAME",
            INSP_METH: "INSP_METH",
            INSP_ITEM : "INSP_ITEM",
          },tgt.getRow());
        },
        cssClass: "editable-cell"
      },
      {field:"INSP_METH", title:"검사방법", width:80,
        editor: "list", editorParams: {values: varsINSP_METH,},
        formatter: tb_common_funtions.formatterSelect, formatterParams: {values: varsINSP_METH,},
        cssClass: "user-list"
      },
      {field:"INSP_TOOL", title:"측정기", width:100,
        editor: "list", editorParams: {values: varsINSP_TOOL,},
        formatter: tb_common_funtions.formatterSelect, formatterParams: {values: varsINSP_TOOL,},
        cssClass: "user-list",
        hozAlign: "left",

      },
      { field: "OKNG_FLG", title: "OK/NG",  width: 70, cssClass: "tabulator-editable", formatter: tb_common_funtions.formatterToggleboxGreenIcon, formatterParams: { checkval: "Y" }, },
      // {field:"SPEC_UNIT", title:"단위",  width:100, editor:"list",editorParams: {values: varsUNIT,} ,formatter: tb_common_funtions.formatterSelect, formatterParams: {values: varsUNIT,}},
      {field:"SPEC_VAL",  title:"기준값</br>(㎜)", width:60,editor: "input",
        formatter: tb_custom_formatter.limitValue,
        formatterParams: {
          checkPoint : "OKNG_FLG",
          decimal: 3
        },
        editable:(cell) => {
          if(cell.getData().OKNG_FLG == 'Y'){
            // cell.setValue(0)
          }
          return cell.getData().OKNG_FLG !== 'Y';
        },
      },
      {field:"TOL_UPPER", title:"상한값</br>(㎛)", width:60,editor: "input",
        formatter: tb_custom_formatter.limitValue,
        formatterParams: {
          checkPoint : "OKNG_FLG"
        },
        editable:(cell) => {
          if(cell.getData().OKNG_FLG == 'Y'){

          }
          return cell.getData().OKNG_FLG !== 'Y';
        },
      },
      {field:"TOL_LOWER", title:"하한값</br>(㎛)", width:60,editor: "input",
        formatter: tb_custom_formatter.limitValue,
        formatterParams: {
          checkPoint : "OKNG_FLG"
        },
        editable:(cell) => {
          if(cell.getData().OKNG_FLG == 'Y'){

          }
          return cell.getData().OKNG_FLG !== 'Y';
        },
      },
      {field:"REMARK", title:"비고", editor:"input", width: 300,hozAlign:"left"},
      { field: "", title: "취소", width: 40,
        cellClick: (e, cell) => {
          cell.getRow().delete();
        },
        formatter: tb_custom_formatter.deleteIcon,
        formatterParams : {'icon':true}
      },
    ];
    const commonFieldData = {
      headerSort: true,
      vertAlign: "middle",
      hozAlign: "center",
      resizable: "header", //Resize 는 헤더에서만 가능
      headerHozAlign: "center", //헤더 정렬
      headerSortTristate: true, //데이터 정렬 => 정/역/초기화
    };

    // 모달 열기
    vnLoad("", "../../insp/reg_insp_qc/add_insp_pop.php", this.container, (loadHtml) => {
      this.modal = kuls_modal(loadHtml);
      this.container = document.querySelector("#popup_add_insp_container");
      this.table = this.container.querySelector('.hy-table');
      this.addBtn = this.container.querySelector('.add-btn');
      this.title = this.container.querySelector('.title');

      this.title.innerHTML = `생산오더: ${this.data.WO_NO}`;

      /*
       * @Overview tabulator 객체 생성
       * @Parameter 생성 위치(html class값)
       */
      this.tbList = new Tabulator(this.table, {
        layout: "fitColumns",
        data: [], //기본 데이터
        columns: fields, //컬럼 설정
        columnDefaults: commonFieldData,
        headerSortElement: "<i class='bi'></i>", //정렬 아이콘
        validationMode: "highlight",
      });
  
      /*
       * @Overview 테이블 만들어지면 데이터 불러오기
       * @Parameter 없음
       */
      this.tbList.on("tableBuilt", () => {
        // this.getMainList();
      });

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

      // 검사항목 추가
      ["click", "keypress"].forEach((evt) => {
        const addBtn = document.querySelector(".add-btn");
        addBtn.addEventListener(evt, () => {
          this.addRow();
        });
      });
      // 검사항목 저장
      ["click", "keypress"].forEach((evt) => {
        const saveBtn = document.querySelector(".save-btn");
        saveBtn.addEventListener(evt, () => {
          this.putData();
        });
      });

    });
    // 모달 종료

  }
}