<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import useStore from '@/stores';
import { traduction } from '@/utils/language';
import { _caculateTimeGap, _dateToStr } from '../utils/utils';
import {
  sensorServices,
  getSubjectType,
  downloadSensorLog,
  getTaskStatus,
  clearData,
  downLoadSelEvents,
  getRecordType,
  setRecordType
} from '../alarm.services';
import { IconCaretUp, IconXSolid, IconDelete, IconDownload } from '@computing/opendesign-icons';
import { showElMessage, compareObjectEqual, deepClone, formattingTime } from '@/utils/utils';
import { hasDetails, dealDetails } from '../utils/utils';
import GlobalStoreService from '@/services/gloabal-store-service';
import TableNoData from '@/components/TableNoData/TableNoData.vue';
import ErrorIcon from '@/components/ErrorIcon/ErrorIcon.vue';
import ClearableIcon from '@/components/ClearableIcon/ClearableIcon.vue';
import Dialog from '@/components/Dialog/Dialog.vue';
import { loading } from '@/utils/composition';
import { downloadFileWithResponse } from '@/utils/common-service';
import { UserPrivil } from '@/model/base-enum';
import { checkPrivil } from '@/apps/app-bmc/router/routes';

const store = useStore();
// 系统锁定状态
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const globalStoreService = new GlobalStoreService();
const errorMsg = traduction('COMMON_FAILED');
let total = ref(0);
let pageSize = ref(10);
let currentPage = ref(1);
const dialogRef = ref();
const loadingShow = ref(false);
const canSave = ref(false);
const recordType = ref('');
const preRecordType = ref('');

// 表格数据
const tableData: any = reactive([]);

// 主体类型可选列表
const objectTypeList: any = reactive([]);

// 主体类型的初始搜索值
const entityType = traduction('ALARM_EVENT_ALL');

const hasBasicConfig = checkPrivil(UserPrivil.baseConfig);

const options: any = reactive([
  {
    label: traduction('LINEAR_RECORD'),
    value: 'ClearAfterFull',
    disable: false,
    id: 1
  },
  {
    label: traduction('CIRCULAR_RECORD'),
    value: 'RotateAfterFull',
    disable: false,
    id: 2
  }
]);

// 二次确认弹框
const confirmConfig = reactive({
  id: 'clearDialog',
  content: traduction('COMMON_ASK_OK'),
  title: traduction('ALARM_OK')
});

function clearDialog() {
  if (isSystemLock.value) {
    return;
  }
  dialogRef.value.show();
}

function dialogClose(reason: boolean) {
  dialogRef.value.hide();
  if (reason) {
    loading(true);
    clearData()
      .then(res => {
        showElMessage('success', traduction('COMMON_SUCCESS'));
      })
      .catch(error => {
        showElMessage('error', errorMsg);
      })
      .finally(() => {
        getTableData();
        getEntityTypeData();
        loading(false);
      });
  }
}

// 点击下载图标
function download() {
  loadingShow.value = true;
  downloadSensorLog()
    .then(res => {
      const url = res.data.url;
      queryTask(url);
    })
    .catch(error => {
      showElMessage('error', errorMsg);
    })
    .finally(() => {
      loadingShow.value = false;
    });
}

