//데이터, 테이블, 상단 버튼
let _listTable            = null;
let fltrCheck2            = null;
let fltrCheck1            = null;
let fltrLwstSped          = null;
let fltrHghsSped          = null;
let trafMinNum            = null;
let trafMaxNum            = null;
let fifoCheck             = null;
let fifoTable             = null;
let weightCheck           = null;
let weightTable           = null;
let adjsNoCheck           = null;
let adjsCheck             = null;
let adjsPttr              = null;
let adjsWghtAvrgPre3Cycl  = null;
let adjsWghtAvrgPre2Cycl  = null;
let adjsWghtAvrgPre1Cycl  = null;
let adjs15mPtrnAplyYn     = null;
let adjsShtrMissDecsCycl  = null;
let smthNoCheck           = null;
let smthLimitCheck        = null;
let minSpedNum            = null;
let maxSpedNum            = null;
let smthFiftAvgCheck      = null;
let smthWghtAvrgPre2Cycl  = null;
let smthWghtAvrgPre1Cycl  = null;
let smthWghtAvrgPrst      = null;
let allActiveBtn          = null;
let selectActiveBtn       = null;
let paramId               = null;
let paramName             = null;
let fifoData              = [];
let fltrChecker           = [];
let fusnChecker           = [];
let adjsChecker           = [];
let smthChecker           = [];
let fusnData              = [];
let _selectedLink         = null;
let smthDefBtn            = null;
let fltrDefBtn            = null;
let adjsDefBtn            = null;
let fusnMaxCheck          = null;
let addBtn                = null; 
let delBtn                = null; 
let editBtn               = null; 
let saveBtn               = null; 
let cancelBtn             = null; 
let _fltrCd               = null;
let _smthCd               = null;
let _adjsCd               = null;
let _fusnCd               = null;
let searchBtn             = null;
const _apiUri             = '/api/database/link-para-stup';
const fusnUri             = '/api/database/clct-syst-stup';
const clctSystStupLinkUri = '/api/database/link';
let fusnListData = [];

