<template>
  <div class="p-2 auto-overflow-y">
    <el-card class="mb-2">
      <template #header>
        <div><span class="text-red-500 text-base">监控控制</span></div>
      </template>
      <el-row class="mb-2">
        <el-col :span="3">
          <el-button v-if="!socketStatus" type="primary" icon="Open" @click="doOpenSocket">连接服务</el-button>
          <el-button v-else type="primary" icon="Close" @click="doCloseSocket">断开服务</el-button>
        </el-col>
        <el-col :span="6">
          <div class="flex items-center h-32px">
            <span v-if="socketStatus" class="text-green-500">成功连接到服务：[{{ ipPort }}]</span>
            <span v-else class="text-red-500">未连接到服务</span>
          </div>
        </el-col>
      </el-row>
      <el-row v-if="false" class="mb-2">
        <el-col :span="2">
          <el-button type="primary" icon="Setting" @click="setTime">设置时间</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="Reading" @click="getTime">读取时间</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="Setting" @click="setParam">设置参数</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="Reading" @click="getParam">读取参数</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="Setting" @click="setServiceInfo">设置服务器信息</el-button>
        </el-col>
      </el-row>
      <el-row v-if="false">
        <el-col :span="2">
          <el-button type="primary" icon="Setting" @click="setBlackList">设置黑名单</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="Reading" @click="getData">采集数据</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="Pointer" @click="setData">补采数据</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="SwitchButton" @click="reboot">设备重启</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="Reading" @click="getTermInfo">读取硬件信息</el-button>
        </el-col>
        <el-col :span="2">
          <el-button class="ml-7" type="danger" icon="Delete" @click="clearData">清除数据</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card>
      <template #header>
        <div class="flex justify-between">
          <div class="flex justify-center items-center"><span class="text-red-500 text-base font-bold">设备列表</span></div>
          <div class="w-100">
            <el-input
              v-model="queryParams.deviceNameOrNum"
              style="width: 8rem; margin-right: 10px"
              type="text"
              placeholder="设备名称或机号"
            ></el-input>
            <el-select v-model="queryParams.deviceType" clearable style="width: 9rem; margin-right: 10px" placeholder="设备类型">
              <el-option v-for="item in XF_TermType" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </div>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="tableFilterData"
        max-height="calc(100vh - 29rem)"
        flexible
        table-layout="auto"
        :row-style="{ height: '2.85rem' }"
        :cell-style="{ padding: '0' }"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="设备机号" align="center" prop="termNo" width="90" />
        <el-table-column prop="termName" label="设备名称" align="center" show-overflow-tooltip />
        <el-table-column label="设备IP" align="center" prop="termIp" />
        <el-table-column label="设备端口" align="center" prop="commPort" width="100" />
        <el-table-column label="设备类型" align="center" header-align="center" width="150" prop="termType" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="XF_TermType" :value="scope.row.termType" />
          </template>
        </el-table-column>
        <el-table-column label="设备状态" align="center" header-align="center" width="150" prop="status" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="DEVICE_STATUS" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="是否在线" width="90" align="center" header-align="center" prop="online" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="onlineOptions" :value="scope.row.online + ''" />
          </template>
        </el-table-column>
        <el-table-column label="上次命令" align="center" prop="lastCmdMsg" />
        <el-table-column label="详细信息" align="center" prop="detailMsg" width="400" show-overflow-tooltip />
      </el-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="handleQuery"
      />
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { listAllXfTerm } from '@/api/consumption/xfTerm';
import { XfTermVOMonitor } from '@/api/consumption/xfTerm/types';
import { initWebSocket, sendMsg, websocketclose } from '@/utils/websocket';

const socketStatus = ref(false);
const ipPort = ref('172.16.137.85:9004');
let tableData = ref<XfTermVOMonitor[]>([]);
let tableFilterData = ref<XfTermVOMonitor[]>([]);
let queryParams = reactive({
  deviceNameOrNum: '',
  deviceType: '',
  pageNum: 1,
  pageSize: 10
});
const onlineOptions: DictDataOption[] = [
  { label: '在线', value: 'true', elTagType: 'success' },
  { label: '离线', value: 'false', elTagType: 'danger' }
];
// 是否加载遮罩层
const loading = ref(true);
// 总记录数
const total = ref(0);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
/** 当前页面引用的数据字典 */
const { XF_TermType, DEVICE_STATUS } = toRefs<any>(proxy?.useDict('XF_TermType', 'DEVICE_STATUS'));

const setParam = () => {
  console.log('setParam');
};
const getParam = () => {
  console.log('getParam');
};
const setTime = () => {
  console.log('setTime');
};
const getTime = () => {
  console.log('getTime');
};
const setBlackList = () => {
  console.log('setBlackList');
};
const setServiceInfo = () => {
  console.log('setServiceInfo');
};
const getData = () => {
  console.log('getData');
};
const setData = () => {
  console.log('setData');
};
const reboot = () => {
  console.log('reboot');
};
const getTermInfo = () => {
  console.log('getTermInfo');
};
const clearData = () => {
  console.log('clearData');
};

