// 설비고장등록 팝업
// 테이블 클래스가 정의 되어있다.
// params : 현장 실적 등록 팝업의 vue클래스, 데이터를 읽고 쓸때 필요한 필수 데이터

class Tb_Break_class {
  constructor(vueform, compactData) {
    this.ajaxUrl = "./reg_prod_result.ajax.php";

    this.vueform = vueform;
    this.formData = this.vueform.formData;
    this.compactData = compactData;
    this.getMode = this.compactData.getMode;
    this.putMode = this.compactData.putMode;

    this.container = document.querySelector(`#isFacltBreak`);
    this.table = this.container.querySelector(".hy-table");
    this.addBtn = this.container.querySelector(".add-btn") || "";
    this.removeBtn = this.container.querySelector(".remove-btn") || "";
  }

  getMainList() {
    this.FACLT_CD = document.querySelector("#FACLT_CD_FILT")?.value;

    if (!this.FACLT_CD && this.compactData["data"]["FACLT_CD"]) {
      document.querySelector("#FACLT_CD_FILT").value =
        this.compactData["data"]["FACLT_CD"];
      this.FACLT_CD = document.querySelector("#FACLT_CD_FILT")?.value;
    }

    let talert = window.setTimeout(() => {
      this.tbList.alert("Loading ...");
    }, 1000);
    ajax_json({
      url: this.ajaxUrl,
      data: {
        ...this.compactData["data"],
        mode: this.getMode,
        FACLT_CD: this.FACLT_CD,
      },
      success: (data) => {
        this.tbList.setData(data.data);
      },
      error: (req, status, err) => {
        kuls_alert(err.message);
      },
      complete: () => {
        window.clearTimeout(talert);
        this.tbList.clearAlert();
      },
    });
  }

  putData() {
    const contents = document.querySelector("#cause")?.value;
    const ERR_CD = document.querySelector("#ERR_CD")?.value;
    if (!this.FACLT_CD) {
      kuls_alert("설비를 입력해주세요.");
    } else {
      const postData = {
        mode: this.putMode,
        reqdata: JSON.stringify([
          {
            FACLT_CD: this.FACLT_CD,
            EMP_NO: this.formData.EMP_NO,
            CONTENT: contents,
            ERR_CD: ERR_CD,
          },
        ]),
      };

      ajax_json({
        url: this.ajaxUrl,
        data: postData,
        success: (data) => {
          if (data.code) {
            kuls_success("저장되었습니다.");

            // form data 재부팅
            // 좌측 폼에 들어갈 데이터 및 버튼 제어용 데이터 조회
            ajax_json({
              url: "./reg_prod_result.ajax.php",
              data: {
                mode: "getFormData",
                OP_SEQ: this.vueform.formData["OP_SEQ"],
                WO_NO: this.vueform.formData["WO_NO"],
                WO_SEQ: this.vueform.formData["WO_SEQ"],
              },
              success: (data) => {
                if (data.code) {
                  console.log(data.data[data.data.length - 1]);
                  const time = data.time;
                  this.vueform.formData = {
                    ...this.vueform.formData,
                    ...data.data[data.data.length - 1],

                    EMP_NO: this.vueform.formData.EMP_NO,
                    EMP_NM: this.vueform.formData.EMP_NM,

                    OPER_ST_TM: time[0]?.OPER_ST_TM,
                    OPER_ED_TM:
                      time[time.length - 1] &&
                      time[time.length - 1]["STOP_CD"] == "ED"
                        ? time[time.length - 1].OPER_ED_TM
                        : "",
                  };
                  console.log(this.vueform.formData);

                  this.getMainList();
                } else {
                  kuls_alert(data.mesg);
                }
              },
              error: (request, status, error) => {
                kuls_alert(error.message);
              },
            });
          } else {
            kuls_alert(data.mesg);
          }
        },
        error: (request, status, error) => {
          kuls_alert(error.message);
        },
        complete: () => {},
      });
    }
  }

  init() {
    const fields = [
      // { field: "SEQNO", formatter: "rownum", title: "순번", width: 40 },
      { field: "FACLT_CD", title: "설비코드",     width: 70,  },
      { field: "FACLT_NM", title: "설비명",       width: 100, },
      { field: "ERR_CD",   title: "설비고장코드", width: 80,  },
      { field: "CONTENT",  title: "고장신고사유", width: 400, hozAlign: "left" },
      { field: "EMP_NO",   title: "작업자",       width: 70,  },
      { field: "WRKDT",    title: "등록일시",     width: 80,  },
    ];
    const commonFieldData = {
      headerSort: true,
      vertAlign: "middle",
      hozAlign: "center",
      resizable: "header", //Resize 는 헤더에서만 가능
      headerHozAlign: "center", //헤더 정렬
      headerSortTristate: true, //데이터 정렬 => 정/역/초기화
    };
    this.tbList = new Tabulator(this.table, {
      layout: "fitColumns",
      data: [], //기본 데이터
      columns: fields, //컬럼 설정
      columnDefaults: commonFieldData,
      headerSortElement: "<i class='bi'></i>", //정렬 아이콘
    });

    /*
     * @Overview 테이블 만들어지면 데이터 불러오기
     * @Parameter 없음
     */
    this.tbList.on("tableBuilt", () => {
      this.getMainList();
    });

    this.addBtn.addEventListener("click", () => {
      this.putData && this.putData();
    });
  }
}
