<script setup lang="ts">
import { traduction } from '@/utils/language';
import { onMounted, reactive, ref } from 'vue';
import { getSupplyChainConfig, confirmSupplyChain } 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 { IconRemind } from '@computing/opendesign-icons';


const globalStoreService = new GlobalStoreService();

const columns: ITableColumns[] = [
  {
    title: 'ASSET_INVENTORY_ASSET_NUMBER',
    width: '2%',
    content: 'id',
  },
  {
    title: 'CONFIGURATION_NAME',
    width: '10%',
    content: 'name',
  },
  {
    title: 'DEFAULT_SETTINGS',
    width: '10%',
    content: 'origin',
  },
  {
    title: 'ACTUAL_SETTINGS',
    width: '10%',
    content: 'actual',
  },
];
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',
});
const dialog = ref();

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

  // 如果请求过数据，那么不再发送请求，直接对现有请求数据做重新组合
  if (dataList.length > 0) {
    initShowData();
    return;
  }
  globalStoreService.setValue('isLoading', true);
  getSupplyChainConfig()
    .then((res: any) => {
      let data = res.data;
      if (data && data.ChangedEvents) {
        total.value = data.ChangedEvents.length;
        const list: any = data.ChangedEvents;
        list.forEach((item: any, index: number) => {
          let subItem = {
            name: '',
            origin: '',
            actual: '',
            index: index,
          };
          if (item.indexOf('missed') > -1) {
            subItem.name = item.split('missed')[0];
            subItem.name = subItem.name.replace('Config', '');
            subItem.actual = '--';
            subItem.origin = '--';
          } else if (item.indexOf('changed from') > -1) {
            subItem.name = item.split('changed from')[0];
            subItem.actual = item.split('changed from')[1].split('to')[1];
            subItem.origin = item.split('changed from')[1].split('to')[0];
          } else {
          }
          dataList.push({
            origin: initOriginalData(subItem.origin),
            actual: initOriginalData(subItem.actual),
            name: initOriginalData(subItem.name),
          });
        });
        dataList.forEach((item: any, index: number) => (item.id = index + 1));
        initShowData();
        globalStoreService.setValue('isLoading', false);
      }
    })
    .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();
}

function confirmChange() {
  dialog.value.show();
}

const diaginfo = reactive({
  id: 'changeConfirmDialog',
  content: traduction('SUPPLY_CHAIN_CONFIRM_TIP2'),
  title: traduction('CONFIRM_CONFIGURATIONS'),
  okButton: {
    id: 'secondConfirm_ok_btn',
    label: traduction('COMMON_CONFIRM'),
    hide: false,
  },
});

        
function dialogCloseFun(val: boolean) {
  if (val) {
    confirmSupplyChain()
      .then((res) => {
        showElMessage('success', traduction('COMMON_SUCCESS'));
      }).finally(() => {
        dialog.value.hide();
      });
  } else {
    dialog.value.hide();
  }
}

onMounted(() => {
  getData();
});
</script>

<template>
  <div id="supplyChainConfig" class="assetInventory-box">
    <div class="content">
      <div class="title-search" v-if="tableData.length > 0">
        <el-button id="addWorkNoteBtn" :disabled="systemLock" type="primary" @click="confirmChange">
          {{ $t('CONFIRM_CONFIGURATIONS') }}
        </el-button>
        <div class="el-input-search">
          <SearchInput
            :id-str="'inventorySearchBox'"
            :value="searchContent"
            :placeholder="$t('SENSOR_KEY_WORD')"
            @keyup-enter="keyupEnter"
            @clear="keyupEnter"
          />
        </div>
      </div>
      <div class="desc" v-else>
        <el-icon>
          <IconRemind />
        </el-icon>
        {{ $t('SUPPLY_CHAIN_CONFIRM_TIP') }}
      </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>
  <Dialog ref="dialog" :config="diaginfo" @close="dialogCloseFun">
  </Dialog>
</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: space-between;
    }
    
    .desc {
      width: 100%;
      margin-bottom: 16px;
      padding: 8px 16px;
      color: var(--o-text-color-primary);
      border-radius: 2px;
      background-color: var(--o-color-state-primary-secondary);
      display: flex;
      align-items: center;

      .el-icon {
        margin-right: 8px;
        font-size: 16px;
      }
    }

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