<script setup lang="ts">
import { traduction } from '@/utils/language';
import { onMounted, reactive, ref } from 'vue';
import { getAssetInventory } from '../asset.service';
import { IconSearch } from '@computing/opendesign-icons';
import { ITableColumns, IAssetInventoryTable } from '@/model/base-interface';
import { dataFilter, dataSort, showElMessage, initOriginalData } from '@/utils/utils';

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 columns: ITableColumns[] = [
  {
    title: 'ASSET_INVENTORY_ASSET_NUMBER',
    width: '5%',
    content: 'id',
  },
  {
    title: 'ASSET_INVENTORY_ASSET_TYPE',
    width: '10%',
    content: 'assetType',
  },
  {
    title: 'ASSET_INVENTORY_ASSET_NAME',
    width: '10%',
    content: 'assetName',
  },
  {
    title: 'ASSET_INVENTORY_ASSET_TAG',
    width: '10%',
    content: 'assetTag',
  },
  {
    title: 'ASSET_INVENTORY_PART_NUMBER',
    width: '10%',
    content: 'partNumber',
  },
  {
    title: 'ASSET_INVENTORY_SN',
    width: '10%',
    content: 'sn',
  },
  {
    title: 'ASSET_INVENTORY_FIRMWARE_VERSION',
    width: '15%',
    content: 'firmwareVersion',
  },
  {
    title: 'ASSET_INVENTORY_ASSET_PCB_VERSION',
    width: '10%',
    content: 'pcbVersion',
  },
  {
    title: 'ASSET_INVENTORY_VENDOR_NAME',
    width: '10%',
    content: 'tradeName',
  },
  {
    title: 'ASSET_INVENTORY_MANUFACTURE_DATE',
    width: '10%',
    content: 'manufactureDate',
  },
];
let filterKeys: string[] = [];

const errorMsg = traduction('COMMON_FAILED');

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

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

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

  // 如果请求过数据，那么不再发送请求，直接对现有请求数据做重新组合
  if (dataList.length > 0) {
    initShowData();
    return;
  }
  globalStoreService.setValue('isLoading', true);
  getAssetInventory()
    .then((res: any) => {
      let data = res.data;
      if (data && data.List) {
        total.value = data.TotalCount;
        const list: any = data.List;
        list.forEach((item: any, index: number) => {
          dataList.push({
            assetTag: initOriginalData(item.AssetTag),
            assetType: initOriginalData(item.AssetType),
            assetName: initOriginalData(item.AssetName),
            partNumber: initOriginalData(item.PartNumber),
            sn: initOriginalData(item.SerialNumber),
            firmwareVersion: initOriginalData(item.FirmwareVersion),
            pcbVersion: initOriginalData(item.PCBVersion),
            tradeName: initOriginalData(item.Manufacturer),
            manufactureDate: initOriginalData(item.ManufactureDate),
          });
        });
        dataSort(dataList, 'assetType', 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: any) => {
      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 = dataSort(filterList, 'assetType', 1);
  } else if (order === 'descending') {
    // 降序
    filterList = dataSort(filterList, 'assetType', 2);
  } else {}
  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(() => {
  getData();
});
</script>

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

      <div id="inventoryTableBox">  
        <el-table
          v-addId.table="'inventoryTable'"
          :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>
    </div>

    <el-pagination
      v-if="tableData.length > 0"
      v-model:currentPage="currentPage"
      v-addId.pagination="'inventoryPagination'"
      :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>
.assetInventory-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;
          }
        }
      }
    }
  }

  #inventoryTableBox {
    width: 100%;
    height: 100%;
  }
}
</style>