const handleQuery = () => {
  if (tableData.value.length === 0) {
    return;
  }
  if (!queryParams.deviceNameOrNum && !queryParams.deviceType) {
    // console.log('查询条件为空', tableData.value);
    tableFilterData.value = tableData.value;
    // console.log('查询条件为空 tableFilterData', tableFilterData.value);
  } else {
    let filterData = tableData.value.filter((item) => {
      if (queryParams.deviceNameOrNum && queryParams.deviceType) {
        return (
          (item.termName.includes(queryParams.deviceNameOrNum) || item.termNo.toString().includes(queryParams.deviceNameOrNum)) &&
          item.termType === queryParams.deviceType
        );
      } else if (queryParams.deviceNameOrNum) {
        return item.termName.includes(queryParams.deviceNameOrNum) || item.termNo.toString().includes(queryParams.deviceNameOrNum);
      } else {
        return item.termType === queryParams.deviceType;
      }
    });
    tableFilterData.value = filterData;
  }
  total.value = tableFilterData.value.length;
  // 手动分页
  currentPageData();
};

const currentPageData = () => {
  let startIndex = (queryParams.pageNum - 1) * queryParams.pageSize;
  let endIndex = startIndex + queryParams.pageSize;
  if (endIndex > tableFilterData.value.length) {
    endIndex = tableFilterData.value.length;
  }
  // console.log('startIndex', startIndex, 'endIndex', endIndex);
  tableFilterData.value = tableFilterData.value.slice(startIndex, endIndex);
};

/** 查询消费设备列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAllXfTerm();
  tableData.value = res.data;
  tableData.value.forEach((item) => {
    item.detailMsg = '';
    item.lastCmdMsg = '';
    item.online = false;
    item.status = '0';
  });
  tableFilterData.value = tableData.value;
  total.value = tableData.value.length;
  currentPageData();
  loading.value = false;
};

onMounted(() => {
  getList();
});

const doOpenSocket = () => {
  let protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
  initWebSocket(protocol + ipPort.value + '/xfMonitorWebsocket', (data: any) => {
    // console.log('websocket receive msg', data);
    // 处理解析数据
    if (data.tobject) {
      for (let i = 0; i < tableData.value.length; i++) {
        if (tableData.value[i].termNo == data.tobject.termNo) {
          console.log('websocket receive tobject', data.tobject, data.tobject.status);
          if (data.tobject.type == 'OffLine') {
            tableData.value[i].detailMsg = data.tobject.detail;
            tableData.value[i].lastCmdMsg = '';
            tableData.value[i].online = false;
            tableData.value[i].status = '-1'; // 异常状态
          } else {
            tableData.value[i].detailMsg = data.tobject.detailMsg;
            tableData.value[i].lastCmdMsg = data.tobject.lastCmdMsg;
            tableData.value[i].online = data.tobject.online;
            tableData.value[i].status = data.tobject.status;
          }
          break;
        }
      }
      for (let i = 0; i < tableFilterData.value.length; i++) {
        if (tableFilterData.value[i].termNo == data.tobject.termNo) {
          if (data.tobject.type == 'OffLine') {
            tableFilterData.value[i].detailMsg = data.tobject.detail;
            tableFilterData.value[i].lastCmdMsg = '';
            tableFilterData.value[i].online = false;
            tableFilterData.value[i].status = '-1'; // 异常状态
          } else {
            tableFilterData.value[i].detailMsg = data.tobject.detailMsg;
            tableFilterData.value[i].lastCmdMsg = data.tobject.lastCmdMsg;
            tableFilterData.value[i].online = data.tobject.online;
            tableFilterData.value[i].online = data.tobject.online;
          }
          break;
        }
      }
    }
    if (data.type === 'OffLine') {
      for (let i = 0; i < tableData.value.length; i++) {
        if (tableData.value[i].termNo === data.termNo) {
          tableData.value[i].detailMsg = data.detail;
          tableData.value[i].lastCmdMsg = '';
          tableData.value[i].online = false;
          tableData.value[i].status = '-1'; // 异常状态
          break;
        }
      }
      for (let i = 0; i < tableFilterData.value.length; i++) {
        if (tableFilterData.value[i].termNo === data.termNo) {
          tableFilterData.value[i].detailMsg = data.detail;
          tableFilterData.value[i].lastCmdMsg = '';
          tableFilterData.value[i].online = false;
          tableFilterData.value[i].status = '-1'; // 异常状态
          break;
        }
      }
    }
  });
  setTimeout(() => {
    sendMsg('connect'); //发送信息到服务端，表示前端初始化数据完成！
    socketStatus.value = true;
  }, 100);
};

const doCloseSocket = () => {
  websocketclose();
  console.log('doCloseSocket', 'websocket close');
  socketStatus.value = false;
};

onUnmounted(() => {
  console.log('onUnmounted', 'websocket close');
  websocketclose();
});
</script>
<style lang="scss" scoped></style>
