class Tb_pop_class {
    constructor(container,modal) {
        this.ajaxUrl = "./reg_order.ajax.php";
        this.tbList = "";
        this.itemData = "";
        this.fileData = "";
        this.modal = modal;
        this.container = document.querySelector(container);
        this.table = this.container;
        this.lastNum = 0;
    }
    addRow() {
        this.tbList.addRow();
    }






    getExcel2(data) {


        let sheet_title = "생산오더등록";
        let file_name = "생산오더등록";

        const work_Book = new ExcelJS.Workbook();  // ExcelJS 라이브러리로 새 워크북 생성
        const work_Sheet = work_Book.addWorksheet(sheet_title);   // 새 워크시트 추가

        const all_border = {
            top: { style: "thin", color: { argb: "FF000000" } },
            left: { style: "thin", color: { argb: "FF000000" } },
            bottom: { style: "thin", color: { argb: "FF000000" } },
            right: { style: "thin", color: { argb: "FF000000" } },
        };
        const field_css = {
            yellow: {
                border: all_border,
                font: { color: { argb: "FF9C5700" }, bold: true },
                alignment: { vertical: "middle", horizontal: "center" },
                fill: {
                    type: "pattern",
                    pattern: "solid",
                    fgColor: { argb: "FFFFEB9C" },
                },
            },
            green: {
                border: all_border,
                font: { color: { argb: "FF006100" }, bold: true },
                alignment: { vertical: "middle", horizontal: "center" },
                fill: {
                    type: "pattern",
                    pattern: "solid",
                    fgColor: { argb: "FFC6EFCE" },
                },
            },
            red: {
                border: all_border,
                font: { color: { argb: "FF9C0006" }, bold: true },
                alignment: { vertical: "middle", horizontal: "center" },
                fill: {
                    type: "pattern",
                    pattern: "solid",
                    fgColor: { argb: "FFFFC7CE" },
                },

            },
            blue: {
                border: all_border,
                font: { font: { size: 11 }, color: { argb: "0E3979" }, bold: true },
                alignment: { vertical: "middle", horizontal: "center" },
                fill: {
                    type: "pattern",
                    pattern: "solid",
                    fgColor: { argb: "EAEFF3" },

                }
            },
            title: {
                font: { size: 15, bold: true },
                alignment: { vertical: "middle", horizontal: "center" },
            },
            box: {
                border: all_border,
                alignment: { vertical: "middle", horizontal: "center" },
                font: { size: 11 },

            },


        };

        // // 첫 번째 행 설정, 높이와 제목 설정

        // let ws_row1 = work_Sheet.getRow(1);
        // ws_row1.height = 32;
        // ws_row1.getCell(1).value = "검사항목";
        // ws_row1.getCell(1).style = field_css.title
        // work_Sheet.mergeCells('A1:E1');

        // 코드 가변처리, 항목추가시 편의성 개선
        let headers = [
            { name: "생산오더", width: 15 },
            { name: "작업순서", width: 12 },
            { name: "품목코드", width: 15 },
            { name: "거래처코드", width: 15 },
            { name: "릴리즈일", width: 15 },
            { name: "납기일", width: 15 },
            { name: "지시수량", width: 15 },
            //{ name: "검사번호", width: 15 },
            { name: "검사시료수", width: 15 },
            { name: "비고", width: 15 },
        ];

        let ws_row = work_Sheet.getRow(1);
        ws_row.height = 25;

        headers.forEach((header, index) => {
            let cell = ws_row.getCell(index + 1);
            cell.style = field_css.blue;
            cell.value = header.name;
        });

        work_Sheet.columns = headers.map(header => ({ width: header.width }));


        /*
          let ws_row = work_Sheet.getRow(1);
          ws_row.height = 25;
          // ws_row.getCell(1).style = field_css.blue;
          // ws_row.getCell(1).value = "NO.";
          ws_row.getCell(1).style = field_css.blue;
          ws_row.getCell(1).value = "품목";
          ws_row.getCell(2).style = field_css.blue;
          ws_row.getCell(2).value = "품목(명)";
          ws_row.getCell(3).style = field_css.blue;
          ws_row.getCell(3).value = "공순";
          ws_row.getCell(4).style = field_css.blue;
          ws_row.getCell(4).value = "공정코드";
          ws_row.getCell(5).style = field_css.blue;
          ws_row.getCell(5).value = "준비시간";
          ws_row.getCell(6).style = field_css.blue;
          ws_row.getCell(6).value = "공정시간";
          ws_row.getCell(7).style = field_css.blue;
          ws_row.getCell(7).value = "공정단가";
          ws_row.getCell(8).style = field_css.blue;
          ws_row.getCell(8).value = "검사명";
          ws_row.getCell(9).style = field_css.blue;
          ws_row.getCell(9).value = "측정기";
          ws_row.getCell(10).style = field_css.blue;
          ws_row.getCell(10).value = "검사방법";
          ws_row.getCell(11).style = field_css.blue;
          ws_row.getCell(11).value = "기준값(㎜)";
          ws_row.getCell(12).style = field_css.blue;
          ws_row.getCell(12).value = "상한치(㎛)";
          ws_row.getCell(13).style = field_css.blue;
          ws_row.getCell(13).value = "하한치(㎛)";
          work_Sheet.columns = [
            { width: 15 },
            { width: 30 },
            { width: 15 },
            { width: 15 },
            { width: 15 },

            { width: 15 },
            { width: 15 },
            { width: 15 },
            { width: 15 },
            { width: 15 },

            { width: 15 },
            { width: 15 },
            { width: 15 },
          ];
          */




        // 파일 생성 및 다운로드 부분

        work_Book.xlsx.writeBuffer().then((data) => {
            const blob = new Blob([data], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            });
            const url = window.URL.createObjectURL(blob);
            const anchor = document.createElement("a");
            anchor.href = url;
            anchor.download = file_name;
            anchor.click();
            window.URL.revokeObjectURL(url);
        });
    }




    uploadExcel(){
        let _this = this;
        let postdata = {
            mode : 'uploadData',
            reqdata : JSON.stringify(this.tbList.getData())

        }
        ajax_json({
            url: this.ajaxUrl,
            data: postdata,
            success: function (data) {
                if (data.code) {
                    _this.tbList.setData(data.data);
                    Tb_order.getMainList("getOrderList");
                    kuls_success("저장되었습니다.");
                }else if(data.code == 0){

                    _this.tbList.setData(data.mesg);

                }
            },
            error: function (request, status, error) {
                kuls_alert(error.message);
            },
            complete: function () {
            }
        });
    }
    excelDateToJSDate(excelDate) {
        let formatMethod = "";
        let regex = /^\d{4}\.\d{2}\.\d{2}$/;
        console.log(excelDate);
        let excelEpoch = new Date(1900, 0, 1);
        let jsDate = new Date(excelEpoch.getTime() + (excelDate - 2) * 24 * 60 * 60 * 1000);
        if(regex.test(excelDate)){
            formatMethod = this.convertDateFormat(excelDate)

        }else{
            formatMethod = this.formatDateToYYYYMMDD(jsDate);
        }

        return formatMethod
    }

    formatDateToYYYYMMDD(date) {
        let year = date.getFullYear();
        let month = (date.getMonth() + 1).toString().padStart(2, '0'); // 월은 0부터 시작하므로 1을 더해줌
        let day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    convertDateFormat(dateString) {
        // 날짜를 yyyy-mm-dd 형식으로 변환
        const parts = dateString.split('.');
        const year = parts[0];
        const month = parts[1];
        const day = parts[2];

        return `${year}-${month}-${day}`;
    }

    cellClick(e, tgt) {
        let editor = tgt.getColumn().getDefinition().editor;
        // // 체크박스 클릭
        switch (tgt.getField()) {
            case "check":
                tgt.setValue(tgt.getValue() == "Y" ? "" : "Y");
                break;
            case "OKNG_FLG":
                tgt.setValue(tgt.getValue() == "Y" ? "" : "Y");
                this.clearRemove(tgt.getRow())
                break;
            default:
                if (!editor) {
                    this.rowClick && this.rowClick(e, tgt.getRow());
                }
                break;
        }
    }
    /*
   * @Overview 최초 실행 함수
   * @Parameter 없음
   */
    init() {
        let _this = this;
        // field 정의
        const fields = [
            // {formatter:"rownum", title:"NO", width:40},
            // {field:"ORD_STATUS", title:"상태", width:50, editable:false, formatter: tb_common_funtions.formatterSelect, formatterParams: {values: varsWO_STATUS,}},
            {field:"WO_NO", title:"생산오더", width:70,
                editor: "input",
                // formatter: tb_custom_formatter.pkCode,
                // formatterParams : {tableClass: this},
            },
            // {field:"ORD_TYPE", title:"지시 구분", width:70,editable:false, editorParams: {values: varsORD_TYPE,}, formatter: tb_common_funtions.formatterSelect, formatterParams: {values: varsORD_TYPE,}},
            {field:"PROC_SEQ", title:"작업<br>순서", width:50,hozAlign:"center",editor: "input" },
            // {field:"ITEM_CD", title:"품목", width:80 ,editor:tb_custom_editor.pop},
            {field:"ITEM_CD", title:"품목코드", width:300,hozAlign:"left", editor:"input" },
            // {field:"BP_CD", title:"거래처", visible: false,},
            {field:"BP_CD", title:"거래처코드", width:170 , editor:"input" , hozAlign:"left"},
            {field:"ORD_DT", title:"릴리즈일", width:80 ,
                editor:'date',
                editorParams: {max:'9999-12-31'},
                formatter:"datetime",
                formatterParams:{
                    inputFormat:"yyyy-MM-dd",
                    outputFormat:"yyyy.MM.dd",
                },
                cssClass:"editable-cell", },
            {field:"DLVY_REQ_DT", title:"납기일", width:80 ,
                editor:'date',
                editorParams: {max:'9999-12-31'},
                formatter:"datetime",
                formatterParams:{
                    inputFormat:"yyyy-MM-dd",
                    outputFormat:"yyyy.MM.dd",
                },
                cssClass:"editable-cell",},
            {field:"ORD_QTY", title:"지시수량", width:60 ,hozAlign:"right",editor: "input", cssClass:"editable-cell",},
            {field:"INSP_SAMPL_QTY", title:"검사<br>시료수", width:60 ,hozAlign:"right" ,editor: "input",},
            {field:'REMARK', title:'비고', width:300 ,editor: "input", hozAlign:"left"},
            {field:'RS_MSG', title:'업로드여부', width:300 ,editor: "input", hozAlign:"left"}
        ];
        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>"
        });

        // 데이터 불러오기
        this.tbList.on("tableBuilt", () => {
            // this.getMainList("getOrderList","order_date_st", "order_date_ed", "WO_NO", "ITEM_CD","ITEM_NM", "BP_CD", "BP_NM","WO_STATUS", "ITEM_GRP");
        });
        // cell 클릭 시에
        this.tbList.on("cellClick", (e, tgt) => {
            this.cellClick && this.cellClick(e, tgt);
        });
        // cell 수정 시에
        this.tbList.on("cellEdited", (cell) => {
            // this.cellEdited && this.cellEdited(cell);
        });

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

        // 저장
        ["click", "keypress"].forEach((evt) => {
            const saveBtn = document.querySelector(".save-btn");
            saveBtn.addEventListener(evt, () => {
                _this.uploadExcel()
                // this.putData();
                // Tb_process.putData();
                // Tb_check.putData();
            });
        });
        document.getElementById('excel_down').addEventListener('click', function (e) {
            _this.getExcel2();
        });

        document.getElementById('excel_up').addEventListener('click', function (e) {
            const inputBtn = document.querySelector("#fileInput");
            inputBtn.click();
        });
        document.getElementById('fileInput').addEventListener('change', function (e) {

            let file = e.target.files[0];

            if (!file) {
                return;
            }
            let reader = new FileReader();
            reader.onload = (e) => {

                let data = new Uint8Array(e.target.result);
                let workbook = "";
                workbook = XLSX.read(data, { type: 'array' });

                workbook.SheetNames.forEach((sheetName) => {
                    let rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { header:1 });

                    rows.slice(1).forEach((row,index) => {
                        if(row.length !== 0){
                            let rowToAdd = {
                                WO_NO          : row[0],
                                PROC_SEQ       : row[1],
                                ITEM_CD        : row[2],
                                BP_CD          : row[3],
                                ORD_DT         : _this.excelDateToJSDate(row[4]),
                                DLVY_REQ_DT    : _this.excelDateToJSDate(row[5]),
                                ORD_QTY        : row[6],
                                INSP_SAMPL_QTY : row[7],
                                REMARK         : row[8],
                                _STATUS_    : "I"
                            };
                            console.log(rowToAdd);
                            _this.tbList.addRow(rowToAdd);
                        }
                    });

                });
                document.querySelector("#fileInput").value = ""
            };
            reader.readAsArrayBuffer(file)
        });
    };
}