/*
 * @Overview 파일 업로드
 */
class Tb_file_upload_class {
    constructor(container,clickData) {
        this.ajaxUrl = "/ksvc/insp/reg_insp_qc/reg_insp_qc.ajax.php";
        this.container = document.querySelector(container);

        // this.wo_no = clickData.WO_NO;
        // this.wo_seq = clickData.WO_SEQ;
        // this.op_cd = clickData.OP_CD;
        // this.insp_item = clickData.INSP_ITEM;
        // this.insp_name = clickData.INSP_NAME;

        this.clickData = clickData
        this.table = this.container.querySelector(".hy-table");
        this.addBtn = this.container.querySelector(".add-btn") || "";
        this.saveBtn= this.container.querySelector(".save-btn") || "";
        this.removeBtn = this.container.querySelector(".remove-btn") || "";
        // this.tbList ="";
        //console.log(this.container);
    }

    getMainList(){
        console.log(this.clickData);
        let _this = this;
        let talert = window.setTimeout(()=> { this.tbList.alert("Loading ...") }, 1000);
        ajax_json({
            url: this.ajaxUrl,
            data: {
                mode : "getInspFile",
                WO_NO: this.clickData.WO_NO,
                WO_SEQ: this.clickData.WO_SEQ,
                INSP_ITEM: this.clickData.INSP_ITEM,
                INSP_ITEM_NAME: this.clickData.INSP_ITEM_NAME,
            },
            success: (data) => {
                console.log(data.data);
                this.tbList.setData(data.data);
            },
            error: (req, status, err) => {
                kuls_alert(err.message);
            },
            complete: () => {
                window.clearTimeout(talert);
            },
        });


    }

    cellClick(e, tgt) {
        var editor = tgt.getColumn().getDefinition().editor;
        switch (tgt.getField()) {
            case "check":
                tgt.setValue(tgt.getValue() == "Y" ? "" : "Y");
                this.clearRemove(tgt.getRow())
                break;
            default:
                if (!editor) {
                    this.rowClick && this.rowClick(e, tgt.getRow());
                }
                break;
        }
    }
    /*
    * @Overview 삭제 취소 함수
    * @Parameter 삭제 행
    * @function  클릭시 삭제 취소 & STATUS를 공란으로 변경
    */
    clearRemove(tgt){
        if(tgt._row.data._STATUS_ == "D"){
            // console.log();
            tgt._row.data._STATUS_ = "";
            tgt._row.getElement().classList.remove("remove-row")
            // const selectedRows = this.tbList.getSelectedRows(); // 선택된 모든 행 가져오기
        }
    }
    downloadIcon = function(cell, formatterParams, onRendered){ //plain text value
        if(!cell.getRow().getData().FILE_NM){
            // kuls_alert("");
            return "<button class='reverse-btn disabled-btn' disabled>다운</button>";
        }
        return "<button class='reverse-btn'>다운</button>";

    };
    previewIcon = function(cell, formatterParams, onRendered){ //plain text value
        if(!cell.getRow().getData().FILE_NM){
            // kuls_alert("");
            return "<button class='reverse-btn disabled-btn' diabled>미리보기</button>";
        }
        // console.log(cell.getRow().getData().FILE_NM);
        return "<button class='reverse-btn'>미리보기</button>";

    };


    /*
   * @Overview 테이블 행 삭제 함수
   * @Parameter 없음
   * @function 선택된 모든 행 삭제
   */
    removeRow() {
        const selectedRows = this.tbList.getRows().filter(row=>{
            return row.getData().check ==="Y"
        });

        if(selectedRows.length > 0 ){

            kuls_confirm("삭제","하시겠습니까?", ()=>{
                // 선택된 각 행 삭제
                selectedRows.forEach((row) => {
                    // STAUS D로 바꾸기
                    row.getData()._STATUS_ = row.getData()._STATUS_=="I"?null:"D";

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

                });
            })
        }else{
            kuls_alert("삭제할 행을 선택해주세요.")
        }
    }

