//우측 섹션 관련
let _managerData = [];
let _ixrTable;
let _infoList;
let _todoList;
let _specCtlrList;
let _dispInfoList;
let _radioType;
let _planNumb;
//공통
let _commonUri = "/api/scrs/tb_sc_sgnl_ixr_mngm/list";
const _pageName = '신호교차로 정보';
const pageMsg = "신호교차로";
const phaseMap = new Map();
const titleMap = new Map();
titleMap.set('crfl_nmbr', '이동류');
titleMap.set('min_gren_hh', '최소녹색시간');
titleMap.set('max_gren_hh', '최대녹색시간');
titleMap.set('yelw_hh', '황색시간');
const normalData = [1,2,3,4,5];
const timeData = [6,7,8,9,10];
$(() => {
    //상단 닫기 버튼
    const closeBtn = new dxBtn($('.close-btn'), '닫기', 'close', 'outlined', 80, 30, false, true); 
    closeBtn.onClick(()=>window.close());
    _planNumb = new dxSelect($('.plan_nmbr'), 'outlined', 100, 30, null, null, false, 'plan_nmbr', '플랜번호');
    _planNumb.setDataSource(normalData);
    _planNumb.setValue(1);
    _planNumb.onItemClick((e) => planNumbClick(e.itemData));
    _ixrTable = $(".manager-table")
        .width("100%")
        .height("100%")
        .dxDataGrid({
            dataSource: [],
            allowColumnReordering: true,
            showColumnLines: true,
            showBorders: true,
            allowColumnResizing: true,
            rowAlternationEnabled: true,
            focusedRowEnabled: true,
            columnAutoWidth: true,
            noDataText: "표출할 정보가 없습니다.",
            selection: {
                mode: "single",
            },
            keyExpr: "sgnl_ixr_nmbr",

            headerFilter: {
                visible: true,
            },
            scrolling: {
                mode: "virtual",
            },
            columns: [
                {
                    dataField: "sgnl_ixr_nmbr",
                    caption: "번호",
                    width: 120,
                    alignment: "center",
                    format   : "0000",
                },
                {
                    dataField: "ixr_nm",
                    caption: "교차로 명칭",
                    alignment: "center",
                    cellTemplate(c, e) {
                        return alignTemplate(c, e, 'left');
                    },
                },
            ],
            onRowDblClick(e) {
                ixrTableDblClick(e);
            },
        })
        .dxDataGrid("instance");
    
    _infoList = $(".info-list")
        .width("100%")
        .height("100%")
        .dxDataGrid({
            dataSource: [],
            allowColumnReordering: true,
            showColumnLines: true,
            showBorders: true,
            allowColumnResizing: true,
            rowAlternationEnabled: true,
            focusedRowEnabled: true,
            columnAutoWidth: true,
            noDataText: "표출할 정보가 없습니다.",
            selection: {
                mode: "single",
            },
            sorting:{
                mode: "none",
            },
            keyExpr: "ixr_grop",
            scrolling: {
                mode: "virtual",
            },
            columns: [
                {
                    dataField : "ixr_grop",
                    caption   : "교차로 소속 그룹",
                    alignment : "center",
                },
                {
                    dataField : "stad_dvsn",
                    caption   : "규격",
                    alignment : "center",
                    lookup:{
                        dataSource:[],
                        displayExpr: 'cmmn_cd_kor_nm',
                        valueExpr  : 'cmmn_cd',
                    }
                },
                {
                    dataField : "ixr_dvsn",
                    caption   : "교차로 구분",
                    alignment : "center",
                    lookup:{
                        dataSource:[],
                        displayExpr: 'cmmn_cd_kor_nm',
                        valueExpr  : 'cmmn_cd',
                    }
                },
            ],
        })
        .dxDataGrid("instance");
    
    _dispInfoList = $('.dspl-info-list').width('100%').height('100%').dxPivotGrid({
        allowSortingBySummary: false,
        allowSorting: true,
        allowFiltering: false,
        allowExpandAll: true,
        showBorders: true,
        showRowGrandTotals:false,
        showColumnGrandTotals:false,
        fieldChooser: {
            enabled: false,
        },
        dataSource: {
            fields: [
                {
                    dataField: 'region',
                    area: 'row',
                },
                {
                    dataField: 'title',
                    area: 'column',
                },
                {
                    dataField: 'amount',
                    dataType: 'number',
                    summaryType: 'sum',
                    area: 'data',
                },
            ],
            store : [],
        },
    }).dxPivotGrid('instance');

   
    _todoList = $(".day-ctlr-list")
        .width("100%")
        .height("100%")
        .dxDataGrid({
            dataSource: [],
            allowColumnReordering: true,
            showColumnLines: true,
            showBorders: true,
            allowColumnResizing: true,
            rowAlternationEnabled: true,
            focusedRowEnabled: true,
            columnAutoWidth: true,
            noDataText: "표출할 정보가 없습니다.",
            selection: {
                mode: "single",
            },
            keyExpr: "ixr_phas_oper_plan_nmbr",
            scrolling: {
                mode: "virtual",
            },
            sorting:{
                mode: "none",
            },
            columns: [
                {
                    dataField: "ixr_phas_oper_plan_nmbr",
                    caption: "NO",
                    alignment: "center",
                },
                {
                    dataField : 'hh',
                    caption: "시간",
                    alignment: "center",
                },
                {
                    dataField : 'mm',
                    caption: "분",
                    alignment: "center",
                },
                {
                    dataField : 'cycl',
                    caption: "주기",
                    alignment: "center",
                },
                {
                    dataField : 'ofst',
                    caption: "연동",
                    alignment: "center",
                },
                {
                    caption: "1현시",
                    alignment: "center",
                    columns : [
                        {
                            dataField : 'aring_1phas',
                            caption: "A",
                            alignment: "center",
                        },
                        {
                            dataField : 'bring_1phas',
                            caption: "B",
                            alignment: "center",
                        },
                    ]
                },
                {
                    caption: "2현시",
                    alignment: "center",
                    columns : [
                        {
                            dataField : 'aring_2phas',
                            caption: "A",
                            alignment: "center",
                        },
                        {
                            dataField : 'bring_2phas',
                            caption: "B",
                            alignment: "center",
                        },
                    ]
                },
                {
                    caption: "3현시",
                    alignment: "center",
                    columns : [
                        {
                            dataField : 'aring_3phas',
                            caption: "A",
                            alignment: "center",
                        },
                        {
                            dataField : 'bring_3phas',
                            caption: "B",
                            alignment: "center",
                        },
                    ]
                },
                {
                    caption: "4현시",
                    alignment: "center",
                    columns : [
                        {
                            dataField : 'aring_4phas',
                            caption: "A",
                            alignment: "center",
                        },
                        {
                            dataField : 'bring_4phas',
                            caption: "B",
                            alignment: "center",
                        },
                    ]
                },
                {
                    caption: "5현시",
                    alignment: "center",
                    columns : [
                        {
                            dataField : 'aring_5phas',
                            caption: "A",
                            alignment: "center",
                        },
                        {
                            dataField : 'bring_5phas',
                            caption: "B",
                            alignment: "center",
                        },
                    ]
                },
                {
                    caption: "6현시",
                    alignment: "center",
                    columns : [
                        {
                            dataField : 'aring_6phas',
                            caption: "A",
                            alignment: "center",
                        },
                        {
                            dataField : 'bring_6phas',
                            caption: "B",
                            alignment: "center",
                        },
                    ]
                },
                {
                    caption: "7현시",
                    alignment: "center",
                    columns : [
                        {
                            dataField : 'aring_7phas',
                            caption: "A",
                            alignment: "center",
                        },
                        {
                            dataField : 'bring_7phas',
                            caption: "B",
                            alignment: "center",
                        },
                    ]
                },
                {
                    caption: "8현시",
                    alignment: "center",
                    columns : [
                        {
                            dataField : 'aring_8phas',
                            caption: "A",
                            alignment: "center",
                        },
                        {
                            dataField : 'bring_8phas',
                            caption: "B",
                            alignment: "center",
                        },
                    ]
                },
               
            ],
            onRowDblClick(e) {
            },
        })
        .dxDataGrid("instance");

        _radioType = $('.radio').dxRadioGroup({
            items : [
                {
                    id : 0, 
                    text : '일반',
                },
                {
                    id : 1,
                    text : '시차',
                }
            ],
            width       : '100%',
            height      : '100%',
            displayExpr : 'text',
            valueExpr   : 'id',
            value       : 0,
        }).dxRadioGroup('instance');
        _radioType.on('valueChanged', (e)=>phaseInfoChange(e));
        fetchCdData();
        fetchBaseData();
});

