<script lang="ts" setup>
import { IconDownload } from '@computing/opendesign-icons';
import { ref, onMounted, reactive } from 'vue';
import { reqPath } from '@/api/reqPath';
import GlobalStoreService from '@/services/gloabal-store-service';
import { downloadFileWithResponse } from '@/utils/common-service';
import { showElMessage } from '@/utils/utils';
import { traduction } from '@/utils/language';
import Loading from '@/components/Loading/Loading.vue';
import TableNoData from '@/components/TableNoData/TableNoData.vue';
import {
  getLogData,
  getTaskStateData,
  downloadOperateData,
  downLoadLogUrl,
} from './ibmclog.server';
import { ITableColumns } from '@/model/base-interface';

const globalStoreService = new GlobalStoreService();
const successMsg = traduction('COMMON_SUCCESS');
const errorMsg = traduction('COMMON_FAILED');
// 当前页
const currentPage = ref(1);
let pageSizeCount = ref(10);
let tableData: any[] = reactive([]);
const total = ref(0);
const loadingShow = ref(false);
const columns: ITableColumns[] = [
  {
    title: traduction('FDM_ALARM_NUM'),
    content: 'ID',
    width: '5%',
    className: 'id',
  },
  {
    title: traduction('BMC_LOG_INTERFACE'),
    content: 'Interface',
    width: '5%',
    className: 'interface',
  },
  {
    title: traduction('BMC_LOG_USER'),
    content: 'UserName',
    width: '8%',
    className: 'userName',
  },
  {
    title: traduction('BMC_LOG_IP'),
    content: 'IPAddress',
    width: '8%',
    className: 'ipAdress',
  },
  {
    title: traduction('EVENT_ENGENDER_TIME'),
    content: 'Time',
    width: '10%',
    className: 'time',
  },
  {
    title: traduction('FDM_INFO'),
    content: 'Content',
    width: '20%',
    className: 'content',
  },
];

// 获取数据
function getData(url: string, firstInter?: boolean) {
  tableData.splice(0);
  globalStoreService.setValue('isLoading', true);
  getLogData(url)
    .then((data: any) => {
      if (data && data.Logs) {
        total.value = data.TotalCount;
        if (firstInter) {
          pageChange();
        } else {
          const list = data.Logs;
          tableData.push(...list.reverse());
        }
      }
      globalStoreService.setValue('isLoading', false);
    })
    .catch(err => {
      globalStoreService.setValue('isLoading', false);
    });
}
// 分页器 当前页数量 或者 页码发生改变
function pageChange() {
  let start = total.value - (currentPage.value * pageSizeCount.value);
  let top = pageSizeCount.value;
  if (start < 0) {
    start = 0;
    // 最后一页请求的数据量
    top = total.value - ((currentPage.value - 1) * pageSizeCount.value);
  }

  let url = reqPath.maintance.ibmcLog.ibmcLogOperation + '?Skip=' + start + '&Top=' + top;
  getData(url);
}

// 下载日志
function downLoadLog() {
  loadingShow.value = true;
  downLoadLogUrl(reqPath.maintance.ibmcLog.DownloadOperation, {})
    .then((data: any) => {
      if (data && data.data) {
        const response = data.data;
        getTaskState(response.url);
      }
    })
    .catch(() => {
      showElMessage('error', traduction('COMMON_FAILED'));
    })
    .finally(() => {
      loadingShow.value = false;
    });
}

// 获取下载进度
function getTaskState(url: string) {
  getTaskStateData(url)
    .then((data: any) => {
      if (data && data.data) {
        let taskResponse = data.data;
        if (taskResponse.prepare_progress === 100 && taskResponse.state === 'Completed') {
          beginDownLoad();
        } else if (taskResponse.state === 'Exception') {
          showElMessage('error', traduction('COMMON_FAILED'));
        } else {
          getTaskState(url);
        }
      }
    })
    .catch(() => {
      showElMessage('error', traduction('COMMON_FAILED'));
    });
}