    cellEdited(cell) {
        cell.getData()._STATUS_ = cell.getData()._STATUS_ || "U";
    }
    putTempFile(file){
        let _this = this;


        let formData = new FormData();
        formData.append('upfile', file);
        formData.append('mode', "putTempFile");
        let talert = window.setTimeout(()=> { this.tbList.alert("Loading ...") }, 1000);
        jQuery.ajax({
            url: _this.ajaxUrl,
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: (data)=>{
                if(data.code !== "0") {
                    // kuls_success("적용 되었습니다.");

                    let fdata = JSON.parse(data).data;

                    let FILE_NM   = fdata['file_name'];
                    let TMP_NAME  = fdata['tmp_name'];
                    let FILE_SIZE = fdata['file_size'];
                    let FILE_TYPE = fdata['file_type'];

                    _this.tbList.addRow({
                        _STATUS_:'I',
                        WO_NO : _this.clickData.WO_NO,
                        WO_SEQ :_this.clickData.WO_SEQ,
                        OP_CD :_this.clickData.OP_CD,
                        INSP_NAME :_this.clickData.INSP_NAME,
                        INSP_ITEM :_this.clickData.INSP_ITEM,
                        FILE_NM,
                        TMP_NAME,
                        FILE_SIZE,
                        FILE_TYPE,
                        gubun:'temp',
                    });

                }else{
                    // this.tbList.getRows().forEach(row =>{
                    //   if(data.data.includes(row.getData()['BIZ_AREA_CD'])){
                    //     row.updata({_STATUS_:"U"});
                    //   }
                    // });
                    kuls_alert(data.msg);
                }
            },
            error: (req, stat, err) => {
                kuls_alert(err.message);
            },
            complete: () => {
                window.clearTimeout(talert);

                // this.tbList.clearAlert();
                // this.setFilter();
            },
        });
        return true;


    }
    putFile() {
        let _this = this;
        if (this.tbList.getData().filter(row => row._STATUS_).length == 0) {
            this.getMainList();
            return false;
        }
        const blankObj = [];
        const reqData = [];

        this.tbList.getRows().forEach(row => {

            if (row.getData()['_STATUS_']) {
                if (Object.keys(row._row.data).filter(key => key !== '_STATUS_' && key !== 'USE_FLG').every(key => {

                    const value = row._row.data[key];
                    return (value === undefined || value === '');
                })) {
                    blankObj.push(row);
                } else {
                    reqData.push(row.getData());
                }
            }
        })


        const postdata = reqData.length == 0 ? false : {
            'mode': 'putInspFile',
            'reqdata': JSON.stringify(reqData),
        };
        if (blankObj.length !== 0) {
            kuls_confirm("비어있는 행을 무시하고 진행하시겠습니까?", "", () => {
                ajax_json({
                    url: this.ajaxUrl,
                    data: postdata,
                    success: (data) => {
                        if (data.code) {
                            kuls_success("저장되었습니다.");
                            this.getMainList();
                        } else {
                            kuls_alert(data.mesg);
                        }
                    },
                    error: function (request, status, error) {
                        kuls_alert(error.message);
                    },
                    complete: function () {
                    }
                });

            }, () => {
                blankObj.forEach(row => {
                    row.getElement().classList.add("blank-row")
                })
            })
        } else {
            ajax_json({
                url: this.ajaxUrl,
                data: postdata,
                success: (data) => {
                    if (data.code) {
                        kuls_success("저장되었습니다.");
                        this.getMainList();
                    } else {
                        kuls_alert(data.mesg);
                    }
                },
                error: function (request, status, error) {
                    kuls_alert(error.message);
                },
                complete: function () {
                }
            });

            return true;
        }
    }