$(()=>{
    //상단 조회 버튼
    searchBtn = new dxBtn($(".search-button"), '조회', 'refresh', 'outlined');
    searchBtn.onClick(refreshPage);
    const closeBtn = new dxBtn($(".close-button"), '닫기', 'close', 'outlined');
    closeBtn.onClick(()=>window.close());
    
    //파라미터 설정
    paramId     = new dxTxt($('.param-id'), 'param-id', 40, '파라미터 ID', 150, 30, null, true);
    paramName   = new dxTxt($('.param-name'), 'param-name', 40, '파라미터 명칭', 400, 30);

    //사용안함 체크
    fltrCheck1   = new dxCheck($('.fltr-check1'), '사용안함', false, false, "FMT0");
    fltrCheck2   = new dxCheck($('.fltr-check2'), '범위값 사용', true, false, "FMT1");
    trafMinNum   = new dxNumber($(".fltr_min_tfvl"), 'outlined', 100, 25, 0, 999999, true, 1, 'fltr_min_tfvl');
    trafMaxNum   = new dxNumber($(".fltr_max_tfvl"), 'outlined', 100, 25, 0, 999999, true, 200, 'fltr_max_tfvl');
    fltrLwstSped = new dxNumber($(".fltr_lwst_sped"), 'outlined', 100, 25, 0, 999, true, 1, 'fltr_lwst_sped');
    fltrHghsSped = new dxNumber($(".fltr_hghs_sped"), 'outlined', 100, 25, 0, 999, true, 200, 'fltr_hghs_sped');
    fltrDefBtn   = new dxBtn($('.fltr-defaul-value-btn'), '초기값', 'refresh', 'outlined', 100, 30);
    
    fltrCheck1.onValueChanged(fltrCheck1VC);
    fltrCheck2.onValueChanged(fltrCheck2VC);
    fltrDefBtn.onClick(fltrDefBtnClick);
    
    //보정 파라미터
    //체크 박스 꺼짐 방지
    $(".adjs-check").on('click',()=>{
        if(adjsCheck.getValue())return false;
    });
    $(".adjs-no-check").on('click',()=>{
        if(adjsNoCheck.getValue())return false;
    })
    $(".adjs-pttr").on('click',()=>{
        if(adjsPttr.getValue())return false;
    })
    
    //3주기 평균
    adjsWghtAvrgPre3Cycl = new dxNumber($(".adjs_wght_avrg_pre_3cycl"), 'outlined', 75, 25, 0, 100, true, 20, 'adjs_wght_avrg_pre_3cycl', '##0');
    //2주기 평균
    adjsWghtAvrgPre2Cycl = new dxNumber($(".adjs_wght_avrg_pre_2cycl"), 'outlined', 75, 25, 0, 100, true, 30, 'adjs_wght_avrg_pre_2cycl', '##0');
    //1주기 평균
    adjsWghtAvrgPre1Cycl = new dxNumber($(".adjs_wght_avrg_pre_1cycl"), 'outlined', 75, 25, 0, 100, true, 50, 'adjs_wght_avrg_pre_1cycl', '##0');
    //단기 결측 판단 주기
    adjsShtrMissDecsCycl = new dxNumber($(".adjs_shtr_miss_decs_cycl"), 'outlined', 75, 25, 0, 99, true, 3, 'adjs_shtr_miss_decs_cycl');
    //사용안함 체크
    adjsNoCheck = new dxCheck($('.adjs-no-check'), '사용안함', false, false, "MCA0");
    //단기(15분이동평균)/장기(패턴) 체크
    adjsCheck           = new dxCheck($(".adjs-check"), '단기(15분이동평균)/장기(패턴)', true, false, "MCA1");
    adjsPttr            = new dxCheck($(".adjs-pttr"), '패턴적용', false, false, "MCA2");
    adjs15mPtrnAplyYn   = new dxCheck($(".adjs_ptrn_15m_aply_yn"), '15분 패턴 추가적용(장기 결측시)', false);
    adjsDefBtn          = new dxBtn($('.adjs-defaul-value-btn'), '초기값', 'refresh', 'outlined', 100, 30);
    
    adjsNoCheck.onValueChanged(adjsNoCheckVC);
    adjsCheck.onValueChanged(adjsCheckVC);
    adjsPttr.onValueChanged(adjsPttrVC)
    adjsDefBtn.onClick(adjsDefBtnClick);


    //퓨전 파라미터
    $(".weight-check").on('click',()=>{
        if(weightCheck.getValue())return false;
    });
    $(".fifo-check").on('click',()=>{
        if(fifoCheck.getValue())return false;
    })
    $(".fusn-max-check").on('click',()=>{
        if(fusnMaxCheck.getValue())return false;
    })
   
    //우선순위 체크
    fifoCheck = new dxCheck($('.fifo-check'), '우선순위', true, false, "FST1");
    //우선순위 테이블
    fifoTable = $(".fifo-list").width('100%').height("100%").dxDataGrid({
        dataSource              : [],
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'clct_syst_cd',
        selection: {
            mode : 'single',
        },
        headerFilter: {
            visible : false,
        },
        editing:{
            mode: 'cell',
            allowUpdating: true,
        },
        scrolling: {
            mode : 'virtual',
        },
        columns:[
            {   
                dataField    : "clct_syst_desc",
                caption      : "수집원",
                alignment    : "center",
                allowEditing : false,
                // sortIndex    : 0,
                // sortOrder    : "asc",
                cssClass     : "noPadding",
                validationRules: [{ type: 'required' }],
                cellTemplate(c,e){
                    let result = nullChecker(e.displayValue);
                    return  $('<div style="text-align: left;">'+result+'</div>')
                }
            },
            {
                dataField :"fusn_prrt",
                caption   :"우선순위",
                alignment :"center",
                cssClass  : "noPadding",
                lookup    :{
                    dataSource  : [],
                    displayExpr : 'fusn_prrt',
                    valueExpr   : 'fusn_prrt',
                },
                cellTemplate(c,e){
                    if (nullChecker(e.data.fusn_prrt) === "" ){
                        return c.text("사용안함")
                    }
                    return c.text(e.data.fusn_prrt);
                }
            },]
    }).dxDataGrid("instance");

    //가중치 체크
    weightCheck = new dxCheck($('.weight-check'), '가중치', false, false, "FST2");
    //가중치 테이블
    weightTable = $(".weight-list").width('100%').height("100%").dxDataGrid({
        dataSource              : [],
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        disabled                : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'clct_syst_cd',
        headerFilter: {
            visible : false,
        },
        editing:{
            mode: 'cell',
            allowUpdating: true,
        },
        selection: {
            mode : 'single',
        },
        scrolling: {
            mode : 'virtual',
        },
        disabled : true,
        columns:[
            {   
                dataField    : "clct_syst_desc",
                caption      : "수집원",
                alignment    : "center",
                allowEditing : false,
                cssClass     : "noPadding",
                cellTemplate(c,e){
                    alignTemplate(c, e,'left');
                }
            },
            {
                dataField    : "fusn_wght",
                caption      : "가중치",
                alignment    : "center",
                cssClass     : "noPadding",
                editorOptions:{
                    dataType        : "number",
                    showSpinButtons : true,
                    format          : '##0',
                    min             : 0,
                    max             : 100,
                },
                cellTemplate(c,e){
                    if (nullChecker(e.displayValue) === "") {
                        c.text(10);
                    }
                    else {
                        c.text(e.displayValue);
                    }
                }
                
            },]
    }).dxDataGrid("instance");
    
    //최대값 적용 코드 확인
    fusnMaxCheck = new dxCheck($('.fusn-max-check'), '최대값 적용', false, false, "FST3")
    
    fusnMaxCheck.onValueChanged(fusnMaxCheckVC);
    fifoCheck.onValueChanged(fifoCheckVC);
    weightCheck.onValueChanged(weightCheckVC);
   
    //평활화 파라미터
    //체크박스 꺼짐 방지
    $(".smth-fift-avg-check").on("click",()=>{
        if(smthFiftAvgCheck.getValue())return false
    });
    $(".smth-no-check").on("click",()=>{
        if(smthNoCheck.getValue())return false
    });
    $(".smth-limit-check").on("click",()=>{
        if(smthLimitCheck.getValue())return false
    });
      
    smthNoCheck          = new dxCheck($(".smth-no-check"), '사용안함', false, false, "SMT0");
    smthLimitCheck       = new dxCheck($(".smth-limit-check"), '편차제한(최저-최대)', true, false, "SMT1");
    smthFiftAvgCheck     = new dxCheck($(".smth-fift-avg-check"), '15분 이동평균(전체합=100)', false, false, "SMT2");
    minSpedNum           = new dxNumber($(".smth_lwst_sped_fctr"), 'outlined', 75, 25, 0.00, 9.99, true, 0.20, 'smth_lwst_sped_fctr', '#0.##00');
    maxSpedNum           = new dxNumber($(".smth_hghs_sped_fctr"), 'outlined', 75, 25, 0.00, 9.99, true, 2.00, 'smth_hghs_sped_fctr', '#0.##00');
    smthWghtAvrgPre2Cycl = new dxNumber($(".smth_wght_avrg_pre_2cycl"), 'outlined', 75, 25, 0, 100, true, 20, 'smth_wght_avrg_pre_2cycl', '##0', true);
    smthWghtAvrgPre1Cycl = new dxNumber($(".smth_wght_avrg_pre_1cycl"), 'outlined', 75, 25, 0, 100, true, 30, 'smth_wght_avrg_pre_1cycl', '##0', true);
    smthWghtAvrgPrst     = new dxNumber($(".smth_wght_avrg_prst"), 'outlined', 75, 25, 0, 100, true, 50, 'smth_wght_avrg_prst', '##0', true);
    smthDefBtn           = new dxBtn($('.smth-defaul-value-btn'), '초기값', 'refresh', 'outlined', 100, 30);
    
    smthNoCheck.onValueChanged(smthNoCheckVC);
    smthLimitCheck.onValueChanged(smthLimitCheckVC);
    smthFiftAvgCheck.onValueChanged(smthFiftAvgCheckVC);
    smthDefBtn.onClick(smthDefBtnClick);
    
    //하단 버튼 
    addBtn    = new dxBtn($('.add-btn'), '추가', 'plus', 'outlined');
    delBtn    = new dxBtn($('.del-btn'), '삭제', 'minus', 'outlined', null, null, true, false);
    editBtn   = new dxBtn($('.edit-btn'), '수정', 'edit', 'outlined', null, null, true);
    saveBtn   = new dxBtn($('.save-btn'), '저장', 'save', 'outlined', null, null, null, false);
    cancelBtn = new dxBtn($('.cancel-btn'), '취소', 'plus', 'outlined', null, null, null, false);
    
    addBtn.onClick(addBtnClick);
    delBtn.onClick(delBtnClick);
    editBtn.onClick(editBtnClick);
    saveBtn.onClick(saveBtnClick);
    cancelBtn.onClick(cancelBtnClick);

    selectActiveBtn = $(".select-active-btn").dxButton({
        stylingMode:'outlined',
        icon : 'check',
        text:'등록',
        disabled    : true,
        onClick(){
            let updateData = updateSettingData();
            if (updateData) {

                if(_listTable.getSelectedRowsData().length <= 0){
                    alertWarning("선택된 데이터가 없습니다. 파리미터 정보를 설정할 데이터를 선택해주세요");
                    return false;
                }
                
                confirmMessage("선택된 구간에 대하여 파라미터 정보를 설정합니다.<br>선택한 구간에 대하여 파라미터 정보를 적용하시겠습니까?").done((yes) => {
                    if (yes === true) {
                        let result = 0;
                        let updateId = [];
                        for(let ii = 0; ii < _listTable.getSelectedRowsData().length; ii ++){
                            updateId.push(_listTable.getSelectedRowsData()[ii].link_id)
                        }

                        result = postInsertUpdate("/api/database/link-prcs-para/" + updateId, updateData);
                        if (result > 0) {
                            alertConfirm("파라미터 정보를 설정하였습니다.");
                            settingData(updateId[updateId.length - 1]);
                        }
                    }
                });

            }
        }
    }).dxButton("instance");
    
    fltrChecker = [ fltrCheck1, fltrCheck2 ];
    
    fusnChecker   = [ fifoCheck, weightCheck, fusnMaxCheck];
    
    adjsChecker   = [ adjsNoCheck, adjsCheck, adjsPttr];
    
    smthChecker   = [ smthNoCheck, smthLimitCheck, smthFiftAvgCheck];
    
    //링크 관리 테이블
    _listTable = $(".list-table").width('100%').height("100%").dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        focusedRowEnabled       : true,
        noDataText              : '표출할 정보가 없습니다.',
        keyExpr                 : 'para_id',
        filterRow: {
            visible: true,
            applyFilter: "auto",
            showOperationChooser:false,
        },
        scrolling               : {
            mode : 'standard',
        },
        paging: {
            enabled: true,
            pageSize: 1000,
        },
        selection: {
            mode        : 'single',
        },
        headerFilter: {
            visible : true,
        },
        grouping: {
            autoExpandAll : true,
        },
        scrolling: {
            mode : 'virtual',
        },
        columns:[
            {   
                caption      : "기본정보",
                alignment    : "center",
                allowSorting : false,
                columns : [
                    {
                        dataField   : "para_id",
                        caption     : "ID",
                        alignment   : "center",
                    },
                    {
                        dataField   : "para_nm",
                        caption     : "명칭",
                        alignment   : "center",
                        cellTemplate(c,e){
                            alignTemplate(c, e, 'left')
                        }
                    }
                ]
            },
            {
                caption      : "필터링 파라미터",
                alignment    : "center",
                allowSorting : false,
                columns : [
                    {
                        dataField   : "fltr_mthd_desc",
                        caption     : "파라미터",
                        alignment   : "center",
                    },
                    {
                        dataField   : "detl.fltr_min_tfvl",
                        caption     : "교통량(최저)",
                        alignment   : "center",
                        cellTemplate(c,e){
                            alignTemplate(c, e, 'right')
                        }
                    },
                    {
                        dataField   : "detl.fltr_max_tfvl",
                        caption     : "교통량(최대)",
                        alignment   : "center",
                        cellTemplate(c,e){
                            alignTemplate(c, e, 'right')
                        }
                    },
                    {
                        dataField   : "detl.fltr_lwst_sped",
                        caption     : "속도(최저)",
                        alignment   : "center",
                        cellTemplate(c,e){
                            alignTemplate(c, e, 'right')
                        }
                    },
                    {
                        dataField   : "detl.fltr_hghs_sped",
                        caption     : "속도(최대)",
                        alignment   : "center",
                        cellTemplate(c,e){
                            alignTemplate(c, e, 'right')
                        }
                    }
                ]
            },
            {
                caption      : "퓨전 파라미터",
                alignment    : "center",
                allowSorting : false,
                columns : [
                    {
                        dataField   : "fusn_mthd_desc",
                        caption     : "파라미터",
                        alignment   : "center",
                    },
                    // {
                    //     dataField   : "detl.fusn_prrt",
                    //     caption     : "우선순위",
                    //     alignment   : "center",
                    // },
                    // {
                    //     dataField   : "detl.fusn_wght",
                    //     caption     : "가중치",
                    //     alignment   : "center",
                    // },
                ]
            },
            {
                caption      : "보정 파라미터",
                alignment    : "center",
                allowSorting : false,
                columns : [
                    {
                        dataField   : "adjs_mthd_desc",
                        caption     : "파라미터",
                        alignment   : "center",
                    },
                    {
                        dataField   : "detl.adjs_wght_avrg_pre_3cycl",
                        caption     : "평균가중치(3)",
                        alignment   : "center",
                        cellTemplate(c,e){
                            alignTemplate(c, e, 'right');
                            wghtDisplayValue(e,c);
                        }
                    },
                    {
                        dataField   : "detl.adjs_wght_avrg_pre_2cycl",
                        caption     : "평균가중치(2)",
                        alignment   : "center",
                        cellTemplate(c,e){
                            alignTemplate(c, e, 'right');
                            wghtDisplayValue(e,c);
                        }
                    },
                    {
                        dataField   : "detl.adjs_wght_avrg_pre_1cycl",
                        caption     : "평균가중치(1)",
                        alignment   : "center",
                        cellTemplate(c,e){
                            alignTemplate(c, e, 'right');
                            wghtDisplayValue(e,c);
                        }
                    },
                    {
                        dataField   : "detl.adjs_ptrn_15m_aply_yn",
                        caption     : "15분 패턴",
                        alignment   : "center",
                        lookup      : {
                            dataField : ["Y", "N"],
                        }
                    },
                    {
                        dataField   : "detl.adjs_shtr_miss_decs_cycl",
                        caption     : "단기결측판단주기",
                        alignment   : "center",
                    }
                ]
            },
            {
                caption      : "평활화 파라미터",
                alignment    : "center",
                dataField    : "detl",
                allowSorting : false,
                columns : [
                    {
                        dataField   : "smth_mthd_desc",
                        caption     : "파라미터",
                        alignment   : "center",
                    },
                    {
                        dataField   : "detl.smth_lwst_sped_fctr",
                        caption     : "최저속도",
                        dataType    : 'number',
                        alignment   : "center",
                        cellTemplate(c,e){
                            alignTemplate(c, e, 'right');
                            if (!isNaN(e.displayValue)){
                                c.text(e.displayValue.toFixed(2));
                            }
                        }
                    }, 
                    {
                        dataField   : "detl.smth_hghs_sped_fctr",
                        caption     : "최대속도",
                        alignment   : "center",
                        dataType    : 'number',
                        cellTemplate(c,e){
                            alignTemplate(c, e, 'right');
                            if (!isNaN(e.displayValue)){
                                c.text(e.displayValue.toFixed(2));
                            }
                        }
                    },
                    {
                        dataField   : "detl.smth_wght_avrg_pre_2cycl",
                        caption     : "가중치 평균(2)",
                        alignment   : "center",
                        cellTemplate(c,e){
                            alignTemplate(c, e, 'right');
                            wghtDisplayValue(e,c);
                        }
                    },
                    {
                        dataField   : "detl.smth_wght_avrg_pre_1cycl",
                        caption     : "가중치 평균(1)",
                        alignment   : "center",
                        cellTemplate(c,e){
                            alignTemplate(c, e, 'right');
                            wghtDisplayValue(e,c);
                        }
                    },
                    {
                        dataField   : "detl.smth_wght_avrg_prst",
                        caption     : "가중치 평균(0)",
                        alignment   : "center",
                        cellTemplate(c,e){
                            alignTemplate(c, e, 'right');
                            wghtDisplayValue(e,c);
                        }
                    }
                ]
            },
        ],
        onRowClick(e) {
            //delBtn .setDisabled(false);
            editBtn.setDisabled(false);
            settingData(e.data);
        },
    }).dxDataGrid("instance");
    
    sectionResize($('.size-border'), $('.body-box'), $('.list-box'), $('.edit-section'), $('.hide-div'));
    console.log(paddingVal($('.list-box'), 'height'));
   
    document.onkeydown = (e)=>{
        if ("F5" === e.key) {
            e.keyCode = 0;
            e.cancelBubble = true;
            e.returnValue = false;
        }
    }

    $(window).bind('beforeunload', ()=>{
        window.opener.$('.popup-screen').css('display', 'none');
    })
    fetchBaseDate();
});

