<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-10">
          <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>
        
        

      </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" :default-sort="{ prop: 'SK_ID', order: 'descending' }"
                  header-row-class-name="thead-light" :data="filterTableData" :height="600" style="width: 100%;">
                  <el-table-column sortable fixed prop="SK_ID" label="SK_ID" width="180" />
                <el-table-column v-for="(key, index) in uniqueKeys" :key="index" :prop="key" :label="key" width="180" />  
                <el-table-column fixed="right" label="Option" width="120">
                  <template #default="scope">
                    <b-button style ="padding:0.20rem 0.20rem" variant="link" @click="handleClick(scope.$index, scope.row)"> Detail </b-button>
                  </template>
                </el-table-column>                
              </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>
    <b-modal ref="my-modal" size="xl" hide-footer title="Using Component Methods">
      <div class="d-block">
        <b-tabs content-class="mt-3" fill>
          <b-tab title="INFO" active>              
            <form class="row g-3">
              <div class="col-md-4">
                <label for="inputEmail4" class="form-label">SK_ID</label>
                <input type="text" v-model="this.selectMap.SK_ID" class="form-control" >
              </div>
              <div class="col-md-4">
                <label for="inputPassword4" class="form-label">SK_CONN_TYPE</label>
                <input type="text" v-model="this.selectMap.SK_CONN_TYPE" class="form-control" >
              </div>
              <div class="col-md-4">
                <label for="inputEmail4" class="form-label">PKG_ID</label>
                <input type="text" v-model="this.selectMap.PKG_ID" class="form-control" >
              </div>
              <div class="col-md-4">
                <label for="inputPassword4" class="form-label">SK_IP</label>
                <input type="text" v-model="this.selectMap.SK_IP" class="form-control" >
              </div>     
              <div class="col-md-4">
                <label for="inputPassword4" class="form-label">SK_PORT</label>
                <input type="text" v-model="this.selectMap.SK_PORT" class="form-control" >
              </div>                                                               
              <div class="col-md-4">
                <label for="inputPassword4" class="form-label">SK_TYPE</label>
                <input type="text" v-model="this.selectMap.SK_TYPE" class="form-control" >
              </div>    
              <div class="col-md-4">
                <label for="inputPassword4" class="form-label">PARENT_SK_ID</label>
                <input type="text" v-model="this.selectMap.PARENT_SK_ID" class="form-control" >
              </div>       
              <div class="col-md-4">
                <label for="inputPassword4" class="form-label">SK_DELIMIT_TYPE</label>
                <input type="text" v-model="this.selectMap.SK_DELIMIT_TYPE" class="form-control" >
              </div>                     
              <div class="col-md-4">
                <label for="inputPassword4" class="form-label">MAX_LENGTH</label>
                <input type="text" v-model="this.selectMap.MAX_LENGTH" class="form-control" >
              </div>       
              <div class="col-md-4">
                <label for="inputPassword4" class="form-label">HD_ID</label>
                <input type="text" v-model="this.selectMap.HD_ID" class="form-control" >
              </div>                     
              <div class="col-md-4">
                <label for="inputPassword4" class="form-label">HD_TYPE</label>
                <input type="text" v-model="this.selectMap.HD_TYPE" class="form-control" >
              </div>       
              <div class="col-md-4">
                <label for="inputPassword4" class="form-label">HD_LENGTH</label>
                <input type="text" v-model="this.selectMap.HD_LENGTH" class="form-control" >
              </div>                      
              <div class="col-12">
                <label for="inputAddress" class="form-label">Address</label>
                <input type="text" class="form-control" id="inputAddress" placeholder="1234 Main St">
              </div>
              <div class="col-md-6">
                <label for="inputCity" class="form-label">City</label>
                <input type="text" class="form-control" id="inputCity">
              </div>
              <div class="col-md-4">
                <label for="inputState" class="form-label">State</label>

              </div>
              <div class="col-md-2">
                <label for="inputZip" class="form-label">Zip</label>
                <input type="text" class="form-control" id="inputZip">
              </div>
              <div class="col-12">
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" id="gridCheck">
                  <label class="form-check-label" for="gridCheck">
                    Check me out
                  </label>
                </div>
              </div>
              <div class="col-12 text-center" >
                <button type="submit" class="btn btn-primary">Save</button>
                <b-button variant="danger" class="btn btn-primary" @click="reStartSocket()">RESTART</b-button>
              </div>
            </form>        
          </b-tab>
          <b-tab title="HD">
            <div>
         <!--     <el-table
                :data="tableData"
                :span-method="arraySpanMethod"
                border
                style="width: 100%"
              >
                <el-table-column prop="HD_ID" label="HD_ID" width="180" />
                <el-table-column prop="HD_TYPE" label="HD_TYPE" />
                <el-table-column prop="HD_NAME" sortable label="HD_NAME" />
                <el-table-column prop="HD_DESC" sortable label="HD_DESC" />
                <el-table-column prop="MAX_LANGTH" sortable label="MAX_LANGTH" />
              </el-table>

              <el-table
                :data="tableData"
                :span-method="objectSpanMethod"
                border
                style="width: 100%; margin-top: 20px"
              >
                <el-table-column prop="id" label="ID" width="180" />
                <el-table-column prop="name" label="Name" />
                <el-table-column prop="amount1" label="Amount 1" />
                <el-table-column prop="amount2" label="Amount 2" />
                <el-table-column prop="amount3" label="Amount 3" />
              </el-table> -->
            </div>   
          </b-tab>
          <b-tab title="BODY"><p>I'm the tab with the very, very long title</p></b-tab>
          <b-tab title="CHANNEL" >
            <el-table :data="channels" :border="true" style="width: 100%">
              <el-table-column type="expand">
                <template #default="props">
                  <div m="4">
                    <p m="t-0 b-2">details: {{ props.row.details }}</p>
                   <!-- <p m="t-0 b-2">CH_LAST_SEND_MSG: {{ props.row.city }}</p>
                    <p m="t-0 b-2">CH_ACTIVE_DT: {{ props.row.address }}</p>
                    <p m="t-0 b-2">CH_LAST_SEND_DT: {{ props.row.zip }}</p>
                    <p m="t-0 b-2">BZ_METHOD_DT: {{ props.row.zip }}</p>
                    <p m="t-0 b-2">CH_LAST_RECIVE_DT: {{ props.row.zip }}</p>
                    <p m="t-0 b-2">CH_LAST_RECIVE_MSG: {{ props.row.zip }}</p> -->
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="Address" prop="address" />
              <el-table-column label="Id" prop="id" />
            </el-table>            
          </b-tab>
        </b-tabs>
      </div>
      <b-button class="mt-3" variant="outline-danger" block @click="hideModal">Close</b-button>      
    </b-modal>    
  </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 : [			
                      "SK_CONN_TYPE",	
                      "SK_TYPE",		
                      "PKG_ID",			
                      "PARENT_SK_ID",	
                      "SK_IP",			
                      "SK_PORT",		
                      "SK_DELIMIT_TYPE",
                      "IS_SK_RUN",		
                      "SK_ACK_YN",		
                      "SK_KEEP_YN",		
                      "HD_TYPE",		
                      "HD_LENGTH",		
                      "MAX_LENGTH",		
                      ],
        currentPage: 1, // currentPage를 추가하고 초기 값으로 1을 설정
        search : '',     
        selected: null,
        options: [],    
        channels: [],
        selectMap: {},

      };
    },
    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: {
      handleClick(index, row){
        console.log(index, row);
        this.selectMap = row;
        this.$refs['my-modal'].show()
        console.log(this.selectMap.CHANNEL_MAP);

        let input = this.selectMap.CHANNEL_MAP;

        // 입력 문자열에서 '{'와 '}'를 제거합니다.
        input = input.slice(1, -1);

        // 각 채널 정보를 분리합니다.
        let channels = input.split('}, ');

        // 각 채널 정보를 처리합니다.
        let connections = channels.map(channel => {
          let id, address, fieldObjects = [];

          // 채널 ID와 주소를 추출합니다.
          let idAndAddress = channel.split('={')[0];
          if (idAndAddress) {
            [id, address] = idAndAddress.split(', ');
          }

          // 채널의 세부 정보를 추출합니다.
          let details = channel.split('={')[1];
          if (details) {
            let fields = details.split(', ');

            // 각 필드를 처리합니다.
            fieldObjects = fields.map(field => {
              let [key, value] = field.split('=');
              return { [key]: value };
            });
          }

          // 채널 정보를 객체로 반환합니다.
          return {
            id: id,
            address: address,
            details: fieldObjects
          };
        });
        this.channels = connections;
        console.log(this.channels);
      },
      hideModal() {
        this.$refs['my-modal'].hide();
        this.selectMap = {};
      },      
      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 = "socketList";        
        
        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;        
             
        this.$store.dispatch('websocket/sendMessage', this.message); // 메시지 전송        
      },    
      reStartSocket() {   
        
        if(this.selectMap.SK_CONN_TYPE !== 'CLIENT'||this.selectMap.SK_TYPE !== 'TCP'){
          alert('TCP CLIENT만 가능합니다.');
          return;
        }
        if (confirm("정말 재시작하시겠습니까??") == false){    //확인
            return;            
        }            
        this.message.EXECUTE = "SOCKET_RERUN";
        this.message.DATA_LIST = (this.selectMap == null) ? '':this.selectMap.SK_ID;        
        
        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);
         
          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;

          //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>