function ixrTableDblClick(e){
    recvIxrInfoData([e.data]);
    const key = e.data.sgnl_ixr_nmbr;
    getDataAsync('/api/scrs/tb_sc_ixr_phas/' + key, recvPhasData, key);
    planNumbClick(_planNumb.getValue());
}

function planNumbClick(planNumb){
    getDataAsync('/api/scrs/tb_sc_tod_cnfg/' + _ixrTable.getSelectedRowsData()[0].sgnl_ixr_nmbr + '/' + planNumb, recvTodData);
}
function phaseInfoChange(e){
    if (nullChecker(e.value) !== "") {
        const signData = phaseMap.get(e.value);
        console.log(signData);
        if (signData) {
            drawPivotTable(signData)
        }
        else  {
            _dispInfoList.option('dataSource.store', []);
        }
        const planData = e.value === 0 ? normalData : timeData;
        _planNumb.setDataSource(planData);
        _planNumb.setValue(planData[0]);
        planNumbClick(planData[0]);
    }
}

function fetchBaseData(){
    getDataAsync(_commonUri, recvListData);
}

function recvListData(jsonData){
    _ixrTable.option('dataSource', jsonData);
    if (jsonData.length > 0) {
        const key = jsonData[0].sgnl_ixr_nmbr;
        _ixrTable.selectRows(key);
        _ixrTable.option('focusedRowIndex', 0);
        recvIxrInfoData([jsonData[0]]);
        getDataAsync('/api/scrs/tb_sc_ixr_phas/' + key, recvPhasData, key);
    }
}