function paddingVal(position, type){
    let padding;
    if (type === 'width') {
        const width = position[0].getBoundingClientRect().width;
        padding = width - position.width();
    }
    else {
        const height = position[0].getBoundingClientRect().height;
        padding = height - position.height();
    }
    
    return padding;
}

function refreshPage(){
    const selectedData = _listTable.getSelectedRowsData();
    fetchListData(()=>{
        if (selectedData && selectedData.length > 0) {
            _listTable.refresh().done(()=>{
                _listTable.selectRows(selectedData[0].para_id).done(()=>{
                    _listTable.option('focusedRowKey', selectedData[0].para_id);
                    settingData(_listTable.getSelectedRowsData()[0]);
                });
            })
        }
    });
}

/*========================필터링 파라미터 설정=======================*/
//사용안함 체크 시
function fltrCheck1VC(e){
    fltrCheck2.setValue(!e.value);
}
//범위값 사용 체크 시
function fltrCheck2VC(e){
    fltrCheck1.setValue(!e.value);
    fltrDefBtn.setDisabled(!e.value);
    trafMaxNum.setDisabled(!e.value);
    trafMinNum.setDisabled(!e.value);
    fltrHghsSped.setDisabled(!e.value);
    fltrLwstSped.setDisabled(!e.value);
    $(".fltr-box").toggleClass("dx-nav-item");
    $(".fltr-box").toggleClass("dx-theme-border-color-as-background-color");
}
//초기값 버튼 클릭
function fltrDefBtnClick(){
    arraySettingValue([trafMaxNum, trafMinNum, fltrHghsSped, fltrLwstSped])
}

