<script setup lang="ts">
import { traduction, getErrorTranslate } from '@/utils/language';
import { computed, nextTick, reactive, ref,onMounted } from 'vue';
import useStore from '@/stores';
import { UserPrivil } from '@/model/base-enum';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { IconUser, IconAlarm, IconRefresh } from '@computing/opendesign-icons';
import Dialog from '@/components/Dialog/Dialog.vue';
import { getStoreData, loading, showFailedMessage, showSuccessMessage } from '@/utils/composition';
import SecondPassword from '@/components/SecondPassword/SecondPassword.vue';
import { refreshInfo } from '../asset.service';
import { SecondAuthorityFail } from '@/model/base-enum';
import { getAssetData } from '../asset.service';
import { ITableColumns, IAssetChangeTable } 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';


const preserveLog = ref(true);
const store = useStore();
const systemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const powerState = computed(() => getStoreData('loct', 'powerState'));
// 安全配置权限
const isPrivileges = checkPrivil(UserPrivil.securityConfig);
const dialogRef = ref();
const dialogConfig = reactive({
  title: traduction('ASSET_MAINTANCE_CHANGE_REFRESH'),
  content: ``,
  id: 'refreshAssetChange'
});
const secondRef = ref();
const nopwd = getStoreData('loct', 'nopwd');
const globalStoreService = new GlobalStoreService();

const columns: ITableColumns[] = [
  {
    title: 'COMMON_DEVICE_TYPE',
    width: '25%',
    content: 'type',
  },
  {
    title: 'ASSET_MAINTANCE_DEVICE_LOCATION',
    width: '25%',
    content: 'location',
  },
  {
    title: 'HOME_DEVICEINFO',
    width: '25%',
    content: 'info',
  },
  {
    title: 'ASSET_MAINTANCE_TRUST_STATUS',
    width: '25%',
    content: 'status',
  },
];
let filterKeys: string[] = [];
let names: string[] = [];

const errorMsg = traduction('COMMON_FAILED');

