import { requestGet, apiGet } from "/js/utils/restApi.js";

const time = $('.time');
let _strtIdx;
let _endIdx;
let interval;
let sysY = [
  {
      id   : 'tot',
      name : 'ITS 프로세스',
      data : null,
      color : '#7cb5ec',
      stack : 'ITS 프로세스'
  },
  {
      id   : 'CCTV',
      name : 'CCTV',
      data : null,
      color : '#f7a35c',
      stack : 'CCTV'
  },
  {
      id   : 'VDS',
      name : 'VDS',
      data : null,
      color : '#8085e9',
      stack : 'VDS',
  },
  {
      id   : 'DSRC',
      name : 'DSRC',
      data : null,
      color : '#90ed7d',
      stack : 'DSRC',
  },
  {
      id   : 'VMS',
      name : 'VMS',
      data : null,
      color : '#f15c80',
      stack : 'VMS',
  },
  {
    id   : 'SIG',
    name : '신호제어기',
    data : null,
    color : '#e4d354',
    stack : 'SIG',
  },
  {
    id   : 'CCAM',
    name : '교차로카메라',
    data : null,
    color : 'gray',
    stack : 'CCAM',
  },
]
let traffArr = [
    {
        id    : 'ltc1',
        name  : '원활',
        color : '#15B337',
    }, 
    {
        id    : 'ltc2',
        name  : '지체',
        color : '#FFAA00',
    }, 
    {
        id    : 'ltc3',
        name  : '정체',
        color : '#ff0000',
    },
]
let clctArr = [
    {
        id    : 'moct01',
        name  : '민간정보',
        color : '#FFAA00',
    },
    {
        id    : 'dsrc01',
        name  : 'DSRC',
        color : 'red',
    }, 
    {
        id    : 'gits01',
        name  : '경기도',
        color : 'green',
    }, 
    {
        id    : 'vds01',
        name  : 'VDS',
        color : '#f7ff5c',
    }
]

const systemY = [
    {
        name : '통신이상',
        data : [],
        color : '#FF0000',
    },
    {
        name : '정상',
        data : [],
        color : '#15B337',
    },
];

const dbY = [
    {
        name : '여유공간',
        data : [],
        color : '#15B337',
    },
    {
        name : '사용공간',
        data : [],
        color : '#FF0000',
    },
]
let _incdList;

$(()=>{
    time.text(now());
    timer();
    
    _incdList = $('.incd-list').width("100%")
        .height("100%")
        .dxDataGrid({
        dataSource              : null,
        allowColumnReordering   : true,
        showColumnLines         : true,
        allowColumnResizing     : true,
        showBorders             : true,
        rowAlternationEnabled   : true,
        columnAutoWidth         : true,
        noDataText              : "현재 돌발 발생 정보가 없습니다.",
        focusedRowEnabled       : true,
        keyExpr                 : ['incd_ocrr_id', 'rgst_dt'],
        headerFilter: {
            visible: true,
        },
        selection: {
            mode: "single",
        },
        scrolling: {
            mode: "virtual",
        },
        columns: [
            {
                dataField: "incd_type_clsf_desc",
                caption: "분류",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_strt_dt",
                caption: "시작 일시",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_end_prar_dt",
                caption: "종료 예정 일시",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_titl",
                caption: "제목",
                alignment: "center",
                cssClass : 'p-5',
                cellTemplate(c, e) {
                    c.css("text-align", "left");
                    return c.text(e.displayValue);
                },
            },
            {
                dataField: "ocrr_lctn_nm",
                caption: "발생 위치 설명",
                alignment: "center",
                cssClass : 'p-5',
                cellTemplate(c, e) {
                    c.css("text-align", "left");
                    return c.text(e.displayValue);
                },
            },
            {
                dataField: "incd_prgr_step_desc",
                caption: "진행 단계",
                alignment: "center",
                cssClass : 'p-5',
            },
            {
                dataField: "incd_orgn_desc",
                caption: "동발상황 구분",
                alignment: "center",
                cssClass : 'p-5',
            },
        ],
    }).dxDataGrid('instance');
    let clctY = [];
    let clctPie = [];
    clctArr.map((item)=>{
        if (item.id === 'moct01') {
            clctY.push({...item, data:[], type : 'area', yAxis : 1});
          }
          else {
            clctY.push({...item, data:[], type : 'line'});
          }
          clctPie.push({...item, y:0});
    })
    let traffY = [];
    let traffPie = [];
    traffArr.map((item)=>{
        traffY.push({...item, data:[], showInLegend: false,});
        traffPie.push({...item, y:0});
    })
    drawAreaChart('traff_0', [], '개수', 0, traffY, '교통 상황');
    drawAreaChart('traff_1', [], '개수', 0, traffY, '교통 상황');
    drawAreaChart('traff_2', [], '개수', 0, traffY, '교통 상황');
    drawPieChart('traff_tot_0', traffPie);
    drawPieChart('traff_tot_1', traffPie);
    drawPieChart('traff_tot_2', traffPie);
    drawMultiChart('clct_0', [], '수집건수(개)', 0, clctY, '수집원');
    drawPieChart('clct_tot_0', clctPie);
    drawBarChart(dbY, [], 'database', dataBaseFormat, '사용률(%)');
    drawBarChart(systemY, [], 'system', sysFormat, '가동률(%)');
    fetchBaseData();
    $('.img').on('click', ()=>fetchBaseData());

})