/*========================결측보정 파라미터====================*/
//패턴 적용 체크시
function adjsPttrVC(e){
    if(e.value){
        adjsCheck.setValue(false);
        adjsNoCheck.setValue(false);
        adjsDefBtn.setDisabled(true);
    }
}
//사용안함 체크 시
function adjsNoCheckVC(e){
    if(e.value){
        adjsCheck.setValue(false);
        adjsPttr.setValue(false);
        adjsDefBtn.setDisabled(true);
    }
}
//단기(15분이동평균)/장기(패턴) 체크 시
function adjsCheckVC(e){
    if(e.value){
        adjsNoCheck.setValue(false);
        adjsPttr.setValue(false);
        adjsDefBtn.setDisabled(false);
    }
    $(".adjs-box").toggleClass("dx-theme-border-color-as-background-color");
    $(".adjs-box").toggleClass("dx-nav-item");
    adjsWghtAvrgPre3Cycl.setReadOnly(!e.value);
    adjsWghtAvrgPre2Cycl.setReadOnly(!e.value);
    adjsWghtAvrgPre1Cycl.setReadOnly(!e.value);
    adjs15mPtrnAplyYn.setDisabled(!e.value);
    adjsShtrMissDecsCycl.setReadOnly(!e.value);
}
//초기값 버튼 클릭
function adjsDefBtnClick(){
    if (adjsCheck.getValue()){
        adjs15mPtrnAplyYn.setValue(false);
        arraySettingValue([adjsWghtAvrgPre3Cycl, adjsWghtAvrgPre2Cycl, adjsWghtAvrgPre1Cycl, adjsShtrMissDecsCycl]);
    }
}

