<template>
  <footer class="footer">
    <div class="foot-connection">
      <strong>Connection</strong>
      <span>OK</span>
    </div>
    <div class="foot-numbering">
      <span class="num1">{{eventState.critical}}</span>
      <span class="num2">{{eventState.major}}</span>
      <span class="num3">{{eventState.minor}}</span>
    </div>
    <div class="foot-state" v-show="eventState.latestSeverity">{{eventState.latestSeverity}}</div>
    <p class="foot-txt">
      <!-- Sbi-0-chosim[server]-198 HTTP2 CONNECTION ALARM (sysId=821, rsysId=198, rsysId=198, rsysName=AMF[server]) -->
      {{eventState.latestCause +' '+eventState.latestLocation}}
    </p>
    <div class="foot-btn-wrap">
      <!-- <button><i class="ico ico1"></i>Event View</button> -->
      <button class="evt-view" @click="fnEventView()"><i class="ico ico1"></i>Event View</button>
    </div>
    <span class="foot-logo">SAMSUNG SDS</span>
  </footer>
  <!-- 이벤트 이력 -->
  <div class="footer--dialog" :class="[eventViewPop == true ? 'active' : '']">
    <div class="footer--dialog--after"></div>
    <div class="v-common-dialog-wrapper custom-dialog">
      <div class="modal-tit">
        <strong>이벤트 이력</strong>
        <span class="bar"></span>
        <v-switch v-model="curAlarm" label="CURRENT ALARM" hide-details></v-switch>
        <div class="select-on">
          <v-btn class="custom-btn btn-blue btn-evt mini" :disabled="!curAlarm" @click="fnClearAlarmConfirm()" v-if="selectedItem.length"><i class="ico"></i>알람 해제</v-btn>
          <v-checkbox class="custom-check type2" hide-details v-if="selectedItem.length" readonly v-model="defaultCheckbox" style="pointer-events:none;">
            <template v-slot:label>
              목록 <span class="strong">{{selectedItem.length}}</span>건 선택
            </template>
          </v-checkbox>
        </div>
        <div class="btn-wrap">
          <v-btn class="custom-btn mini btn-white btn-pip" @click="fnEventViewOpenPop()"><i class="ico"></i>전체 보기</v-btn>
          <v-btn class="custom-btn btn-white mini" @click="fnReset()" v-if="!curAlarm"><i class="ico"></i>초기화</v-btn>
          <v-btn class="custom-btn btn-gray mini" @click="fnFixWindow()"><i class="ico"></i>창 고정</v-btn>
        </div>
      </div>
      <div class="modal-cont">
        <div class="tbl-wrapper">
          <div class="tbl-wrap">
            <ag-grid-vue
              style="width:100%; height:calc(50vh - 7.13rem)"
              class="ag-theme-quartz"
              :gridOptions="gridOptions"
              :columnDefs="getHeaders"
              :defaultColDef="defaultColDef"
              :rowData="listObj.rowData"
              :suppressPaginationPanel="true"
              :suppressScrollOnNewData="true"
              @selection-changed="fnOnSelectChange"
              @rowClicked="fnRowClick"
              @grid-ready="fnOnGridReady"
            >
            </ag-grid-vue>
          </div>
        </div>
      </div>
      <div class="foot-btn-wrap">
        <button class="evt-view" @click="fnEventView()"><i class="ico ico1"></i>Event View</button>
      </div>
    </div>
  </div>
  <!-- 이벤트 이력 상세 정보 -->
  <eventDetailView ref="refEventDetailView" :isEventDetailModal="isEventDetailModal" :eventDetailData="eventDetailData" :currentAlarmYn="curAlarm" @closeModal="fnCloseEventDetailModal"/>
</template>

