<template>
  <div>
    <base-header class="pb-6 pb-8 pt-5 pt-md-8 bg-gradient-success">
      <!-- Card stats -->
      <b-row>
        <div class ="col-md-4 col-xl-9">
          <b-form-select v-model="selected" :options="options"></b-form-select>
        </div>
        <base-button type="default" class ="col-md-1 col-xl-1" @click="sendMessage">조회</base-button>
        <base-button type="danger" class ="col-md-1 col-xl-1" @click="sendReloadMessage">REROAD</base-button>
        

      </b-row>
    </base-header>
    <b-container fluid class="mt--7">
      <b-row>
        <b-col>
          <!--<light-table/>-->
          <b-card >
              <b-card-header class="border-0">
                  <h3 class="mb-4">{{ tableNm }}</h3>
                  <el-input v-model="search" size="small" placeholder="Type to search" />
              </b-card-header>                    
              <el-table class="table-responsive table"
                  header-row-class-name="thead-light" :data="filterTableData" :height="600" style="width: 100%;">
                <el-table-column v-for="(key, index) in uniqueKeys" :key="index" :prop="key" :label="key" width="180" />  
              </el-table>              
              <b-card-footer class="py-4 d-flex justify-content-end">
                  <base-pagination v-model="currentPage" :per-page="10" :total="50"></base-pagination>
              </b-card-footer>              
          </b-card>          
        </b-col>
      </b-row>            
    </b-container>
  </div>
</template>
<script>
  import { Dropdown, DropdownItem, DropdownMenu, Table, TableColumn } from 'element-ui';
  import projects from './Tables/projects'
  import users from './Tables/users'
  import LightTable from "./Tables/RegularTables/LightTable";
  import DarkTable from "./Tables/RegularTables/DarkTable";

  export default {
    components: {
      LightTable,
      DarkTable,
      [Dropdown.name]: Dropdown,
      [DropdownItem.name]: DropdownItem,
      [DropdownMenu.name]: DropdownMenu,
      [Table.name]: Table,
      [TableColumn.name]: TableColumn
    },
    data() {
      return {
        projects,
        users,
        //message: {"COMMAND":"SOCKET_SET","DATA_LIST":"toolInitList"}, 
        message: {"COMMAND":"SOCKET_SET"}, 
        tableData : [],
        tableNm:'',       
        uniqueKeys : [],
        currentPage: 1, // currentPage를 추가하고 초기 값으로 1을 설정
        search : '',     
        selected: null,
        options: [],    
      };
    },
    mounted() {
      if(this.isConnected){
        this.sendMessage();
      }
    },    
    computed: {
      currentMessage() {
        return this.$store.state.websocket.socket.currentMessage;  // state 접근
      },
      isConnected() {
        return this.$store.state.websocket.socket.isConnected;
      },      
      filterTableData(){
        if(!this.search){
          return this.tableData;
        } else {
          return this.tableData.filter(row => 
            this.uniqueKeys.some(key => 
              String(row[key]).toLowerCase().includes(this.search.toLowerCase())
            )
          )
        }        
      }   
    },    
    methods: {
      sendMessage() {
        const uniqueMessageId = 'id' + Math.random().toString(8).substr(2, 8); // Unique ID 생성. 실제 애플리케이션에서는 더 견고한 방법을 사용해야 합니다.
        this.message.WORK_VALUE = uniqueMessageId; // 메시지에 ID 포함
        this.message.EXECUTE = "SOCKET_SELECT_LIST";
        this.message.DATA_LIST = (this.selected == null) ? '':this.selected;        
        console.log(this.message);
        this.$store.commit('websocket/registerRequest', uniqueMessageId); // 요청 등록
        this.$store.dispatch('websocket/sendMessage', this.message); // 메시지 전송        
      },
      sendReloadMessage() {                
        this.message.EXECUTE = "INIT_RELOAD";
        this.message.DATA_LIST = (this.selected == null) ? '':this.selected;        
        console.log(this.message);        
        this.$store.dispatch('websocket/sendMessage', this.message); // 메시지 전송        
      },      
    },
    watch: {
      currentMessage(newMessage) {
        if (newMessage && this.$store.getters['websocket/isResponseForRequest'](newMessage.WORK_VALUE)) {
          // 이 메시지가 이 컴포넌트에서 보낸 요청에 대한 응답이라면
          // 여기에서 응답 처리 로직을 작성합니다.
          console.log(newMessage.DATA_LIST);
          console.log(typeof(newMessage.DATA_LIST));
          try {            
            var dataList = JSON.parse(newMessage.DATA_LIST);            
          } catch (e) {
            console.log("형식이 다릅니다. : " +  newMessage.DATA_LIST);
            this.tableNm = newMessage.DATA_LIST;
          }
          this.tableNm = (dataList == null || dataList.length == 0)? 'NO DATA': this.tableNm = this.selected;
          this.tableData = dataList;

          //목록이 있으면 해당 목록 가져오고 없으면 목록 업데이트 
          if(this.options.length == 0){        
            dataList.forEach((map, index) => {              
              var tempMap = {"value": map.fieldNm,"text": map.fieldNm};
              this.options.push(tempMap);
          });
          }


          //console.log(Object.keys(JSON.parse(newMessage.DATA_LIST)));
          this.uniqueKeys = new Set();
            this.uniqueKeys = Array.from(
                dataList.reduce((keySet, obj) => {
                    Object.keys(obj).forEach(key => keySet.add(key));
                    return keySet;
                }, new Set())
            );
          
          //console.log(this.tableData);
          //console.log(Array.from(uniqueKeys));
          
          this.$store.commit('websocket/unregisterRequest', newMessage.WORK_VALUE);          
        }
      },
    }, 
  };
</script>

<style>
.el-table.table-dark{
  background-color: #172b4d;
  color: #f8f9fe;
}

.el-table.table-dark th,
.el-table.table-dark tr{
  background-color: #172b4d;
}

.el-table.table-dark td,
.el-table.table-dark th.is-leaf{
  border-bottom: none;
}
</style>