/*========================평활화 파라미터====================*/
//15분 이동 평균 체크 시
function smthFiftAvgCheckVC(e){
    if(e.value){
        smthLimitCheck.setValue(false);
        smthNoCheck.setValue(false);
        smthDefBtn.setDisabled(false);
    }
    $(".smth-avg-box").toggleClass("dx-nav-item");
    $(".smth-avg-box").toggleClass("dx-theme-border-color-as-background-color");
    smthWghtAvrgPre2Cycl.setReadOnly(!e.value);
    smthWghtAvrgPre1Cycl.setReadOnly(!e.value);
    smthWghtAvrgPrst.setReadOnly(!e.value);
}
//사용안함 체크 시
function smthNoCheckVC(e){
    if(e.value){
        smthFiftAvgCheck.setValue(false);
        smthLimitCheck.setValue(false);
        smthDefBtn.setDisabled(true);
    }
}
//편차제한 체크 시
function smthLimitCheckVC(e){
    if(e.value){
        smthFiftAvgCheck.setValue(false);
        smthNoCheck.setValue(false);
        smthDefBtn.setDisabled(false);
    }
    $(".smth-sped-box").toggleClass("dx-nav-item");
    $(".smth-sped-box").toggleClass("dx-theme-border-color-as-background-color");
    minSpedNum.setReadOnly(!e.value);
    maxSpedNum.setReadOnly(!e.value);
}
//초기값 버튼 클릭
function smthDefBtnClick(){
    if (smthLimitCheck.getValue()) {
        arraySettingValue([minSpedNum, maxSpedNum])
    }
    else {
        arraySettingValue([smthWghtAvrgPre2Cycl, smthWghtAvrgPre1Cycl, smthWghtAvrgPrst])
    }
}

//초기값 자동 세팅을 위한 함수
function arraySettingValue(array){
    for (let ii = 0; ii < array.length; ii++){
        array[ii].setValue(array[ii].value);
    }
}
/*=================퓨전 파라미터 ======================*/
function fifoCheckVC(e){
    if (e.value) {
        fusnMaxCheck.setValue(false);
        weightCheck.setValue(false);
        dsblOffBtn(fifoTable);
        dsblOnBtn(weightTable);
    }
    $(".fifo-box").toggleClass("dx-nav-item");
    $(".fifo-box").toggleClass("dx-theme-border-color-as-background-color");
}
function fusnMaxCheckVC(e){
    if (e.value) {
        fifoCheck.setValue(false);
        weightCheck.setValue(false);
        fifoTable.option("disabled", true);
        weightTable.option("disabled", true);
        dsblOnBtn(fifoTable);
        dsblOnBtn(weightTable);
    }
}
function weightCheckVC(e){
    if (e.value) {
        fusnMaxCheck.setValue(false);
        fifoCheck.setValue(false);
        dsblOnBtn(fifoTable);
        dsblOffBtn(weightTable);
    }
    $(".weight-box").toggleClass("dx-nav-item");
    $(".weight-box").toggleClass("dx-theme-border-color-as-background-color");
}

/*==================하단 버튼 이벤트 =================== */
function addBtnClick(){
    $('.hide-div').css('display', 'none');
    cancelBtn.setVisible(true);
    saveBtn.setVisible(true);
    editBtn.setVisible(false);
    addBtn.setVisible(false);
    searchBtn.setDisabled(true);
    dsblOnBtn(_listTable);
    initData();
    let data = [];
    getData('/api/database/link-para-stup/new-id', data);
    if (data) {
        paramId.setValue(data[0].new_id);
    }
}

function editBtnClick(){
    $('.hide-div').css('display', 'none');
    cancelBtn.setVisible(true);
    saveBtn.setVisible(true);
    editBtn.setVisible(false);
    addBtn.setVisible(false);
    searchBtn.setDisabled(true);
    dsblOnBtn(_listTable);
    //delBtn.setVisible(false);
}

function initData(){
    arraySettingValue([
        trafMaxNum, 
        trafMinNum, 
        fltrLwstSped,
        fltrHghsSped, 
        paramId,
        paramName,
        fltrCheck1,
        adjsCheck,
        adjs15mPtrnAplyYn,
        adjsWghtAvrgPre3Cycl,
        adjsWghtAvrgPre2Cycl,
        adjsWghtAvrgPre1Cycl,
        adjsShtrMissDecsCycl,
        smthLimitCheck,
        minSpedNum,
        maxSpedNum,
        smthWghtAvrgPre1Cycl,
        smthWghtAvrgPre2Cycl,
        smthWghtAvrgPrst,
        fifoCheck,
    ]);

    fltrDefBtn.setDisabled(false);
    adjsDefBtn.setDisabled(false);
    smthDefBtn.setDisabled(false);

    weightTable.option('dataSource', fusnListData);
    fifoTable.option('dataSource', fusnListData);
}