async function fetchBaseData(){
    clearInterval(interval);
    const all      = apiGet("/api/common/dashboard/traf-prcn-stat/traf-stts/all"); // 노드정보 요청
    const its      = apiGet("/api/common/stts/process/its"); // 링크정보 요청
    const stts     = apiGet("/api/common/stts/total"); // 링크정보 요청
    const database = apiGet("/api/common/stts/dbms"); // 도로정보 요청
    const incd     = apiGet("/api/manage/main/syst-opr/incd-ocrr")//
    $('.loading-box').css('display','flex');
    Promise.all([all, its, stts, database, incd])
    .then((results) => Promise.all(results.map((r) => r.json())))
    .then((values) => {
        recvDrawData(values[0]);
        recvPrcsData(values[1]);
        recvPrcsTotData(values[2]);
        recvDbData(values[3]);
        recvIncdData(values[4]);
        interval = setInterval(() => {  
          fetchBaseData();
        }, 5 * 60 * 1000);
    })
    .catch((err) => {
        console.error(`: Error in fetchBaseData ${err}`);
    })
    .finally(()=>{
      $('.loading-box').css('display','none');
    });
}

/**
 * 돌발 데이터 수신
 * @param {*} jsonData 수신 데이터
 */
function recvIncdData(jsonData){
    if (jsonData.length > 0) {
        jsonData.map((item)=>{
            if (item.rgst_dt) item.rgst_dt = getParseDateTime(item.rgst_dt);
            if (item.incd_strt_dt) item.incd_strt_dt = getParseDateTime(item.incd_strt_dt);
            if (item.incd_end_prar_dt) item.incd_end_prar_dt = getParseDateTime(item.incd_end_prar_dt);
        })
    }
    _incdList.option('dataSource', jsonData);
}

/**
 * 데이터베이스 데이터 수신
 * @param {*} jsonData 수신 데이터
 */