function recvPhasData(jsonData, key){
    phaseMap.clear();
    if (jsonData.length > 0) {
        jsonData.map((item)=>{
            phaseMap.set(item.ixr_oper_mode, item);
        });
        const data = phaseMap.get(_radioType.option('value'));
        drawPivotTable(data);
        const planNmbr = _planNumb.getValue();
        getDataAsync('/api/scrs/tb_sc_tod_cnfg/' + key + '/' + planNmbr, recvTodData);
    }
}

function recvTodData(jsonData){
    console.log(jsonData);
    _todoList.option('dataSource', jsonData);
}

function drawPivotTable(signData){
    let cnt = 1;
    let data = [];
    for (let ii =1; ii <=8; ii++) {
        for (let key in signData) {
            if (key.includes('aring_' + ii)) {
              data.push({
                  id : cnt++,
                  region : ii + ' - A링',
                  title : titleMap.get(key.substring(12, key.length)),
                  amount :  signData[key],
              });
            }
            else if (key.includes('bring_' + ii)) {
              data.push({
                  id : cnt++,
                  region : ii + ' - B링',
                  title : titleMap.get(key.substring(12, key.length)),
                  amount :  signData[key],
              });
            }
        }
    }

    _dispInfoList.option('dataSource.store', data);
}

function recvIxrInfoData(jsonData){
    _infoList.option('dataSource', jsonData);
}

function fetchCdData(){
    //'규격', '교차로구분'
    const cdColumns = ['STDDVSN', 'CRSDVSN'];
    getDataAsync('/api/database/code/cmmn-cd/' + encodeURIComponent('STDDVSN'), recvCdData, 1);
    getDataAsync('/api/database/code/cmmn-cd/' + encodeURIComponent('CRSDVSN'), recvCdData, 2);
}

function recvCdData(jsonData, index){
    _infoList.option('columns[' + index + '].lookup.dataSource', jsonData);
}