<script lang="ts" setup>
import { traduction } from '@/utils/language';
import { ref, nextTick, computed, onUnmounted } from 'vue';
import useStore from '@/stores';
import { ITableColumns } from '@/model/base-interface';
import { getTaskData, deleteJobs, cancelJob } from '../sp.server';
import taskParams from './SpTaskParams.vue';
import Date from '@/utils/date';
import { showElMessage } from '@/utils/utils';
import { loading } from '@/utils/composition';
let timer: number | null = null;
const store = useStore();
let isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});

const props = defineProps({
  type: {
    type: String,
    required: true,
    default: '',
  },
});
let tableData = ref([] as any[]);
const taskForm = ref();
const jobParams = ref({});
const columns: ITableColumns[] = [
  {
    title: 'SP_TASK_ID',
    width: '12.5%',
    content: 'Id',
  },
  {
    title: 'SP_TASK_TYPE',
    width: '12.5%',
    content: 'JobType',
  },
  {
    title: 'IBMC_MANUAL_EFFECTIVE',
    width: '12.5%',
    content: 'aliveModel',
  },
  {
    title: 'SP_TASK_STATUS',
    width: '12.5%',
    content: 'JobState',
  },
  {
    title: 'SP_TASK_VALIDATE_TIME',
    width: '12.5%',
    content: 'InitialStartTime',
  },
  {
    title: 'SP_TASK_CREATE_TIME',
    width: '12.5%',
    content: 'CreateTime',
  },
  {
    title: 'COMMON_OPERATE',
    width: '12.5%',
    content: 'operate',
  },
];
const currentStatus = ref('');
// 删除终止任务弹窗设置
const operateType = ref('delete');
const tipRef = ref();
const dialogConfig = computed(() => {
  return {
    title: ['Completed', 'Cancelled', 'Exception'].includes(currentStatus.value)
      ? traduction('SP_TASK_DELETE')
      : traduction('SP_TASK_STOP'),
    content: ['Running', 'Pending'].includes(currentStatus.value)
      ? traduction('SP_CONFIRM_TIP')
      : traduction('SP_DELETE_TASK_TIP'),
  };
});
let typeMap = {
  OS: 'SPOSInstall',
  Diagnose: 'SPDiagnose',
  Update: 'SPFWUpdate',
};
let allTask = ref([]);
function getZeroAreaTime(timeStrap: number, showSec: boolean = false) {
  let date = sessionStorage.getItem('DateTime') || '';
  let area = date?.indexOf('UTC') > 0 ? 'UTC' : 'GMT';
  let ms = `${timeStrap} ${area}+0000`;
  return `${new Date(ms).pattern('yyyy/MM/dd')} ${new Date(ms).pattern('HH:mm')}:${showSec ? new Date(ms).pattern('ss') : '00' }`;
}
function init(refreshConfig = false) {
  let JobType = typeMap[props.type];
  if (refreshConfig) {
    loading(true);
  }
  getTaskData(JobType)
    .then((res: any) => {
      tableData.value.splice(0);
      res.Jobs.sort(
        (a: { CreateTime: number }, b: { CreateTime: number }) => a.CreateTime - b.CreateTime,
      );
      if (res.Jobs.length) {
        let jobs = res.Jobs[res.Jobs.length - 1];
        jobs.aliveModel = jobs.InitialStartTime
          ? traduction('SP_TASK_LATER')
          : traduction('SP_TASK_IMMEDIATELY');
        jobs.CreateTime = jobs.CreateTime.replace('T', ' ');
        jobs.InitialStartTime = jobs.InitialStartTime.replace('T', ' ');
        jobs.CreateTime = getZeroAreaTime(jobs.CreateTime, true);
        tableData.value.push(jobs);
      }
      allTask.value = res.Jobs || [];
      jobParams.value = tableData.value[0] || '{}';
      if (refreshConfig || !tableData.value.length) {
        queryConfigParam(true, jobParams.value);
      }
      currentStatus.value = tableData.value[0]?.JobState;
    }).finally(() => {
      loading(false);
    });
}

