<script setup lang="ts">
import { traduction } from '@/utils/language';
import { onMounted, reactive, ref, computed } from 'vue';
import { getSensorsData } from './sensors.server';
import { IconSearch } from '@computing/opendesign-icons';
import { ITableColumns, ISensorsTable, sensorUnit } from '@/model/base-interface';
import { dataFilter, dataSort, dataCustomSort, showElMessage, initOriginalData } from '@/utils/utils';
import { getStoreData } from '@/utils/composition';

import GlobalStoreService from '@/services/gloabal-store-service';
import TableNoData from '@/components/TableNoData/TableNoData.vue';

import SearchInput from '@/components/SearchInput/SearchInput.vue';

const globalStoreService = new GlobalStoreService();
const multihost = computed(() => getStoreData('loct', 'multihost'));

let columns: ITableColumns[] = [
  {
    title: 'SENSOR_NUMBER',
    width: '5%',
    content: 'id',
  },
  {
    title: 'SENSOR_TITLE',
    width: '15%',
    content: 'name',
    sortKey: 'name',
    sortable: true,
  },
  {
    title: 'SENSOR_CURRENT_VAL',
    width: '10%',
    content: 'readingValue',
  },
  {
    title: 'SENSOR_STATE',
    width: '10%',
    content: 'statusText',
  },
  {
    title: 'SENSOR_HOST',
    width: '10%',
    content: 'systemId',
    hide: !multihost.value,
  },
  {
    title: 'SENSOR_EMERGENCY_LOWER',
    width: '10%',
    content: 'lowerThresholdFatal',
  },
  {
    title: 'SENSOR_CRITICAL_LOWER',
    width: '10%',
    content: 'lowerThresholdCritical',
  },
  {
    title: 'SENSOR_SLIGHT_LOWER',
    width: '10%',
    content: 'lowerThresholdNonCritical',
  },
  {
    title: 'SENSOR_SLIGHT_TOP',
    width: '10%',
    content: 'upperThresholdNonCritical',
  },
  {
    title: 'SENSOR_CRITICAL_TOP',
    width: '10%',
    content: 'upperThresholdCritical',
  },
  {
    title: 'SENSOR_EMERGENCY_TOP',
    width: '10%',
    content: 'upperThresholdFatal',
  },
];
let filterKeys: string[] = [];
let names: string[] = [];

const errorMsg = traduction('COMMON_FAILED');

let dataList: ISensorsTable[] = [];
let tableData: ISensorsTable[] = reactive([]);

const searchContent = ref('');
let currentPage = ref(1);
let total = ref(0);
let pageSize = ref(10);
let sort = reactive({
  prop: 'name',
  // 排序方式,ascending:升序 descending:降序 null:默认
  order: null,
});

// 获取数据 当前排序、筛选、分页等操作都是在前端进行的（参照v2）
function getData() {
  tableData.splice(0);

  // 如果请求过数据，那么不再发送请求，直接对现有请求数据做重新组合
  if (dataList.length > 0) {
    initShowData();
    return;
  }

  globalStoreService.setValue('isLoading', true);
  getSensorsData()
    .then((data: any) => {
      if (data && data.List) {
        total.value = data.TotalCount;
        const list: any = data.List;
        list.forEach((item: any, index: number) => {
          const unit = sensorUnit[item.Unit] || '';
          const status = item.Status;
          const statusObj = status ? status.toUpperCase() : '--';
          dataList.push({
            name:
              initOriginalData(item.Name) !== '--' ? item.Name + (unit ? ` (${unit})` : '') : '--',
            readingValue: initOriginalData(item.ReadingValue),
            status,
            statusText: statusObj,
            statusClassName: statusObj && statusObj.className,
            statusIcon: statusObj && statusObj.icon,
            lowerThresholdCritical: initOriginalData(item.LowerThresholdCritical),
            lowerThresholdFatal: initOriginalData(item.LowerThresholdFatal),
            lowerThresholdNonCritical: initOriginalData(item.LowerThresholdNonCritical),
            upperThresholdNonCritical: initOriginalData(item.UpperThresholdNonCritical),
            upperThresholdCritical: initOriginalData(item.UpperThresholdCritical),
            upperThresholdFatal: initOriginalData(item.UpperThresholdFatal),
            systemId: initOriginalData(item.SystemId),
          });
        });
        // 初始化的时候以升序展示
        dataList = dataCustomSort(dataList, 'name', true);
        dataList = dataSort(dataList, 'systemId', 1);
        dataList.forEach((item: any, index: number) => (item.id = index + 1));
        initShowData();
        globalStoreService.setValue('isLoading', false);
      } else {
        globalStoreService.setValue('isLoading', false);
        showElMessage('error', errorMsg);
      }
    })
    .catch(err => {
      globalStoreService.setValue('isLoading', false);
    });
}