let dataList: IAssetChangeTable[] = [];
let tableData: IAssetChangeTable[] = 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);
  getAssetData()
    .then((data: any) => {
      if (data && data.List) {
        total.value = data.TotalCount;
        const list: any = data.List;
        list.forEach((item: any, index: number) => {
          dataList.push({
            type: initOriginalData(item.Type),
            location: initOriginalData(item.Name),
            currentHash: initOriginalData(item.ActualDigest),
            standardHash: initOriginalData(item.StandardDigest),
            hashInfo: initOriginalData(item.StandardDescription),
            status: item.ActualDigest === item.StandardDigest,
            info: initOriginalData(item.Description),
          });
        });
        // 初始化的时候以升序展示
        dataList = dataSort(dataList, 'type', 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 = dataSort(filterList, 'name', 1);
  } else if (order === 'descending') {
    // 降序
    filterList = dataSort(filterList, 'name', 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 refresh() {
  dialogRef.value.show();
}

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

function dialogClose(reason: boolean) {
  dialogRef.value.hide();
  if (reason) {
    if (!nopwd) {
      secondRef.value.show();
    } else {
      loading(true);
      const params = {
        ReauthKey: '',
      };
      // 刷新函数
      refreshInfo(params)
        .then(() => {
          showSuccessMessage();
          getData();
        })
        .catch((error: any) => {
          const errorCode = error?.data.error[0].code;
          showFailedMessage(getErrorTranslate(errorCode));
        })
        .finally(() => {
          loading(false);
        });
    }
  }
}

function confirmReset(param: { reason: boolean; password: string }) {
  if (param.reason) {
    const params = {
      ReauthKey: window.btoa(param.password),
    };
    loading(true);
    refreshInfo(params)
      .then(
        () => {
          showSuccessMessage();
          secondRef.value.hide();
          getData();
        },
        (error: any) => {
          const errorCode = error.data.error[0].code;
          if (
            errorCode === SecondAuthorityFail.REAUTHFAILED ||
            errorCode === SecondAuthorityFail.AUTHORIZATIONFAILED
          ) {
            secondRef.value.setErrorId();
            secondRef.value.clearPassword();
          } else {
            showFailedMessage(getErrorTranslate(errorCode));
          }
        }
      )
      .finally(() => {
        loading(false);
      });
  } else {
    secondRef.value.hide();
  }
}

</script>
<template>
  <div id="assetChange" class="change-box">
    <div class="title-refresh" v-if="!systemLock && isPrivileges">
      <el-tooltip
        :content="$t('COMMON_REFRESH')"
        placement="top"
        trigger-keys
      >
        <el-button id="refreshBtn" class="refresh_btn" @click="refresh">
          <template #icon>
            <IconRefresh />
          </template>
        </el-button>
      </el-tooltip>
    </div>
    <div class="content">
      <el-table
        v-addId.table="'assetChangeTable'"
        :data="tableData"
        :default-sort="sort"
        border
      >
        <el-table-column
          v-for="item in columns"
          :key="item.title"
          :label="$t(item.title)"
          :min-width="item.width"
          :sortable="item.sortable"
          :show-overflow-tooltip ="item.content !== 'status'"
        >
          <template #default="scope">
            <div v-if="item.content === 'status'" :id="item.content + scope.row.id" class="status">
              <el-tooltip
                :content="$t('REMOTE_HELP_DOCUMENT')"
                trigger-keys
                placement="top"
                :disabled="powerState !== 'On'"
                popper-class="hashTextBox"
              >
                <template #content>
                  <div>
                    <div id="currentHashTip" class="hashText">
                      {{ $t('ASSET_MAINTANCE_METRIC') }}：{{ scope.row.currentHash }}
                    </div>
                    <div v-if="!scope.row[item.content]" id="standardHashTip" class="hashText">
                      {{ $t('TPCM_BASE_VALUE_LABEL') }}：{{ scope.row.standardHash }}
                    </div>
                    <div v-if="!scope.row[item.content]" id="hashInfoTip" class="hashText">
                      {{ $t('ASSET_MAINTANCE_BASE_INFO') }}：{{ scope.row.hashInfo }}
                    </div>
                  </div>
                </template>
                <div v-if="powerState === 'On'" class="status-text">
                  <el-icon
                    v-if="scope.row[item.content]"
                    :size="16"
                    class="icon-believable"
                    id="okIcon"
                  >
                    <IconAlarm />
                  </el-icon>
                  <el-icon v-else :size="16" class="icon-unreliable" id="warnIcon">
                    <IconAlarm />
                  </el-icon>
                  <span v-if="scope.row[item.content]" class="status-text" id="okText">
                    {{ $t('ASSET_MAINTANCE_STATUS_TRUST') }}
                  </span>
                  <span v-else class="status-text" id="warnText">
                    {{ $t('ASSET_MAINTANCE_STATUS_UNTRUST') }}
                  </span>
                </div>
                <div v-else class="status-text">
                  <el-icon :size="16" class="icon-power-off" id="offIcon">
                    <IconAlarm />
                  </el-icon>
                  <span class="status-text" id="offText">
                    {{ $t('LICENSE_STATUS_UNKNOWN') }}
                  </span>
                </div>
              </el-tooltip>
            </div>
            <span :id="item.content + scope.row.id" :class="item.content" v-else>
              {{ 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="'assetChangePagination'"
      :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="dialogRef" :config="dialogConfig" @close="dialogClose">
    <template #other>
      <div id="refreshContent" class="asset-dialog">
        <el-icon :size="24">
          <IconAlarm />
        </el-icon>
        <div id="refreshText" class="asset-content">
          <p>{{ $t('ASSET_MAINTANCE_REFRESH_TIP1') }}</p>
          <p>{{ $t('ASSET_MAINTANCE_REFRESH_TIP2') }}</p>
        </div>
      </div>
    </template>
  </Dialog>
  <SecondPassword ref="secondRef" @close="confirmReset" />
</template>
<style lang="scss" scoped>
.change-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;
    }

    :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;
          }
        }
      }
    }

    .status{
      display: flex;
    }
    
    .status-text{
      margin-left: 4px;
    }
  }
}
.refresh_btn {
  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;
    }
  }
}
.asset-dialog {
  display: flex;
}
.asset-content {
  margin-left: 16px;
}
.status-text{
  display: flex;
}
.icon-believable{
  svg{
    :deep(path){
      &:first-child {
        fill: #24AB36;
      }
    }
  }
}
.icon-unreliable{
  svg{
    :deep(path){
      &:first-child {
        fill: #F97611;
      }
    }
  }
}
.icon-power-off{
  svg{
    :deep(path){
      &:first-child {
        fill: #576372;
      }
    }
  }
}

</style>
<style lang="scss">
.hashTextBox{
  .hashText{
    line-break: anywhere;
  }
}
</style>