function delBtnClick(){

}
function cancelBtnClick(){
    $('.hide-div').css('display', 'flex');
    cancelBtn.setVisible(false);
    saveBtn.setVisible(false);
    editBtn.setVisible(true);
    addBtn.setVisible(true);
    editBtn.setDisabled(true);
    searchBtn.setDisabled(false);
    dsblOffBtn(_listTable);
    const selectedData = _listTable.getSelectedRowsData();
    if (selectedData && selectedData.length > 0) {
        editBtn.setDisabled(false);
        settingData(selectedData[0]);
    }
    else {
        initData();
    }
    //delBtn.setVisible(true);
}
function saveBtnClick(){
    let updateData = updateSettingData();
    let paramIdVal = paramId.getValue();
    if (updateData === false){
        return
    }
    else {
        let result = postInsertUpdate(_apiUri + '/' + encodeURIComponent(paramIdVal), updateData)
        if (result > 0) {
            alertConfirm( '파라미터 ID : '+ paramIdVal + '<br>파라미터 정보를 설정하였습니다.');
            fetchListData(()=>{
                _listTable.refresh().done(()=>{
                    _listTable.selectRows(paramIdVal).done(()=>{
                        _listTable.option('focusedRowKey', paramIdVal);
                        cancelBtnClick();
                        window.opener.$('.param-select').dxSelectBox('instance').option('dataSource', _listTable.option('dataSource'));
                    })
                })
            });
        }
    }
}
function fetchBaseDate(){
    getDataAsync(fusnUri, (fusnData)=>{
        if (fusnData.length > 0) {
            for ( let ii = 1; ii <= fusnData.length; ii++){
                fusnListData.push({...fusnData[ii-1]});
                fusnListData[ii-1].fusn_prrt = ii;
                fusnListData[ii-1].fusn_wght = 10;
                fusnListData[ii-1].clct_syst_desc = fusnData[ii-1].clct_syst_nm;
                if(fusnData.length === ii){
                    fifoData.push({fusn_prrt:ii});
                    fifoData.push({fusn_prrt:'사용안함'});
                    break;
                } 
                
                fifoData.push({
                    fusn_prrt:ii,
                })
            }
        }
        fifoTable.option('dataSource', fusnListData);
        fifoTable.option('columns[1].lookup.dataSource', fifoData);
        weightTable.option('dataSource', fusnListData);
    })
    fetchListData();
}
function fetchListData(method){
    getDataAsync(_apiUri, (jsonData)=>{ 
        _listTable.option('dataSource', jsonData);
        if(method) {
            method();
        }
    });
}

function settingData(data){
        let paramIdVal = data.para_id;
        paramId.setValue(paramIdVal);
        paramName.setValue(data.para_nm);
        let detl        = data.detl;
        let searchData  = [];
        getData(_apiUri + '/' + paramIdVal, searchData);
        let wfData = [];
        if (searchData && searchData.length > 0) {
            wfData = searchData[0].clcts;
            wfData.map((item)=>{
                item.fusn_wght = item.fusn_wght * 100;
            })
        }
        weightTable.option('dataSource', wfData);
        fifoTable.option('dataSource', wfData);

        findCheckValue(fltrChecker, data.fltr_mthd_cd);
        findCheckValue(fusnChecker, data.fusn_mthd_cd);
        findCheckValue(smthChecker, data.smth_mthd_cd);
        findCheckValue(adjsChecker, data.adjs_mthd_cd);

        if (detl) {
            adjsWghtAvrgPre3Cycl.setValue( detl.adjs_wght_avrg_pre_3cycl * 100 );
            adjsWghtAvrgPre2Cycl.setValue( detl.adjs_wght_avrg_pre_2cycl * 100 );
            adjsWghtAvrgPre1Cycl.setValue( detl.adjs_wght_avrg_pre_1cycl * 100 );
            minSpedNum.setValue( detl.smth_lwst_sped_fctr );
            maxSpedNum.setValue( detl.smth_hghs_sped_fctr );
            smthWghtAvrgPre2Cycl.setValue( detl.smth_wght_avrg_pre_2cycl * 100 );
            smthWghtAvrgPre1Cycl.setValue( detl.smth_wght_avrg_pre_1cycl * 100 );
            smthWghtAvrgPrst.setValue( detl.smth_wght_avrg_prst * 100 );
            fltrLwstSped.setValue( detl.fltr_lwst_sped );
            fltrHghsSped.setValue( detl.fltr_hghs_sped );
            trafMinNum.setValue( detl.fltr_min_tfvl );
            trafMaxNum.setValue( detl.fltr_max_tfvl );
            adjsShtrMissDecsCycl.setValue( detl.adjs_shtr_miss_decs_cycl );
            let result = detl.adjs_ptrn_15m_aply_yn === 'Y';
            adjs15mPtrnAplyYn.setValue( result );
        }
}
function findCheckValue(array, code){
    for (let idx in array) {
        if (array[idx].code === code) {
            array[idx].setValue(true);
            return;
        } 
    }
}