// 开始下载
function beginDownLoad() {
  downloadOperateData()
    .then((res: any) => {
      const fileName = res.headers['content-disposition'].split('=')[1];
      downloadFileWithResponse(res.data, fileName);
      showElMessage('success', traduction('COMMON_SUCCESS'));
    })
    .catch(() => {
      showElMessage('error', traduction('COMMON_FAILED'));
    });
}

// 框内页码范围
const handleSizeChange = (val: number) => {
  pageSizeCount.value = val;
  currentPage.value = 1;
  pageChange();
};

// 第几页点击
const handleCurrentChange = (val: number) => {
  pageChange();
};

onMounted(() => {
  // 获取数据
  const url =
    reqPath.maintance.ibmcLog.ibmcLogOperation + '?Skip=0' + '&Top=' + pageSizeCount.value;
  getData(url, true);
});
</script>

<template>
  <div class="ibmc-box">
    <div class="icon-box">
      <!-- 下载按钮 -->
      <el-tooltip
        v-if="!loadingShow"
        class="box-item"
        effect="dark"
        :content="$t('COMMON_DOWN')"
        placement="top"
        trigger-keys
      >
        <el-button
          id="operateDownload"
          :disabled="loadingShow"
          :class="loadingShow ? 'disLoading' : ''"
          class="download_log"
          @click="downLoadLog"
        >
          <template #icon>
            <!-- 下载 -->
            <IconDownload />
          </template>
        </el-button>
      </el-tooltip>
      <el-button
        v-else
        id="operateLoading"
        :disabled="loadingShow"
        :class="loadingShow ? 'disLoading' : ''"
        class="download_log"
      >
        <template #icon>
          <!-- 加载中 -->
          <Loading :state="true" />
        </template>
      </el-button>
    </div>
    <el-table
      v-addId.table="'tableComponent'"
      :data="tableData"
      style="width: 100%"
      border
      resizable
    >
      <el-table-column
        v-for="(item, i) in columns"
        :key="i"
        :prop="item.content"
        :label="item.title"
        :min-width="item.width"
      >
        <template #default="scope">
          <span v-addTooltip.td :class="item.className">{{ scope.row[item.content] }}</span>
        </template>
      </el-table-column>

      <template #empty>
        <TableNoData />
      </template>
    </el-table>
    <div class="pagenation">
      <el-pagination
        v-model:currentPage="currentPage"
        v-addId.pagination="'logPageNation'"
        :page-sizes="[10, 15, 30, 50]"
        :page-size="pageSizeCount"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.ibmc-box {
  flex: 1;
  margin-right: 24px;
  padding: 16px 16px;
  border-radius: 4px;
  background-color: var(--o-bg-color-base);
  position: relative;
  display: flex;
  flex-direction: column;

  .icon-box {
    height: 32px;
    .disLoading {
      background-color: var(--o-bg-color-placeholder);
    }
    .download_log {
      float: right;
      font-size: 16px;
      width: 32px;
      min-width: auto;
      padding: 7px;
      &:hover {
        svg {
          color: var(--o-color-primary-secondary);
        }
      }
      .loading {
        background: rgba(0, 0, 0, 0);
        :deep(.circular) {
          position: absolute;
          left: 100%;
          width: 16px;
          height: 16px;
          margin-top: -8px;
          margin-left: -16px;
        }
      }
      svg {
        color: var(--o-text-color-tertiary);
        &:hover {
          color: var(--o-color-primary-secondary);
          cursor: pointer;
        }
      }
    }
    margin-bottom: 16px;
  }

  :deep(.el-table) {
    flex: 1;
    padding-bottom: 16px;
    display: flex;
    flex-direction: column;
    .el-table__inner-wrapper {
      flex: 1;
      display: flex;
      flex-direction: column;
      .el-scrollbar__view {
        height: 100%;
      }
    }
    .el-table__body-wrapper {
      flex: 1;
      display: flex;
      flex-direction: column;
    }
    .el-table__empty-block {
      margin-top: 0;
    }
    .cell span {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
</style>