function recvDbData(jsonData) {
    let series = [
        {
            name : '여유공간',
            data : [],
            color : '#15B337',
        },
        {
            name : '사용공간',
            data : [],
            color : '#FF0000',
        },
    ];
    let categories = [];
    if (jsonData.length > 0) {
      jsonData.map((item, idx)=>{
          if (idx === 0 || idx === 1) {
            categories.push('Session' + (idx+1));
            series[0].data.push(Number((100 - Number(item.use_sesn)).toFixed(2)));
            series[1].data.push(Number(Number(item.use_sesn).toFixed(2)));
          }
          else  {
            categories.push(item.tbls_nm.replace('TS_ATMS_', ''));
            series[0].data.push(Number(Number(item.tbls_rmnd_cpct).toFixed(2)));
            series[1].data.push(Number((100 - Number(item.tbls_rmnd_cpct)).toFixed(2)));
          }
      })
      categories.push('TOTAL');
      series[0].data.push(Number(Number(jsonData[0].tbls_rmnd_cpct).toFixed(2)));
      series[1].data.push(Number((100 - Number(jsonData[0].tbls_rmnd_cpct)).toFixed(2)));
    }
    drawBarChart(series, categories, 'database', dataBaseFormat, '사용률(%)');
}

/**
 * 데이터베이스 chart label 포맷
 * @param {*} info chart 정보
 * @returns 포맷 정보
 */
function dataBaseFormat(info){
  let name = info.series.name;
  if (info.y >= 0){
      if (info.x.indexOf('Session') > -1) {
          name = name.replace('공간', '률');
          name = name.replace('여유', '미사용');
      }
      return '<b>'+ name +'</b><br>'
          + '비율 : <b>' 
          + info.y + '%'
          + '</b>';
  }
}

/**
 * 프로세스 전체 데이터 수신
 * @param {*} jsonData 수신 데이터
 */
function recvPrcsTotData(jsonData) {
    let fcltList = jsonData.fclt_list;
    sysY.map((item)=>{
      fcltList.map((obj)=>{
          if (obj.fclt_type === item.id) {
            let {error_cnt, normal_cnt} = obj;
              item.data = [error_cnt, normal_cnt];
          }
      })
    })

    let categories = [];
    let series = [
      {
          name  : '통신이상',
          data  : [],
          tot   : [],
          color : '#FF0000',
      },
      {
          name  : '정상',
          tot   : [],
          data  : [],
          color : '#15B337'
      },
    ];
    sysY.map((item)=>{
        categories.push(item.name);
        series[0].data.push(item.data[0]);
        series[1].data.push(item.data[1]);
        let tot = item.data[0] + item.data[1];
        series[0].tot.push(tot);
        series[1].tot.push(tot);
    })
    drawBarChart(series, categories, 'system', sysFormat, '가동률(%)');
}

/**
 * 프로세스 상태 정보 데이터 수신
 * @param {*} jsonData 수신 데이터
 */
function recvPrcsData(jsonData) {
  let totVal = 0;
  jsonData.map((item)=>{
      if (item.syst_stts_cd === "0") {
        totVal++;
      }
  })
  sysY[0].data = [jsonData.length - totVal, totVal];
}
/**
 * prcn_type (0/1/2 => 현재/어제/지난주)
 * 
 * clct(수집원 개수)
 * dsrc01  - DSRC
 * gits01  - 경기도
 * moct01  - 민간정보
 * prcn_tm - 가공시각
 * vds01   - VDS
 * rate_ltc0 - 현재 정보없음비율
 * rate_ltc1 - 현재 원활비율
 * rate_ltc2 - 현재 지체비율
 * rate_ltc3 - 현재 정체비율
 * traf(소통등급 개수) 
 * ltc0 - 정보없음갯수
 * ltc1 - 원활갯수
 * ltc2 - 지체갯수
 * ltc3 - 정체갯수
 * prcn_tm - 가공시각
 * @param {*} jsonData 
 */