function updateSettingData(){
    let adjs_mthd_cd = null;
    let fltr_mthd_cd = null;
    let fusn_mthd_cd = null;
    let smth_mthd_cd = null;
    fifoTable.saveEditData();
    weightTable.saveEditData();

    //체크 값 데이터
    fltrChecker.map((item)=>{
        if (item.getValue()) return fltr_mthd_cd = item.code;
    });

    fusnChecker.map((item)=>{
        if(item.getValue()) return fusn_mthd_cd = item.code;
    });

    adjsChecker.map((item)=>{
        if(item.getValue()) return adjs_mthd_cd = item.code;
    });

    smthChecker.map((item)=>{
        if(item.getValue()) return smth_mthd_cd = item.code;
    });
    
    let fifoTableData   = fifoTable.option('dataSource');
    let weightTableData = weightTable.option('dataSource');

    let clcts           = [];
    let totWeight       = 0;
    let fusnTot         = 0;
    let dataPrrtTot     = 0;
    let adjsWghtAvrgTot = adjsWghtAvrgPre3Cycl.getValue()
                        + adjsWghtAvrgPre2Cycl.getValue()
                        + adjsWghtAvrgPre1Cycl.getValue();

    let smthWghtAvrgTot = smthWghtAvrgPre2Cycl.getValue()
                        + smthWghtAvrgPre1Cycl.getValue()
                        + smthWghtAvrgPrst.getValue();

    let para_id         = paramId.getValue();
    let cnt = 1;
    for ( let ii = 0; ii < fifoTableData.length; ii++ ) {
        let fusn_prrt = null;
        let fusn_wght = null;
        if (fusn_mthd_cd === 'FST1') {
            //사용안함 제외 syslist 데이터
            fusn_prrt = fifoTableData[ii].fusn_prrt;

            if (fusn_prrt === '사용안함' || nullChecker(fusn_prrt) === "") {
                continue;
            }
            else {
                dataPrrtTot += cnt++;
                fusnTot += fusn_prrt;
                fusn_wght = 0.1;
            }
        }
        else if(fusn_mthd_cd === 'FST2') {
            fusn_wght = Number(weightTableData[ii].fusn_wght);
            fusn_prrt = ii + 1;
            if (fusn_wght) {
                totWeight += fusn_wght;
                fusn_wght = (fusn_wght / 100);
            }
        }
        else {
            fusn_prrt = ii+1;
            fusn_wght = 0.1;
        }
        clcts.push({
            clct_syst_cd : fifoTableData[ii].clct_syst_cd,
            fusn_prrt    : fusn_prrt,
            fusn_wght    : fusn_wght,
            para_id      : para_id,
        });
    }

    //유효성 검사
    switch (true) {
        case nullChecker(para_id) === "" :
            alertWarning("파라미터 ID를 입력해주세요", null, paramId.text)
            return false;
        case nullChecker(paramName.getValue()) === "" :
            alertWarning("파라미터명을 입력해주세요", null, paramName.text)
            return false;
        case fltr_mthd_cd === "FMT1" && validationText(trafMinNum):
            alertWarning("필터링 파라미터 - 범위값 사용<br>교통량 최저 범위를 입력하세요", null, trafMinNum.number);
            return false;
        case fltr_mthd_cd === "FMT1" && validationText(trafMaxNum):
            alertWarning("필터링 파라미터 - 범위값 사용<br>교통량 최대 범위를 입력하세요", null, trafMaxNum.number);
            return false;
        case fltr_mthd_cd === "FMT1" && trafMinNum.getValue() > trafMaxNum.getValue():
            alertWarning("필터링 파라미터 - 범위값 사용<br>최저 범위가 최대 범위 보다 큽니다.", null, trafMaxNum.number);
            return false;
        case fltr_mthd_cd === "FMT1" && validationText(fltrLwstSped):
            alertWarning("필터링 파라미터 - 범위값 사용<br>속도 최저 범위를 입력하세요", null, fltrLwstSped.number);
            return false;
        case fltr_mthd_cd === "FMT1" && validationText(fltrHghsSped):
            alertWarning("필터링 파라미터 - 범위값 사용<br>속도 최대 범위를 입력하세요.", null, fltrHghsSped.number);
            return false;
        case fltr_mthd_cd === "FMT1" && fltrLwstSped.getValue() > fltrHghsSped.getValue():
            alertWarning("필터링 파라미터 - 범위값 사용<br>속도 최저 범위가 최대 범위보다 작아야 합니다.", null, fltrHghsSped.number);
            return false;
        case (fusn_mthd_cd === "FST1" && dataPrrtTot === 0):
            alertWarning("퓨전 파라미터 - 우선순위<br>우선 순위가 지정되지 않았습니다.");
            return false;
        case fusn_mthd_cd === "FST1" && dataPrrtTot !== fusnTot:
            alertWarning("퓨전 파라미터 - 우선순위<br>우선 순위는 순서에 맞게 각자 다른값을 가져야 합니다.");
            return false;
        case fusn_mthd_cd === "FST2" && totWeight !== 100:
            alertWarning("퓨전 파라미터 - 가중치<br>가중치의 전체합은 100 이어야 합니다.");
            return false;
        case adjs_mthd_cd === "MCA1" && validationText(adjsWghtAvrgPre3Cycl):
            alertWarning("보정 파라미터 - 단기(15분이동평균)/장기(패턴)<br>3주기전 평균 가중치 값을 입력해주세요.", null, adjsWghtAvrgPre3Cycl.number);
            return false;
        case adjs_mthd_cd === "MCA1" && validationText(adjsWghtAvrgPre2Cycl):
            alertWarning("보정 파라미터 - 단기(15분이동평균)/장기(패턴)<br>2주기전 평균 가중치 값을 입력해주세요.", null, adjsWghtAvrgPre2Cycl.number);
            return false;
        case adjs_mthd_cd === "MCA1" && validationText(adjsWghtAvrgPre1Cycl):
            alertWarning("보정 파라미터 - 단기(15분이동평균)/장기(패턴)<br>1주기전 평균 가중치 값을 입력해주세요.", null, adjsWghtAvrgPre1Cycl.number)
            return false;
        case adjs_mthd_cd === "MCA1" && adjsWghtAvrgTot !== 100:
            alertWarning("보정 파라미터 - 단기(15분이동평균)/장기(패턴)<br>평균 가중치의 전체합은 100 이어야 합니다.", null, adjsWghtAvrgPre1Cycl.number);
            return false;
        case adjs_mthd_cd === "MCA1" && validationText(adjsShtrMissDecsCycl):
            alertWarning("보정 파라미터 - 단기(15분이동평균)/장기(패턴)<br>단기 결측 판단 주기 값을 입력해주세요.", null, adjsShtrMissDecsCycl.number);
            return false;
            
        case smth_mthd_cd === "SMT1" && validationText(minSpedNum):
            alertWarning("평활화 파라미터 - 편차제한(최저-최대)<br>최저속도계수 값을 입력해주세요.", null, minSpedNum.number);
            return false;
            
        case smth_mthd_cd === "SMT1" && validationText(maxSpedNum):
            alertWarning("평활화 파라미터 - 편차제한(최저-최대)<br>최대속도계수 값을 입력해주세요.", null, maxSpedNum.number);
            return false;
        case smth_mthd_cd === "SMT1" && minSpedNum.getValue() > maxSpedNum.getValue():
            alertWarning("평활화 파라미터 - 편차제한(최저-최대)<br>최저속도계수 값이 최대속도계수 값보다 작아야 합니다.", null, maxSpedNum.number);
            return false;
        case smth_mthd_cd === "SMT2" && validationText(smthWghtAvrgPre2Cycl):
            alertWarning("평활화 파라미터 - 15분 이동평균(전체합=100)<br>2주기전 가중치 평균 값을 입력해주세요.", null, smthWghtAvrgPre2Cycl.number);
            return false;
            
        case smth_mthd_cd === "SMT2" && validationText(smthWghtAvrgPre1Cycl):
            alertWarning("평활화 파라미터 - 15분 이동평균(전체합=100)<br>1주기전 가중치 평균 값을 입력해주세요.", null, smthWghtAvrgPre1Cycl.number);
            return false;
            
        case smth_mthd_cd === "SMT2" && validationText(smthWghtAvrgPrst):
            alertWarning("평활화 파라미터 - 15분 이동평균(전체합=100)<br>현재 가중치 평균 값을 입력해주세요.", null, smthWghtAvrgPrst.number);
            return false;
            
        case smth_mthd_cd === "SMT2" && smthWghtAvrgTot !== 100:
            alertWarning("평활화 파라미터 - 15분 이동평균(전체합=100)<br>분 이동평균값 가중치의 전체합은 100 이어야 합니다.", null, smthWghtAvrgPrst.number);
            return false;
    }

    let adjs_wght_avrg_pre_3cycl = adjsWghtAvrgPre3Cycl.getValue() / 100;
    let adjs_wght_avrg_pre_2cycl = adjsWghtAvrgPre2Cycl.getValue() / 100;
    let adjs_wght_avrg_pre_1cycl = adjsWghtAvrgPre1Cycl.getValue() / 100;
    let smth_lwst_sped_fctr      = minSpedNum.getValue().toFixed(2);
    let smth_hghs_sped_fctr      = maxSpedNum.getValue().toFixed(2);
    let smth_wght_avrg_pre_2cycl = smthWghtAvrgPre2Cycl.getValue() / 100;
    let smth_wght_avrg_pre_1cycl = smthWghtAvrgPre1Cycl.getValue() / 100;
    let smth_wght_avrg_prst      = smthWghtAvrgPrst.getValue() / 100;
    let fltr_lwst_sped           = fltrLwstSped.getValue();
    let fltr_hghs_sped           = fltrHghsSped.getValue();
    let fltr_min_tfvl            = trafMinNum.getValue();
    let fltr_max_tfvl            = trafMaxNum.getValue();
    let adjs_shtr_miss_decs_cycl = adjsShtrMissDecsCycl.getValue();
    let adjs_ptrn_15m_aply_yn    = adjs15mPtrnAplyYn.getValue()?'Y':'N';
    let para_nm                  = paramName.getValue();
    let updateData   = {
        detl: {
            adjs_ptrn_15m_aply_yn     : adjs_ptrn_15m_aply_yn,
            adjs_shtr_miss_decs_cycl  : adjs_shtr_miss_decs_cycl,
            adjs_wght_avrg_pre_1cycl  : adjs_wght_avrg_pre_1cycl,
            adjs_wght_avrg_pre_2cycl  : adjs_wght_avrg_pre_2cycl,
            adjs_wght_avrg_pre_3cycl  : adjs_wght_avrg_pre_3cycl,
            fltr_hghs_sped            : fltr_hghs_sped,
            fltr_lwst_sped            : fltr_lwst_sped,
            fltr_max_tfvl             : fltr_max_tfvl,
            fltr_min_tfvl             : fltr_min_tfvl,
            smth_hghs_sped_fctr       : smth_hghs_sped_fctr,
            smth_lwst_sped_fctr       : smth_lwst_sped_fctr,
            para_id                   : para_id,
            para_r                    : 0.2,
            smth_wght_avrg_pre_1cycl  : smth_wght_avrg_pre_1cycl,
            smth_wght_avrg_pre_2cycl  : smth_wght_avrg_pre_2cycl,
            smth_wght_avrg_prst       : smth_wght_avrg_prst,                
        },
        para: {
            adjs_mthd_cd : adjs_mthd_cd,
            fltr_mthd_cd : fltr_mthd_cd,
            fusn_mthd_cd : fusn_mthd_cd,
            smth_mthd_cd : smth_mthd_cd,
            para_id :  para_id,
            para_nm : para_nm,
        },
        clcts : clcts,
        paramId : para_id,
    }
    return updateData;
}