function startTimer() {
  if (timer) {
    clearTimer();
  }
  timer = window.setInterval(() => {
    init(false);
  }, 10000);
}
function clearTimer() {
  clearInterval(timer as number);
}
onUnmounted(() => {
  clearTimer();
});
function queryConfigParam(flag: boolean, p: any) {
  nextTick(() => {
    taskForm.value?.queryConfig(flag, p);
  });
}
const STATUS_MAP = {
  Completed: traduction('SP_STATUS_SUCCESS'),
  Pending: traduction('SP_STATUS_WAITING'),
  Running: traduction('SP_STATUS_RUNNING'),
  Cancelled: traduction('SP_STATUS_STOP'),
  Exception: traduction('STORE_ABNORMAL'),
  Unknow: traduction('LICENSE_STATUS_UNKNOWN'),
};
const getStatus = (row: any) => {
  return STATUS_MAP[row.JobState] || STATUS_MAP.Unknow;
};

let currentjob = ref('');
function deleteJob() {
  deleteJobs([currentjob.value]).then(res => {
    if (res.status === 200) {
      showElMessage('success', traduction('COMMON_SUCCESS'));
      init(true);
      currentjob.value = '';
    } else {
      showElMessage('error', res.data || traduction('COMMON_FAILED'));
    }
  });
}
// 删除操作
function delCert(row: any) {
  currentjob.value = row.Id;
  operateType.value = 'delete';
  if (['Completed', 'Cancelled', 'Pending'].includes(row.JobState)) {
    nextTick(() => {
      tipRef.value.show();
    });
    return;
  }
  deleteJob();
}
// 终止操作
function cancelledJob() {
  cancelJob({ JobId: currentjob.value, JobState: 'Cancelled' }).then(res => {
    if (res.status === 200) {
      showElMessage('success', traduction('COMMON_SUCCESS'));
      init(true);
      currentjob.value = '';
      operateType.value = '';
    } else {
      showElMessage('error', res.data || traduction('COMMON_FAILED'));
    }
  });
}
// 终止操作
function stop(row: any) {
  currentjob.value = row.Id;
  operateType.value = 'stop';
  if (['Running', 'Pending'].includes(row.JobState)) {
    nextTick(() => {
      tipRef.value.show();
    });
    return;
  }
  cancelledJob();
}
const closeHandle = (val: boolean) => {
  tipRef.value.hide();
  if (val) {
    if (operateType.value === 'delete') {
      deleteJob();
      queryConfigParam(false, '{}');
    } else {
      cancelledJob();
    }
    startTimer();
  }
};

function taskCreated() {
  init(true);
  startTimer();
}
function taskDelete() {
  init(false);
  startTimer();
}
const titleMap = {
  OS: 'SP_OS_TASK_TITLE',
  Update: 'SP_UPGRADE_TASK_TITLE',
  Diagnose: 'SP_DIAGNOSIS_TASK_TITLE',
};
const getTitle = computed(() => {
  return titleMap[props.type] || 'SP_TITLE';
});