<script setup>
import customNullValue from '@/components/cellRenderer/customNullValue.vue';
import "ag-grid-community/styles/ag-grid.css"; // Mandatory CSS required by the Data Grid
import "ag-grid-community/styles/ag-theme-quartz.css"; // Optional Theme applied to the Data Grid
import { AgGridVue } from "ag-grid-vue3"; // Vue Data Grid Component
import { useI18n } from 'vue-i18n';
import eventDetailView from './footer/eventDetailView.vue';
  /***********************
  *     plugins inject
  ************************/
  const {$toast, $log, $dayjs, $eventBus } = useNuxtApp()
  const i18n = useI18n()
  
  /***********************
  *     data & created
  ************************/
  const pageId = 'footer'
  const eventClientId = ref('')
  const eventState = ref({
    critical: 0,
    major: 0,
    minor: 0,
    warning: 0,
    latestCause: '',    // 최근발생이벤트 원인
    latestLocation: '', // 최근발생이벤트 위치
    latestSeverity: ''  // 최근발생이벤트 심각도
  })
  const eventInterval = ref(null)
  const curAlarm = ref(false)
  const gridApi = shallowRef()  // Grid Api
  const remToPx = () => parseFloat(getComputedStyle(document.documentElement).fontSize);
  const rowHeightRem = 3.125; // 원하는 rem 값
  const rowHeightPx = rowHeightRem * remToPx();
  // grid default 옵션
  const defaultColDef = ref({
    lockVisible: true, // 열을 그리드 밖으로 꺼내지 않음
  })
  let listObj = ref({
    currentData: [],
    eventData: [],
    rowData: []
  })
  const objSlt = ref({
    eventTypeList: [],
    severityList: [],
    alarmGroupList: [],
    alarmStateList: []
  })

  const getHeaders = computed(() => {
    let headers = [
      { field: "no", headerName: "No", width:100, cellRenderer: customNullValue},
      { field: "eventType", headerName: "이벤트 유형", width:130, cellRenderer: customNullValue},
      { field: "eventCode", headerName: "이벤트 코드", width:130, cellRenderer: customNullValue},
      { field: "severity", headerName: "심각도", width:130, cellRenderer: fnSeverityRenderer},
      { field: "alarmGroup", headerName: "알람 그룹", cellRenderer: customNullValue},
      { field: "location", headerName: "위치", cellRenderer: customNullValue},
      { field: "probcause", headerName: "발생 원인", cellRenderer: customNullValue},
      { field: "alarmTime", headerName: "발생 시간", cellRenderer: customNullValue},
      { field: "clearTime", headerName: "해제 시간", cellRenderer: customNullValue},
      { field: "alarmState", headerName: "상태", cellRenderer: customNullValue}
    ]
    if(curAlarm.value){
      headers.unshift({ field: "checkbox", headerName: "", checkboxSelection: true, headerCheckboxSelection: true,
      showDisabledCheckboxes: true, //비활성화 체크박스 보이게 설정
      width:50, checkboxSelection: params => {
        let activeState = ['Uncleared', 'Audit', 'Unack', 'Ack']
        let isCheckBoxStatus = (params.data.neId === -1 && params.data.eventType === 'Alarm' && _includes(activeState, params.data.alarmState))
        return isCheckBoxStatus // alarmState가 'Uncleared'일 경우만 체크박스 활성화
      }
      })
    }
    return headers
  })
  const gridOptions = {
    columnDefs: getHeaders.value,
    rowData: listObj.value.rowData,      // 테이블 데이터
    rowSelection : 'multiple',
    suppressMovableColumns: false,
    autoSizeStrategy: {
      type: "fitGridWidth", // width맞춤
    },
    headerHeight : rowHeightPx,
    rowHeight: rowHeightPx,
    pagination: false,
    suppressPaginationPanel: true,    // 하단 default 페이징 컨트롤 숨김
    suppressRowClickSelection: true,  // 행 클릭 체크박스 무시
    localeText: {
      noRowsToShow: i18n.t('common.noData')
    },
    isRowSelectable: (rowNode) => {
      // 나이가 30 미만이면 체크박스 비활성화
      let activeState = ['Uncleared', 'Audit', 'Unack', 'Ack']
      let isCheckBoxStatus = (rowNode.data.neId === -1 && rowNode.data.eventType === 'Alarm' && _includes(activeState, rowNode.data.alarmState))
      return isCheckBoxStatus
    }
    // onRowSelected: (event) => {
    //   // 조건에 따라 선택 비활성화 처리
    //   if (event.node.data.neId === -1 && event.node.data.eventType === 'Alarm') {
    //     //console.log(event.node.data.neId)
    //     //console.log(event.node.data.eventType)
    //     // 선택 비활성화
    //     event.node.setSelected(false)
    //   }
    // },
    // onSelectionChanged: () => {
    //   const selectedNodes = gridOptions.api.getSelectedNodes()
    //   console.log(selectedNodes)
    //   selectedNodes.forEach(node => {
    //     console.log(node.data.neId)
    //     // if (node.data.age < 30) {
    //     //   gridOptions.api.deselectNode(node); // 선택 해제
    //     // }
    //   })
    // }
  }

  let eventViewPop = ref(false);          // 이벤트 이력 팝업
  const eventDetailData = ref({})         // 이벤트뷰어 상세 데이터
  const refEventDetailView = ref(null)    // 이벤트뷰어 상세 ref 참조
  const isEventDetailModal = ref(false)   // 이벤트뷰어 상세 모달
  const getEventTypeText = computed(() => {
    return (val) => {
    if(!useUtil.isNull(val) && val !== '-') {
      let titleValue = useUtil.nvl(_find(objSlt.value.eventTypeList, { value: val }), '-')
        return titleValue.title
      }else{
        return val
      }
    }
  })
  const getSeverityText = computed(() => {
    return (val) => {
    if(!useUtil.isNull(val) && val !== '-') {
      let titleValue = useUtil.nvl(_find(objSlt.value.severityList, { value: val }), '-')
        return titleValue.title
      }else{
        return val
      }
    }
  })
  const getAlarmGroupText = computed(() => {
    return (val) => {
    if(!useUtil.isNull(val) && val !== '-') {
      let titleValue = useUtil.nvl(_find(objSlt.value.alarmGroupList, { value: val }), '-')
        return titleValue.title
      }else{
        return val
      }
    }
  })
  const getAlarmStateText = computed(() => {
    return (val) => {
    if(!useUtil.isNull(val) && val !== '-') {
      let titleValue = useUtil.nvl(_find(objSlt.value.alarmStateList, { value: val }), '-')
        return titleValue.title
      }else{
        return val
      }
    }
  })
  let fixWindowYN = ref((useUtil.nvl(localStorage.getItem('eventViewFix'), 'N')))
  if(fixWindowYN.value === 'Y') {
    eventViewPop.value = true
  } else {
    eventViewPop.value = false
  }
  const selectedItem = ref([])        // 선택한항목 리스트
  const defaultCheckbox = ref(true)   // ..건 선택 체크박스 상태

  watchEffect(() =>{
    // 감시하고자 하는 데이터를 해당 블럭내에서 사용하면 호출된다.
    // getLang.value를 감시하는 상태
    fnGetEnumCode(useLangStore().getLang)
  })

  watch(() => curAlarm.value, (newV, oldV) => {
    fnGetEventViewer()
  },{ deep: true, immediate: false })

  onMounted(() => {
    if(!useUtil.isNull(eventInterval.value)) {
      clearInterval(eventInterval.value)
    }

    fnGetEventViewer()

    eventInterval.value = setInterval(() => {
      fnGetEventViewer()
    }, 5000)
    //}, 1000 * 30)
  })

  $eventBus.off('SET_FOOTER')
  $eventBus.on('SET_FOOTER', () => {
    //console.log('%c [SET_FOOTER]' ,'color:#bada55')
    clearInterval(eventInterval.value)
  })

  $eventBus.off('DELETE_CLEAR_ALARM')
  $eventBus.on('DELETE_CLEAR_ALARM', () => {
    fnClearAlarm()
  })
  /***********************
  *     Methods
  ************************/
  /**
   * @SCRIPT
   * ENUM 업데이트
   * @param lang
   */
  function fnGetEnumCode(lang){
    lang = useUtil.nvl(lang, 'kr')
    let objEnum = useEnumCode.getEnumCode(lang)

    objSlt.value.alarmStateList = [...objEnum.alarmState]
    objSlt.value.alarmGroupList = [...objEnum.alarmGroup]
    objSlt.value.severityList = [...objEnum.severity]
    objSlt.value.eventTypeList = [...objEnum.eventType]
  }

  /**
   * @SCRIPT
   * 이벤트뷰어 리스트 단건 클릭 이벤트
   */
  function fnRowClick(params){
    eventDetailData.value = params.data
    isEventDetailModal.value = true
    // 데이터 초기화
    refEventDetailView.value.fnInit()
  }

  /**
   * @SCRIPT
   * 이벤트뷰어 상세페이지 닫기
   */
  function fnCloseEventDetailModal() {
    isEventDetailModal.value = false
  }

  /**
   * @SCRIPT
   * Grid 데이터 바인딩
   */
  function fnOnGridReady(params){
    gridApi.value = params.api
    // gridApi.value.api.setRowData(rowData.value);
    //fnGetLoginHistory()
  }

  /**
   * @SCRIPT
   * 초기화 버튼 이벤트
   */
  function fnReset() {
    gridApi.value.setGridOption('rowData', [])
  }

  /**
   * @SCRIPT
   * 창 고정 버튼 이벤트
   */
  function fnFixWindow() {
    if(fixWindowYN.value === 'Y') {
      fixWindowYN.value = 'N'
      eventViewPop.value = false
      localStorage.setItem('eventViewFix', 'N')
    } else {
      fixWindowYN.value = 'Y'
      eventViewPop.value = true
      localStorage.setItem('eventViewFix', 'Y')
    }
  }

  /**
   * @SCRIPT
   * 이벤트뷰어 활성화 이벤트
   */
  function fnEventView() {
    if(fixWindowYN.value === 'N') {
      // 창고정이 꺼져있는경우
      if(eventViewPop.value) {
        eventViewPop.value = false
      } else {
        eventViewPop.value = true
      }
    } else {
      eventViewPop.value = true
    }
  }

  /**
   * @SCRIPT
   * 체크박스 선택 시 이벤트
   */
  function fnOnSelectChange() {
    const selectedRows = gridApi.value.getSelectedRows()
    let arrData = []
    selectedRows.forEach((row) => {
      arrData.push(row)
    })
    selectedItem.value = arrData
  }

  /**
   * @SCRIPT
   * 이벤트뷰어 윈도우 팝업 이벤트
   */
  //  const eventAllPop = () => { // 이벤트 이력 전체 보기
  //   window.open("/design/evtHisPip", "_blank", "width=");
  //   components\common\footer\eventViewWindowPop.vue
  // }
  function fnEventViewOpenPop() {
    const width = window.screen.width
    const height = window.screen.height
    const url = window.location.origin+'/view/home/eventView/eventViewWindowPop'
    const popupWindow = window.open(url, '_blank', `width=${width},height=${height},top=0,left=0`)
    
    if (popupWindow) {
      popupWindow.focus()
    }
    // 전체보기에 대한 이벤트 처리
    // popupWindow.onload = function () {
    //   let dataObj = []
    //   console.log(':::::::::::::fnEventViewOpenPop:::::::::::::')
    //   dataObj = listObj.value.currentData
    //   dataObj.clientId = eventClientId.value
    //   //dataObj.clientId = eventClientId.value
    //   console.log(dataObj)
    //   popupWindow.postMessage({message: JSON.stringify(dataObj)}, '*')
    // }
  }

  /**
   * @API
   * event viewer
   */
  function fnGetEventViewer(){
    let _req = {}
    _req.clientId = useUtil.nvl(eventClientId.value, -1)

    useAxios().post(useApi.eventViewer, _req).then((res) => {
    //fetch('/test.json').then(response => response.json()).then(res => {
      let temp = []
      let currentTotalCnt = 0
      let eventTotalCnt = 0
      let resClientId = res.data.data.clientId
      let curAlarm = res.data.data.curAlarm // {critical: 0, major: 0, minor: 0, warning: 0}
      let currentList = res.data.data.curAlarms
      let eventList = res.data.data.events
      eventTotalCnt = eventList.length
      currentTotalCnt = currentList.length
      eventClientId.value = resClientId

      // 상태값 데이터 셋팅
      eventState.value = {
        critical: curAlarm.critical,
        major: curAlarm.major,
        minor: curAlarm.minor,
        warning: curAlarm.warning,
        latestCause: useUtil.nvl(curAlarm.latestCause, ''),
        latestLocation: useUtil.nvl(curAlarm.latestLocation, ''),
        latestSeverity: curAlarm.latestSeverity
      }

      // CURRENT ALARM 활성화 시 보여질 데이터셋팅 실시간으로 값이 쌓이는 형식
      if(currentTotalCnt > 0) {
        currentList.forEach((item, idx) => {
          let obj = {}
          obj.no = idx + 1
          obj.seqNo = useUtil.nvl(item.seqNo, '-')
          obj.neId = useUtil.nvl(item.neId, '-')
          obj.neName = useUtil.nvl(item.neName, '-')
          obj.neGroup = useUtil.nvl(item.neGroup, '-')
          obj.emsName = useUtil.nvl(item.emsName, '-')
          obj.location = useUtil.nvl(item.location, '-')
          obj.eventCode = useUtil.nvl(item.eventCode, '-')
          obj.probcause = useUtil.nvl(item.probcause, '-')
          obj.tenantName = useUtil.nvl(item.tenantName, '-')
          obj.clearUser = useUtil.nvl(item.clearUser, '-')
          obj.clearSystem = useUtil.nvl(item.clearSystem, '-')
          obj.clearType = useUtil.nvl(item.clearType, '-')
          obj.ackTime = useUtil.nvl(item.ackTime, '-')
          obj.ackUser = useUtil.nvl(item.ackUser, '-')
          obj.ackSystem = useUtil.nvl(item.ackSystem, '-')
          obj.modifyUser = useUtil.nvl(item.modifyUser, '-')
          obj.modifySystem = useUtil.nvl(item.modifySystem, '-')
          obj.additionalText = useUtil.nvl(item.additionalText, '-')
          obj.eventType = getEventTypeText.value(item.eventType)
          obj.severity = getSeverityText.value(item.severity)
          obj.alarmGroup = getAlarmGroupText.value(item.alarmGroup)
          obj.alarmState = getAlarmStateText.value(item.alarmState)
          obj.alarmTime = useUtil.fnNullCheckFormatDate(item.alarmTime)
          obj.clearTime = useUtil.fnNullCheckFormatDate(item.clearTime)
          temp.push(obj)
        })
        listObj.value.currentData = _cloneDeep(temp)
      }

      // CURRENT ALARM 비활성화 시 보여질 이벤트데이터 셋팅 실시간으로 값이 쌓이는 형식
      if(eventTotalCnt > 0) {
        eventList.forEach((item) => {
          let obj = {}
          obj.no = 0
          obj.seqNo = useUtil.nvl(item.seqNo, '-')
          obj.neId = useUtil.nvl(item.neId, '-')
          obj.neName = useUtil.nvl(item.neName, '-')
          obj.neGroup = useUtil.nvl(item.neGroup, '-')
          obj.emsName = useUtil.nvl(item.emsName, '-')
          obj.location = useUtil.nvl(item.location, '-')
          obj.eventCode = useUtil.nvl(item.eventCode, '-')
          obj.probcause = useUtil.nvl(item.probcause, '-')
          obj.tenantName = useUtil.nvl(item.tenantName, '-')
          obj.clearUser = useUtil.nvl(item.clearUser, '-')
          obj.clearSystem = useUtil.nvl(item.clearSystem, '-')
          obj.clearType = useUtil.nvl(item.clearType, '-')
          obj.ackTime = useUtil.nvl(item.ackTime, '-')
          obj.ackUser = useUtil.nvl(item.ackUser, '-')
          obj.ackSystem = useUtil.nvl(item.ackSystem, '-')
          obj.modifyUser = useUtil.nvl(item.modifyUser, '-')
          obj.modifySystem = useUtil.nvl(item.modifySystem, '-')
          obj.additionalText = useUtil.nvl(item.additionalText, '-')
          obj.eventType = getEventTypeText.value(item.eventType)
          obj.severity = getSeverityText.value(item.severity)
          obj.alarmGroup = getAlarmGroupText.value(item.alarmGroup)
          obj.alarmState = getAlarmStateText.value(item.alarmState)
          obj.alarmTime = useUtil.fnNullCheckFormatDate(item.alarmTime)
          obj.clearTime = useUtil.fnNullCheckFormatDate(item.clearTime)
          listObj.value.eventData.unshift(obj)
        })
      }
      // 최종 데이터 가공
      fnSetData()
      $log.debug("[footer][fnGetEventViewer][success]")
    }).catch((error)=>{
      $log.debug("[footer][fnGetEventViewer][error]")
      useErrorHandler().fnSetCommErrorHandle(error, fnGetEventViewer)
    }).finally(()=>{
      $log.debug("[footer][fnGetEventViewer][finished]")
    })
  }

  /**
   * @API_REF
   * 조회 API 최종 가공 데이터
   */
  function fnSetData() {
    listObj.value.rowData = []
    if(curAlarm.value) {
      // currentAlarm이 활성화 되어있는 경우
      listObj.value.rowData = listObj.value.currentData
    } else {
      _each(listObj.value.eventData, (item, idx) => {
        item.no = idx + 1
      })
      listObj.value.rowData = listObj.value.eventData
    }
    gridApi.value.setGridOption('rowData', listObj.value.rowData)
  }

  /**
   * @API_REF
   * 데이터 가공 참조
   */
  function fnSeverityRenderer(params) {
    // Critical, Major, Minor, Warning, Normal
    let _cls = ''
    if(!useUtil.isNull(params.value) && params.value !== '-') {
      _cls = params.value == 'Critical' ? 'critical' : params.value == 'Major' ? 'major' : params.value == 'Minor' ? 'minor' : params.value == 'Warning' ? 'minor' : 'minor'
    }
    let el = `<span class="status--ele ${_cls}" title="${params.value}">${params.value}</span>`
    return el
  }
  /**
   * @API_REF
   * 알람해제 confirm
   */
  function fnClearAlarmConfirm() {
    if(selectedItem.value.length > 0){
      let contents = i18n.t('common.footer.eventView.clearAlarmConfirmMsg')
      let param = {
        id: pageId,
        title: '안내',
        content: contents,
        yes:{
          text: i18n.t('common.confirm'),
          isProc: true,
          event:'DELETE_CLEAR_ALARM',
          param:  ''
        },
        no:{
          text: i18n.t('common.cancel'),
          isProc:false
        }
      }
      $eventBus.emit('OPEN_CONFIRM_POP_UP', param)
    }
  }
  /**
   * @API
   * 알람해제
   */
  function fnClearAlarm() {
    let clearNumbers = selectedItem.value.map(item=>item.seqNo).join(',')
    let _req = {
      seqNo: clearNumbers,
      clearUser: useAuthStore().getAccountId
    }
    useAxios().put(useApi.clearAlarm, _req).then((res) => {
      $log.debug("[footer][fnClearAlarm][success]")
      $toast.success('선택한 알람이 해제 되었습니다.')
      fnGetEventViewer()
    }).catch((error)=>{
      $log.debug("[footer][fnClearAlarm][error]")
      $toast.error('선택한 알람 해제를 실패하였습니다.')
      useErrorHandler().fnSetCommErrorHandle(error)
    }).finally(()=>{
      $log.debug("[footer][fnClearAlarm][finished]")
    })
  }
</script>