function validationText(textBox) {
    return nullChecker(textBox.getValue()) === "";
}

//마우스 드래그 리사이즈 함수
function sectionResize(position, parent, position1, position2, serve) {
    const dragBorder = position;
    const firstTHeight = position1.height();
    dragBorder.on('mousedown', function(event){
        let clientY = event.clientY;
        dragBorder.on("dragstart", function(event){
            const dropPosition = parent;
            let whVal1 = position1.height();
            
            dropPosition.on('dragover', function(event){
                event.preventDefault();
            })
            
            dropPosition.on('drop',function(event){
                event.preventDefault();
                let moveVal = null;
                let serveVal = null;
                moveVal = event.clientY - clientY;
                let padding = paddingVal(position1, 'height');
                let borderWidth = position.css('border-width');
                if (borderWidth.length > 0) {
                    borderWidth = borderWidth.replaceAll("px", "");
                    for (let width of borderWidth.split(" ")) {
                        if (Number(width) > 0) {
                            console.log(width);
                            borderWidth = Number(width);
                        }
                    }
                }
                let addVal = paddingVal(position2, 'height') + borderWidth;
                let position2Val = 'calc(100% - '+ (whVal1 + moveVal + addVal) +'px)';
                serveVal = 'calc(100% - '+ (whVal1 + moveVal + 110) +'px)';

                position1.css('height', (whVal1 + moveVal - padding) + 'px');
                position2.css('height', position2Val);
                serve.css('height', serveVal);
                dragBorder.off('dragstart');
                dropPosition.off('dragover');
                dropPosition.off('drop');
               
            })
        });
    })

    dragBorder.on('dblclick',()=>{
        const firstVal1 = firstTHeight
        const firstVal2 = 'calc(100% - 369px)';
        const serveVal = 'calc(100% - 470px)';
        position1.css('height', firstVal1);
        position2.css('height', firstVal2);
        serve.css('height', serveVal);
    })
}

function wghtDisplayValue(e,c){
    if (nullChecker(e.displayValue) !== "") {
        c.text((e.displayValue * 100));
    }
}