init(true);
startTimer();
</script>
<template>
  <div :id="`taskPage${type}`" class="task-page">
    <div class="task-top">
      <div class="task-title">{{ $t('SP_TASK_REPO') }}</div>
      <div v-if="tableData.length === 0" class="is-empty">
        {{ $t('SP_TASK_REPO_EMPTY') }}
      </div>
      <el-table
        v-else
        v-addId.table="'taskTable'"
        :data="tableData"
        border
        class="tableHeight reset-table"
      >
        <el-table-column
          v-for="item in columns"
          :key="item.title"
          :label="$t(item.title)"
          :min-width="item.width"
          :show-overflow-tooltip="item.content !== 'JobState' && item.content !== 'operate'"
        >
          <template #default="scope">
            <div
              v-if="item.content === 'JobState'"
              :id="item.content + scope.row.Id"
              class="status"
            >
              <div class="comon-state" :class="[scope.row.JobState]">
                {{ getStatus(scope.row) }}
              </div>
            </div>
            <div v-else-if="item.content === 'InitialStartTime'" :id="item.content + scope.row.Id">
              <div>
                {{
                  scope.row.InitialStartTime
                    ? getZeroAreaTime(scope.row.InitialStartTime)
                    : '-'
                }}
              </div>
            </div>
            <div
              v-else-if="item.content === 'operate'"
              :id="item.content + scope.row.Id"
              class="status"
            >
              <span
                v-if="['Completed', 'Exception', 'Cancelled'].includes(scope.row.JobState)"
                :id="`delTask${scope.$index}`"
                :class="['btn', isSystemLock ? 'disabled-btn' : '']"
                @click="delCert(scope.row)"
              >
                {{ $t('SP_TASK_DELETE') }}
              </span>
              <span
                v-if="['Running'].includes(scope.row.JobState) && scope.row.Abortable || ['Pending'].includes(scope.row.JobState)"
                :id="`delTask${scope.$index}`"
                :class="['btn', isSystemLock ? 'disabled-btn' : '']"
                @click="stop(scope.row)"
              >
                {{ $t('SP_TASK_STOP') }}
              </span>
            </div>
            <span v-else :id="item.content + scope.row.Id" :class="item.content">
              {{ scope.row[item.content] }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="task-content">
      <div class="sp-title">{{ $t(getTitle) }}</div>
      <taskParams
        ref="taskForm"
        :all-task="allTask"
        :task-status="currentStatus"
        :job-params="jobParams"
        :task-type="type"
        @task-created="taskCreated"
        @delete-jobs="taskDelete"
      />
    </div>
  </div>
  <Dialog ref="tipRef" class="tip" :config="dialogConfig" @close="closeHandle"></Dialog>
</template>

<style lang="scss" scoped>
.task-page {
  .task-top,
  .email-table {
    padding: 24px;
    background: var(--o-bg-color-base);
    border-radius: 4px;
  }

  height: calc(100% - 104px);

  .task-top {
    .is-empty {
      margin: 41px auto 56px;
      text-align: center;
      font-size: 12px;
      color: #8d98aa;
      line-height: 16px;
    }
    margin-bottom: 16px;
    :deep(.el-select) {
      width: 320px;
    }
    .btn {
      margin-right: 8px;
      cursor: pointer;
      font-size: 12px;
      color: var(--o-color-primary);

      &:hover {
        color: var(--o-color-primary-secondary);
      }
    }
    .task-title {
      font-size: 16px;
      color: var(--o-text-color-primary);
      line-height: 24px;
      font-weight: bold;
      margin-bottom: 16px;
    }
  }

  .task-content {
    padding: 24px;
    background: var(--o-bg-color-base);
    border-radius: 4px;
    .sp-title {
      font-size: 16px;
      color: var(--o-text-color-primary);
      line-height: 24px;
      font-weight: bold;
      margin-bottom: 16px;
    }
  }

  .tableHeight {
    min-height: 0px;
    :deep(.el-table__inner-wrapper) {
      min-height: 0px;
    }
    :deep(.el-table__body-wrapper) {
      min-height: 0px;
      .el-table__cell {
        border-bottom: none;
      }

      .el-scrollbar {
        min-height: 0px;

        .el-scrollbar__wrap {
          min-height: 0px;
        }
      }
    }
  }

  :deep(.task-top .el-input) {
    width: 320px;
  }
  .comon-state {
    display: inline-block;
    background-color: var(--o-text-color-tertiary);
    color: #fff;
    height: 16px;
    line-height: 16px;
    padding: 0 14px;
    border-radius: var(--i-button-border-radius);
    &.Completed {
      background-color: var(--o-color-success);
    }
    &.Pending {
      background-color: #ebaf00;
    }
    &.Running {
      background-color: var(--o-color-primary);
    }
    &.Cancelled {
      background-color: var(--o-text-color-tertiary);
    }
    &.Exception {
      background-color: var(--o-text-color-tertiary);
    }
  }
}
</style>