    getFileUrl(WO_NO, WO_SEQ, SID,NAME,down){
        let urlStr = '/include/getFile.php'+"?gubun=insp&WO_NO="
            + WO_NO +
            "&WO_SEQ="+ WO_SEQ +
            "&SID="+SID+
            "&name=" + NAME
        if(down == true){
            location.href = urlStr;
        }
        return urlStr;
    }
    init_insp(){
        let _this = this;
        const fields = [

            { field:"check", title: "선택", width: 50, headerSort: false,
                formatter: tb_common_funtions.formatterCheckboxIcon,
                formatterParams: { checkval: "Y" },
            },
            { formatter: "rownum",  title: "NO", width: 50 },
            { field:"INSP_ITEM",  title: "검사항목", width: 60, visible:false},
            { field:"INSP_NAME",  title: "검사항목명", width: 60 },
            { field:"REMARK",  title: "비고", width: 100,editor: "input" },
            { field:"WO_NO",  title: "생산오더", width: 100 },
            // { field: "DOWNLOAD",    title: "다운로드", width: 100, formatter: this.downloadIcon,
            //   cellClick:function(e, cell){
            //     console.log(cell.getRow().getData())
            //   }
            // },
            { field: "DOWNLOAD",    title: "다운로드", width: 100, formatter: this.downloadIcon,
                cellClick:function(e, cell){
                    if(cell.getRow().getData().FILE_ID === undefined){
                        kuls_alert("저장 후 사용 가능합니다")
                        return false;
                    }
                    _this.getFileUrl(
                      cell.getRow().getData().WO_NO,
                      cell.getRow().getData().WO_SEQ,
                      cell.getRow().getData().FILE_ID,
                      cell.getRow().getData().FILE_NM,
                      true
                    );
                    //   location.href = '/include/getFile.php'+"?gubun=draw&nid="
                    //                 + cell.getRow().getData().DRAW_NO
                    //                 + "&sid="+cell.getRow().getData().SID
                    //                 + "&file_id="+cell.getRow().getData().FILE_ID
                }
            },
            // { field: "DRAW_VER",    title: "버전",    width: 100 },
            // { field: "DRAW_NO",     title: "파일이름", width: 150, editor: "input" ,editable:(cell)=>{ let val = cell.getData(); return val._STATUS_ === 'I' },}, //file의 nid이기도 함
            { field: "FILE_NM",     title: "파일명",  width: 150 },
            { field: "SID",                       visible:false},
            { field: "FILE_ID",                   visible:false},
            { field: "MAKE_TM",     title: "등록일", width: 100},
            { field: "MAKE_USER_ID",title: "등록자", width: 100 },
            { field: "preview",     title: "미리보기", width: 80,formatter:this.previewIcon,
                cellClick:function(e,cell){
                    if(!cell.getRow().getData().FILE_ID){
                        kuls_alert("저장 후 사용 가능합니다")
                        return false;
                    }
                    pop_filedown(
                        _this.getFileUrl(
                            cell.getRow().getData().WO_NO,
                            cell.getRow().getData().WO_SEQ,
                            cell.getRow().getData().FILE_ID,
                        ), cell.getRow().getData().FILE_NM.split(".").pop()
                    );
                }
            },
        ];
        const commonFieldData = {
            headerSort: true,
            vertAlign: "middle",
            hozAlign: "center",
            resizable: "header", //Resize 는 헤더에서만 가능
            headerHozAlign: "center", //헤더 정렬
            headerSortTristate: true, //데이터 정렬 => 정/역/초기화
        };

        /*
         * @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 유효성 검사메세지 띄우기
         * @Parameter cell, 입력값, validators
         */
        this.tbList.on("validationFailed", (cell, value, validators) => {
            cell.setValue("");
            let errMsg = "";
            switch (validators[0].type) {
                case "alphanumeric":
                    errMsg = " 필드는 특수문자를 입력할 수 없습니다.";
                    break;
                case "numeric":
                    errMsg = " 필드는 숫자만 입력할 수 있습니다.";
                    break;
                default:
                    errMsg = " 필드는 " + validators[0].parameters;
                    break;
            }

            kuls_warning(cell.getColumn().getDefinition().title + errMsg);
        });

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

        /*
         * @Overview cell 수정 함수
         * @Parameter cell
         * @Function status u로 바꿀것
         */
        this.tbList.on("cellEdited", (cell) => {
            this.cellEdited && this.cellEdited(cell);
        });

        // 추가
        ["click", "keypress"].forEach((evt) => {
          this.addBtn.addEventListener(evt, () => {
              uploadFile();
            // this.addRow && this.addRow();
          });
        });
        // 저장
        ["click", "keypress"].forEach((evt) => {
            this.saveBtn.addEventListener(evt, () => {
                this.putFile();
                // this.addRow && this.addRow();
            });
        });
        // 삭제
        ["click", "keypress"].forEach((evt) => {
            this.removeBtn.addEventListener(evt, () => {
                // 삭제 함수
                this.removeRow && this.removeRow();
            });
        });
        document.getElementById('file_input').addEventListener('change', function() {

            // 파일 정보 가져오기
            let file = this.files[0];
            console.log(this.files);
            // const tempClass = new Tb_file_upload_class()
            _this.putTempFile(file);

        });
        document.getElementById('WO_NO_T').innerText= this.clickData.WO_NO;
        document.getElementById('OP_CD_T').innerText= this.clickData.OP_CD;
        document.getElementById('INSP_NAME_T').innerText= this.clickData.INSP_NAME;

    }

}

const uploadFile=()=> {
    // (Tb_item.tbList.getSelectedData()[0]?.ITEM_CD);
    // if(!Tb_item.tbList.getSelectedData()[0]?.ITEM_CD){
    //     kuls_alert("품목코드를 클릭해주세요");
    //     return false;
    // }
    document.getElementById('file_input').click();
}