function recvDrawData(jsonData){
    dataSorting(jsonData, 'traf.prcn_tm');
    let nowHh = new Date().getHours();
    if (jsonData && jsonData.length) {
        jsonData.map((item)=>{
            const traf  = item.traf;
            _strtIdx = 0;
            _endIdx  = 0;
            if (traf.length > 0 ) {
                dataSorting(traf, 'prcn_tm');
                if (nowHh <= 12) {
                    _strtIdx = 0;
                    _endIdx  = 144;
                }
                else {
                    let index = traf.findIndex(item => Number(item.prcn_tm.substring(0,2)) === nowHh);
                    _strtIdx = index - 72;
                    _endIdx  = index + 72;
                    if (_strtIdx >= 144) {
                        _strtIdx = 144;
                        _endIdx = 288;
                    }
                }
                traf.map((item)=>{
                    const prcnTm = item.prcn_tm;
                    item.prcn_tm = prcnTm.substring(0,2) + ":" + prcnTm.substring(2,4);
                });
                drawChart(traf, item.prcn_type, 'traff', item, _strtIdx, _endIdx);
            }
            const clct = item.clct;
            if (clct.length > 0) {
                dataSorting(clct, 'prcn_tm');
                clct.map((item)=>{
                    const prcnTm = item.prcn_tm;
                    item.prcn_tm = prcnTm.substring(0,2) + ":" + prcnTm.substring(2,4);
                })
                drawChart(clct, item.prcn_type, 'clct', item, _strtIdx, _endIdx);
            }
        })
    }
}

/**
 * column(%) chart 그리기
 * @param {*} series y축 데이터
 * @param {*} categories x축 데이터
 * @param {*} id 요소 id
 * @param {*} format label format 함수
 * @param {*} title y축 이름
 */
function drawBarChart(series, categories, id, format, title){
   
    Highcharts.chart(id, {
      chart: {
          type   : 'column',
          backgroundColor: {
              classNmae: 'dx-theme-background-color dx-theme-border-color',
          },
      },
      title: {
        text: '',
      },
      xAxis: {
          categories: categories,
          labels: {
            style: {
              color:  $('.dx-theme-material-typography').css('color'),
             // display : 'none',
            },
          },
      },
      yAxis: { // Primary yAxis
        min : 0,
        max : 100,
        tickInterval: 5,
        labels: {
              style: {
                  color:  $('.dx-theme-material-typography').css('color')
              }
          },
          title: {
              text: title,
              style: {
                  color:  $('.dx-theme-material-typography').css('color')
              }
          },
      },
      // tooltip: {
      //     shared: true,
      // },
      legend: {
          layout: 'vertical',
          align: 'right',
          verticalAlign: 'top',
          floating: false,
          visible : false,
          y: 30,
          borderWidth: 1,
          itemStyle:{
              color: $('.dx-theme-material-typography').css('color'),
          },
          backgroundColor: {
              className : 'dx-nav-item dx-theme-border-color',
          },
          shadow: false,
      },
      plotOptions: {
        column: {
          stacking: 'percent'
        }
      },
      series: series,
      exporting: {
          enabled: false,
      },
      credits: {
          enabled: false
      },
      tooltip: {
          formatter: function () {
              return format(this);
          }
        }
  });
}
function sysFormat(info){
  let name = info.series.name;
  let tot  = info.series.userOptions.tot[info.point.index];
  if (info.y >= 0){
      return '<b>'+ name +'</b><br>'
          + '비율 : <b>' 
          + (info.y/tot*100).toFixed(1) + '%'
          + '</b><br>'
          + '개수 : <b>' 
          + info.y
          + '</b>';
  }
}
/**
 * area chart 그리기
 * @param {*} id 요소 ID
 * @param {*} xAxis category
 * @param {*} yTitle y축 명칭
 * @param {*} tmIdx 현재 시각 index
 * @param {*} series chart series
 */