// 查询下载进度
function queryTask(url: string) {
  getTaskStatus(url)
    .then(res => {
      const data = res.data;
      if (data) {
        if (data.prepare_progress === 100 && data.state === 'Completed') {
          beginDownLoad();
        } else if (data.prepare_progress <= 100) {
          queryTask(url);
        } else {}
      }
    })
    .catch(() => {
      showElMessage('error', traduction('COMMON_FAILED'));
    });
}
// 开始下载
function beginDownLoad() {
  downLoadSelEvents()
    .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 dialogConfig = reactive({
  visible: false,
  content: [] as string[],
  show: (val: string) => {
    dealDetails(val)?.forEach((item: any) => {
      dialogConfig.content.push(item);
    });
    dialogConfig.visible = true;
  },
  close: () => {
    dialogConfig.content = [];
    dialogConfig.visible = false;
  }
});

function handleSizeChange(val: number) {
  pageSize.value = val;
  currentPage.value = 1;
  getTableData();
}

// 获取主体类型
function getEntityTypeData() {
  objectTypeList.splice(0);
  getSubjectType().then((subjectType: any) => {
    const list = subjectType.data.List;
    const resList = list.map((item: { Label: string; ID: number }) => {
      return {
        label: item.Label,
        id: item.ID
      };
    });

    // 排序
    resList.sort((a: any, b: any) => {
      return a.label.localeCompare(b.label);
    });

    objectTypeList.push(...resList);
    // 全部
    objectTypeList.unshift({
      label: traduction('ALARM_EVENT_ALL'),
      id: -1
    });
    setSubject();
  });
}

// 获取请求参数
function getParams() {
  const params: any = {
    Skip: pageSize.value * (currentPage.value - 1),
    Top: pageSize.value
  };
  return params;
}

// 获取表格数据
function getTableData() {
  tableData.splice(0);
  globalStoreService.setValue('isLoading', true);
  sensorServices(getParams())
    .then((res: any) => {
      if (res?.data?.List) {
        tableData.push(...res.data.List);
        total.value = res.data.TotalCount;
        setSubject();
      }
      globalStoreService.setValue('isLoading', false);
    })
    .catch(() => {
      globalStoreService.setValue('isLoading', false);
    });
}

function getRecord() {
  globalStoreService.setValue('isLoading', true);
  getRecordType()
    .then((res: any) => {
      if (res?.data?.SelOverWritePolicy) {
        canSave.value = false;
        recordType.value = res.data.SelOverWritePolicy;
        preRecordType.value = res.data.SelOverWritePolicy;
      }
      globalStoreService.setValue('isLoading', false);
    })
    .catch(() => {
      globalStoreService.setValue('isLoading', false);
    });
}

function saveRecord() {
  globalStoreService.setValue('isLoading', true);
  setRecordType({SelOverWritePolicy: recordType.value})
    .then((res: any) => {
      if (res?.data?.SelOverWritePolicy) {
        canSave.value = false;
        recordType.value = res.data.SelOverWritePolicy;
        preRecordType.value = res.data.SelOverWritePolicy;
      }
      globalStoreService.setValue('isLoading', false);
      showElMessage('success', traduction('COMMON_SUCCESS'));
    })
    .catch(() => {
      globalStoreService.setValue('isLoading', false);
      showElMessage('error', traduction('COMMON_FAILED'));
    });
}

// 根据两次请求的数据进行 主体类型 的设置
function setSubject() {
  if (objectTypeList.length) {
    tableData.forEach((item: any) => {
      const checkItem = objectTypeList.find((subjectItem: any) => {
        return subjectItem.id === item.Subject;
      });

      if (checkItem) {
        item.Subject = checkItem.label;
      }
    });
  }
}

function setCanSave(value: any) {
  if (value !== preRecordType.value) {
    canSave.value = true;
  } else {
    canSave.value = false;
  }
}

onMounted(() => {
  getTableData();
  getRecord();
  getEntityTypeData();
});
</script>
<template>
  <div class="sensor-event">
    <div class="collapse">
      <div class="collapse-header">
        <div class="left" v-if="hasBasicConfig">
          <el-form>
            <el-form-item :label="$t('SENSOR_RECORD')">
              <el-radio-group
                id="recordLevel"
                v-model="recordType"
                :disabled="isSystemLock"
              >
                <el-radio
                  v-for="(item, index) in options"
                  :key="item.id"
                  v-addId.radio="'recordLevel' + index"
                  :label="item.value"
                  @change="setCanSave"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <el-button type="primary" id="saveRecord" class="saveRecord" @click="saveRecord" :disabled="!canSave || isSystemLock">
            {{$t('COMMON_SAVE')}}
          </el-button>
        </div>
        <div class="left" v-else></div>
        <div class="right">
          <el-tooltip
            v-if="!loadingShow"
            effect="dark"
            :content="$t('COMMON_DOWN')"
            placement="top"
            trigger-keys
          >
            <el-button
              id="sensorDownload"
              :disabled="loadingShow"
              :class="loadingShow ? 'disLoading' : ''"
              class="download isIcon"
              @click="download"
            >
              <template #icon>
                <!-- 下载 -->
                <IconDownload />
              </template>
            </el-button>
          </el-tooltip>
          <el-button
            v-else
            id="sensorDownLoading"
            :disabled="loadingShow"
            :class="loadingShow ? 'disLoading' : ''"
            class="download isIcon"
          >
            <template #icon>
              <!-- 加载中 -->
              <Loading :state="true" />
            </template>
          </el-button>
          <Dialog ref="dialogRef" :config="confirmConfig" @close="dialogClose"></Dialog>
        </div>
      </div>
    </div>

    <!--  表格数据 -->
    <el-table v-addId.table="'sensorTable'" :data="tableData" border resizable>
      <el-table-column min-width="5%" :label="$t('EVENT_ORDER')">
        <template #default="scope">
          <span class="sensorId">{{ scope.row.ID }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="15%" :label="$t('COMMON_TIME')">
        <template #default="scope">
          <span class="sensorTime">{{ scope.row.Timestamp }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="15%" :label="$t('SENSOR_NAME')">
        <template #default="scope">
          <span class="sensorName">{{ scope.row.SensorName }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="15%" :label="$t('EVENT_LEVEL')">
        <template #default="scope">
          <span>
            <el-tag
              v-if="scope.row.Level === 'Critical'"
              v-addTooltip.elTag
              class="sensorLevel"
              type="danger"
            >
              {{ $t('ALARM_EVENT_CRITICAL') }}
            </el-tag>
            <el-tag
              v-if="scope.row.Level === 'Minor'"
              v-addTooltip.elTag
              class="sensorLevel"
              type="warning"
            >
              {{ $t('ALARM_EVENT_MINOR') }}
            </el-tag>
            <el-tag
              v-if="scope.row.Level === 'Major'"
              v-addTooltip.elTag
              class="sensorLevel"
              type="major"
            >
              {{ $t('ALARM_EVENT_MAJOR') }}
            </el-tag>
            <el-tag
              v-if="scope.row.Level === 'Informational'"
              v-addTooltip.elTag
              class="sensorLevel"
              type="primary"
            >
              {{ $t('ALARM_EVENT_NORMAL') }}
            </el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column min-width="15%" :label="$t('SENSOR_TYPE')">
        <template #default="scope">
          <span class="sensorType">{{ scope.row.SensorType }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="15%" :label="$t('EVENT_STATUS')">
        <template #default="scope">
          <span class="sensorStatus">{{ scope.row.Status }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="20%" show-overflow-tooltip :label="$t('COMMON_DESCRIPTION')">
        <template #default="scope">
          <span class="sensorDescription">{{ scope.row.Description }}</span>
        </template>
      </el-table-column>

      <template #empty>
        <TableNoData />
      </template>
    </el-table>
    <!-- 处理建议dialog -->
    <div v-if="dialogConfig.visible" v-reqKeepAlive.dialog>
      <el-dialog
        v-model="dialogConfig.visible"
        :close-on-click-modal="false"
        width="432px"
        :title="$t('EVENT_SUGGESTION')"
        @close="dialogConfig.close"
      >
        <div id="handlingSuggestion">
          <div v-for="item in dialogConfig.content" :key="item">{{ item }}</div>
        </div>
        <template #footer>
          <el-button id="saveBtn" size="small" type="primary" @click="dialogConfig.close">
            {{ $t('ALARM_OK') }}
          </el-button>
        </template>
      </el-dialog>
    </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="getTableData"
    />
  </div>
</template>
<style lang="scss" scoped>
.sensor-event {
  flex: 1;
  background-color: var(--o-bg-color-base);
  border-radius: 4px;
  padding: 16px;
  display: flex;
  flex-direction: column;

  .el-table {
    flex: 1;
    .el-tag {
      width: 64px;
      height: 16px;
      padding: 0;
    }
    :deep(.el-tooltip){
      width: calc(100% - 4px) !important;
    }
  }

  .collapse-header {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .left {
      display: flex;
      align-items: center;
      .saveRecord{
        margin-left: 32px;
        :deep(span){
          min-width: 0px !important;
        }
      }
      .el-form-item{
        margin-bottom: 0px;
      }
    }

    .right {
      display: flex;
      align-items: center;
      .locking {
        cursor: not-allowed !important;
      }
      .el-icon {
        font-size: 16px;
        cursor: pointer;
        color: var(--o-text-color-tertiary);
        &:hover {
          color: var(--o-color-primary);
        }
      }
      .disLoading {
        background-color: var(--o-bg-color-placeholder);
      }
      .isIcon {
        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;
          }
        }
      }

      .del {
        margin-right: 8px;
      }
    }
  }

  :deep(.el-radio-button__inner) {
    font-weight: normal;
  }
  :deep(.el-date-editor) {
    height: 32px;
    margin-bottom: 4px;
    max-width: 240px;
  }
  .caret-down {
    transform: rotate(0deg);
    transition: transform 0.2s;
  }
  .caret-up {
    transform: rotate(180deg);
    transition: transform 0.2s;
  }

  :deep(.el-form-item) {
    margin-bottom: 8px;
  }
}
</style>