// 加工展示数据
function initShowData() {
  const { order } = sort;
  const searchText = searchContent.value;

  if (filterKeys.length === 0) {
    columns.forEach((item: any) => {
      filterKeys.push(item.content);
    });
  }

  // 输入框数据进行数据过滤
  let filterList = dataFilter(dataList, filterKeys, searchText);
  total.value = filterList.length;

  if (order === 'ascending') {
    // 升序
    filterList = dataCustomSort(filterList, 'name', true);
  } else if (order === 'descending') {
    // 降序
    filterList = dataCustomSort(filterList, 'name', false);
  }
  const showList = filterList.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value,
  );
  tableData.push(...showList);
}

// 改变排序方式
function sortChange(order: any) {
  sort.order = order.order;
  getData();
}

function handleSizeChange(val: number) {
  pageSize.value = val;
  // 切换每页显示的条数时，默认显示第一页数据以防止当前非首页没有数据显示
  currentPage.value = 1;
  getData();
}

function handleCurrentChange(val: number) {
  getData();
}

// 搜索框回车、搜索事件、清空事件
function keyupEnter(value: string) {
  searchContent.value = value;
  currentPage.value = 1;
  getData();
}

onMounted(() => {
  columns = columns.filter(i => i.hide !== true);
  getData();
});
</script>

<template>
  <div id="inforSensor" class="sensors-box">
    <div class="content">
      <div class="title-search">
        <div class="el-input-search">
          <SearchInput
            :id-str="'sensorSearchBox'"
            :value="searchContent"
            :placeholder="$t('SENSOR_KEY_WORD')"
            @keyup-enter="keyupEnter"
            @clear="keyupEnter"
          />
        </div>
      </div>

      <el-table
        v-addId.table="'sensorTable'"
        :data="tableData"
        :default-sort="sort"
        border
        resizable
        @sort-change="sortChange"
      >
        <el-table-column
          v-for="item in columns"
          :key="item.title"
          :label="$t(item.title)"
          :min-width="item.width"
          :sortable="item.sortable"
        >
          <template #default="scope">
            <span :id="item.content + scope.row.id" :class="item.content">
              {{ scope.row[item.content] }}
            </span>
          </template>
        </el-table-column>
        <template #empty>
          <TableNoData />
        </template>
      </el-table>
    </div>

    <el-pagination
      v-if="tableData.length > 0"
      v-model:currentPage="currentPage"
      v-addId.pagination="'sensorPagination'"
      :page-sizes="[10, 15, 30, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<style lang="scss" scoped>
.sensors-box {
  flex: 1;
  margin-right: 24px;
  padding: 16px;
  background-color: var(--o-bg-color-base);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;

  .content {
    flex: 1;
    padding-bottom: 16px;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: flex-end;

    .title-search {
      margin-bottom: 16px;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }

    .el-input-search {
      width: 296px;
      float: right;
    }

    :deep(.el-input__inner::-webkit-input-placeholder) {
      font-size: 12px !important;
    }

    :deep(.el-input-search) {
      .el-input__prefix-inner {
        display: flex;
        flex-direction: column;
        justify-content: center;

        .el-icon {
          font-size: 16px;
          cursor: pointer;
        }
      }
    }

    :deep(.el-table) {
      .sort-caret.descending {
        color: var(--o-text-color-tertiary);
      }

      tr {
        .el-table__cell:nth-child(1) {
          .cell {
            padding-left: 0;
          }
        }
      }
    }
  }
}
</style>