function drawAreaChart(id, xAxis, yTitle, tmIdx, series, label) {
      
  Highcharts.chart(id, {
    chart: {
        type   : 'area',
        backgroundColor: {
            classNmae: 'dx-theme-background-color dx-theme-border-color',
        },
    },
    title: {
      text: '',
    },
    xAxis: {
        categories: xAxis,
        labels: {
          style: {
            color:  $('.dx-theme-material-typography').css('color'),
            display : 'none',
          }
        },
        plotLines: [{
          color: '#eee',
          width: 2,
          value: tmIdx,
          dashStyle: 'dash',
          zIndex : 999,
      }],
    },
    yAxis: { // Primary yAxis
        labels: {
            style: {
            color:  $('.dx-theme-material-typography').css('color')
            }
        },
        title: {
            text: yTitle,
            style: {
            color:  $('.dx-theme-material-typography').css('color')
            }
        },
        tickInterval: 100,
    },
    tooltip: {
        shared: true,
    },
    legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'top',
        floating: false,
        visible : false,
        y: 30,
        borderWidth: 1,
        itemStyle:{
            color: $('.dx-theme-material-typography').css('color'),
        },
        backgroundColor: {
            className : 'dx-nav-item dx-theme-border-color',
        },
        shadow: false,
    },
    series: series,
    exporting: {
        enabled: false,
    },
    credits: {
        enabled: false
    },
    tooltip: {
        formatter: function () {
            let name = this.series.name;
            if (this.y >= 0){
                return '<b>' + label + '</b><br>'
                    + '시각 : <b>'
                    + this.x 
                    + '</b><br>'
                    + name + ' : <b>' 
                    + new Intl.NumberFormat('en-US').format(this.y)
                    + '</b>';
            }
        }
      }
});
}
function drawMultiChart(id, xAxis, yTitle, tmIdx, series, label){
  Highcharts.chart(id, {
    chart: {
        backgroundColor: {
            classNmae: 'dx-theme-background-color dx-theme-border-color',
        },
    },
    title: {
      text: '',
    },
    xAxis: {
        categories: xAxis,
        labels: {
          style: {
            color:  $('.dx-theme-material-typography').css('color'),
            display : 'none',
          }
        },
        plotLines: [{
          color: '#eee',
          width: 2,
          value: tmIdx,
          dashStyle: 'dash',
          zIndex : 999,
      }],
    },
    yAxis: [{ // Primary yAxis
        labels: {
            style: {
            color:  $('.dx-theme-material-typography').css('color')
            }
        },
        title: {
            text: yTitle,
            style: {
            color:  $('.dx-theme-material-typography').css('color')
            }
        },
        tickInterval: 10,
    },
    {
      labels: {
        style: {
        color:  $('.dx-theme-material-typography').css('color')
        }
        },
        title: {
            text: '',
            style: {
            color:  $('.dx-theme-material-typography').css('color')
            }
        },
        tickInterval: 1000,
        opposite: true,
    },
  ],
    tooltip: {
        shared: true,
    },
    legend: {
        //layout: 'vertical',
        //align: 'bottom',
        //verticalAlign: 'top',
        //y: 30,
        floating: false,
        visible : false,
        borderWidth: 1,
        itemStyle:{
            color: $('.dx-theme-material-typography').css('color'),
        },
        backgroundColor: {
            className : 'dx-nav-item dx-theme-border-color',
        },
        shadow: false,
    },
    series: series,
    exporting: {
        enabled: false,
    },
    credits: {
        enabled: false
    },
    tooltip: {
        formatter: function () {
            let name = this.series.name;
            if (this.y >= 0){
                return '<b>' + label + '</b><br>'
                    + '시각 : <b>'
                    + this.x 
                    + '</b><br>'
                    + name + ' : <b>' 
                    + new Intl.NumberFormat('en-US').format(this.y)
                    + '</b>';
            }
        }
      }
});
}
function drawChart(data, type, column, rate, strt, end) {
    let id;
    let id2;
    let label;
    let yTitle;
    let series = [];
    let pieSeries = [];
    // let array = _drawMap.get(column);
    // console.log(array);
    // console.log(_drawMap.get(column + '_id'));
    // console.log(_drawMap.get(column + '_id2'));
    // console.log(_drawMap.get(column + '_label'));
    // console.log(_drawMap.get(column + '_title'));
    // console.log(_drawMap.get(column + '_title'));
    if (column === 'traff') {
        traffArr.map((item)=>{
                series.push({...item, data:[], showInLegend: false,});
                pieSeries.push({...item, y:0});
        })
        
        id     = column + '_' + type;
        id2    = column + '_tot_' + type;
        label  = '교통 상황';
        yTitle = '개수';
        pieSeries.map((item)=>{
            item.y = rate['rate_' + item.id];
        })
    }
    else if (column === 'clct') {
        clctArr.map((item)=>{
            if (item.id === 'moct01') {
              series.push({...item, data:[], type : 'area', yAxis : 1});
            }
            else {
              series.push({...item, data:[], type : 'line'});
            }
            pieSeries.push({...item, y:0});
        })
        id  = column + '_' + type;
        id2 = column + '_tot_' +type;
        label = '수집원';
        yTitle = '수집건수(개)';
        pieSeries.map((item)=>{
            item.y = rate[item.id];
        })
    }
    let xAxis = [];

    let hh = timeFormmater(new Date().getHours());
    let mm = timeFormmater(new Date().getMinutes());
    if (Number(mm)%5) {
        mm = timeFormmater(mm - Number(mm)%5);
    }
    let time = hh  + ':' + mm;
    let tmIdx = 0;
    data.map((item, idx)=>{
        if (idx >= strt && idx <= end) {
            series.map((obj)=>{
                obj.data.push(item[obj.id]);
            })
            xAxis.push(item.prcn_tm);
            if (time === item.prcn_tm) {
              tmIdx = xAxis.length - 1;
            }
        }
    });
    if (column === 'traff') {
        drawAreaChart(id, xAxis, yTitle, tmIdx, series, label);
    }
    else {
        drawMultiChart(id, xAxis, yTitle, tmIdx, series, label);
    }
    drawPieChart(id2, pieSeries);
}
function drawPieChart(id, pieSeries) {
    Highcharts.chart(id, {
      chart: {
          backgroundColor: {
              classNmae: 'dx-theme-background-color dx-theme-border-color',
          },
          animation: Highcharts.svg,
          plotShadow: false,
          type: 'pie',
      },
      title: {
          text : '',
          style: {
              color: 'rgb(139 138 139)',
              fontSize: 13.9,
              fontWeight: 'bold',
              left:100,
          }
      },
      tooltip: {
          pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
      },
      legend: {
          enabled:false,
          itemStyle:{
              color: "rgb(139 138 139)",
              
          },
          itemHoverStyle: {
              color: 'black'
          },
          itemHiddenStyle: {
              color: 'rgb(55 55 65)'
          },
          layout: 'vertical',
          align: 'right',
          verticalAlign: 'middle'
      },
      // accessibility: {
      //     point: {
      //         valueSuffix: '%'
      //     }
      // },
      plotOptions: {
          pie: {
              size: '120%',
              allowPointSelect: true,
              cursor: 'pointer',
              dataLabels: {
                  enabled: true,
                  format: "<strong>{point.name}</strong><br>{point.percentage:.1f}",
                  distance: -10,
                  color: "white",
                  filter: {
                      property: 'percentage',
                      operator: '>',
                      value: 4
                    }
              },
          }
      },
      exporting: {
          enabled: false,
      },
      credits: {
          enabled: false
      },
      series: [
          {
              name : '',
              data : pieSeries,
          }
      ],
  });
}
function now() {
    let now = new Date();
    let timeVal = "";
    let yy  = now.getFullYear();
    let MM  = timeFormmater(now.getMonth()+1);
    let dd  = timeFormmater(now.getDate());
    let hh  = timeFormmater(now.getHours());
    let mm  = timeFormmater(now.getMinutes());
    let ss  = timeFormmater(now.getSeconds());
    timeVal = yy + "년 " + MM + "월 " + dd + "일 " + hh + ":" + mm + ":" + ss;
    return timeVal;
}

function timer() {
    setInterval(() => {
        time.text(now());
    }, 1000);
}
