<template>
  <div class="comp-hpc-list">
    <Dialog v-model="visible" diaTitle="作业执行列表" width="80%" height="90%" @close="closeFun">
      <div class="content">
        <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-change="changeTabsFun">
          <el-tab-pane label="HPC作业列表" name="cloud">
            <div class="table white">
              <BaseTable
                ref="baseTableRef"
                tableName="HPC_LIST_TABLE"
                :api="queryJobsApi"
                :actionList="actionList"
                fullHeight
              >
                <template #leftOptions>
                  <el-button type="primary" @click="batchCancalFun">批量取消</el-button>
                  <el-button type="primary" @click="batchDeleteFun">批量删除</el-button>
                </template>
                <template #totalElapsedTime="{ row }">
                  <span>{{ row.totalElapsedTime ? row.totalElapsedTime + 'h' : '--' }}</span>
                </template>
                <template #jobStatus="{ row }">
                  <el-tag v-if="row.jobStatus === 'Finished'" type="success">{{
                    WORK_STATUS.O[row.jobStatus]
                  }}</el-tag>
                  <el-tag type="info" v-else-if="row.jobStatus === 'Canceled'">{{
                    WORK_STATUS.O[row.jobStatus]
                  }}</el-tag>
                  <el-tag v-else-if="row.jobStatus === 'Failed'" type="danger">{{
                    WORK_STATUS.O[row.jobStatus]
                  }}</el-tag>
                  <el-tag v-else type="primary">{{ WORK_STATUS.O[row.jobStatus] }}</el-tag>
                </template>
                <template #software="{ row }">
                  <div class="img-box">
                    <img width="14" :src="getAppImg(row)" alt="" />
                    <span>{{ row.software }}</span>
                  </div>
                </template>
              </BaseTable>
            </div>
          </el-tab-pane>
          <el-tab-pane label="HPC资源详情" name="resources">
            <div class="table">
              <div class="chart-box">
                <div class="chart-box-left">
                  <commonFilterChart
                    title="资源运行状态"
                    :charts-id="'chart-1'"
                    :bar-type="'pieChart'"
                    :option="chartOptionOne"
                  ></commonFilterChart>
                </div>
                <div class="chart-box-right">
                  <commonFilterChart
                    title="节点分配状态"
                    :charts-id="'chart-2'"
                    :bar-type="'pieChart'"
                    :option="chartOptionTwo"
                  ></commonFilterChart>
                </div>
              </div>
              <div class="pege-table">
                <BaseTable
                  ref="baseTableRef2"
                  :showSetting="false"
                  tableName="HPC_RESOURCE_LIST"
                  fullHeight
                  hidePagination
                  :data="hpcSourceList"
                >
                  <template #nodeStatus="{ row }">
                    <el-tag type="success" v-if="row.nodeStatus === 'Online'">在线</el-tag>
                    <el-tag type="info" v-else-if="row.nodeStatus === 'Offline'">离线</el-tag>
                    <el-tag type="warning" v-else>异常</el-tag>
                  </template>

                  <template #efficiency="{ row }">
                    <span>{{ row.freeCores }}</span
                    >/<span>{{ row.totalCores }}</span
                    >|<span>{{ getefficiencyFun(row) }}</span>
                  </template>
                  <template #nodeName="{ row }">
                    <el-button link type="primary">{{ row.nodeName }}</el-button>
                  </template>
                </BaseTable>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { delHpcJobsApi, queryHpcResourceApi, queryJobsApi, stopHpcJobApi } from '@/api/pbs/pbs';
import Dialog from '@/components/common/dialog/index.vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import { ElMessage } from 'element-plus';
import { useDict } from '@/utils/useDict';
import { queryAllApplicationApi } from '@/api/system/application';
import { FileUtil } from '@/utils/file';
import commonFilterChart from '@/components/common/echartCard/commonFilterChart.vue';

const { WORK_STATUS } = useDict('WORK_STATUS');

interface Props {
  modelValue: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
});

const baseTableRef = ref();
const baseTableRef2 = ref();
const emit = defineEmits(['update:modelValue']);
const visible = ref(false);
const activeName = ref('cloud');
watch(
  () => props.modelValue,
  (val: boolean) => {
    visible.value = val;
  }
);

const actionList = ref([
  {
    title: '取消',
    type: 'warning',
    needConfirm: true,
    confirmTip: '确定取消选中计算任务吗？',
    click: (row: any) => {
      stopFun(row);
      ElMessage.success('操作成功');
      baseTableRef.value.resetFun();
    },
    hide: (row: any) => {
      return ['Canceled', 'Finished', 'Failed'].includes(row.jobStatus);
    },
  },
  {
    title: '删除',
    type: 'danger',
    needConfirm: true,
    confirmTip: '确定删除选中计算任务吗？',
    click: (row: any) => {
      const jobIds = [row.jobId];
      deleteFun(jobIds);
    },
    hide: (row: any) => {
      return !['Canceled', 'Finished', 'Failed'].includes(row.jobStatus);
    },
  },
]);

const stopFun = async (data: any) => {
  const params = {
    jobId: data.jobId,
  };
  await stopHpcJobApi(params).then((res: any) => {
    if (res.code === 200) {
    }
  });
};

const deleteFun = async (ids: any) => {
  const params = {
    hpcJobIds: ids,
  };

  await delHpcJobsApi(params).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('操作成功');
      baseTableRef.value.resetFun();
    }
  });
};

// 批量取消任务
const batchCancalFun = async () => {
  const checks: any = baseTableRef.value.tableRef.getCheckboxRecords();

  if (checks.length) {
    for (let i = 0; i < checks.length; i++) {
      await stopFun(checks[i]);
    }
    baseTableRef.value.resetFun();
  }
};

// 批量删除任务
const batchDeleteFun = async () => {
  const checks: any = baseTableRef.value.tableRef.getCheckboxRecords();
  if (checks.length) {
    const ids = checks.map((item: any) => {
      return item.jobId;
    });

    await deleteFun(ids);
  }
};

const closeFun = () => {
  emit('update:modelValue', false);
};

const getAppImg = (row: any) => {
  const appImg: any =
    appList.value.find((item: any) => {
      return item.uuid === row.softwareId;
    })?.img || '';
  return appImg;
};

const appList = ref<any>([]);

const getAppInfo = async () => {
  const param = {
    appName: '',
    current: 1,
    size: 999,
  };

  try {
    const res: any = await queryAllApplicationApi(param);
    if (res && res.code === 200) {
      appList.value = res.data.data.map((item: any) => {
        return {
          label: item.appName,
          img: FileUtil.getFilePreviewImgPathUrl(item.appImage),
          uuid: item.uuid,
        };
      });
    }
  } catch {}
};

const hpcSourceList = ref<any>([]);
const changeTabsFun = () => {
  if (activeName.value === 'resources') {
    queryHpcResourceFun();
  }
};

const queryHpcResourceFun = async () => {
  try {
    const res: any = await queryHpcResourceApi();
    if (res && res.code === 200) {
      hpcSourceList.value = res.data.nodeList;

      initChartOneFun(res.data);
      initChartTwoFun(res.data);
    }
  } catch (error) {
    console.log(error);
  }
};
const colorList = ref<any>(['#409eff', '#67c23a', '#909399']);

const chartOptionOne = ref();

const initChartOneFun = (data: any) => {
  chartOptionOne.value = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: '70%',
      top: 'center',
      icon: 'circle',
    },
    series: [
      {
        type: 'pie',
        radius: ['60%', '70%'],
        center: ['30%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold',
          },
        },
        data: [
          { value: data.totalNodes || '', name: '全部' },
          { value: data.totalNodes - data.freeNodes || '', name: '已使用' },
          { value: data.freeNodes || '', name: '未使用' },
        ],
        itemStyle: {
          color: function (params: any) {
            return colorList.value[params.dataIndex];
          },
        },
      },
    ],
  };
};

const chartOptionTwo = ref();

const initChartTwoFun = (data: any) => {
  chartOptionTwo.value = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: '70%',
      top: 'center',
      icon: 'circle',
    },
    series: [
      {
        type: 'pie',
        radius: ['60%', '70%'],
        center: ['30%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold',
          },
        },
        data: [
          { value: data.totalCores || '', name: '全部' },
          { value: data.usedCores || '', name: '已使用' },
          { value: data.freeCores || '', name: '未使用' },
        ],
        itemStyle: {
          color: function (params: any) {
            return colorList.value[params.dataIndex];
          },
        },
      },
    ],
  };
};

// 获取CPU使用效率
const getefficiencyFun = (row: any) => {
  let num: any = '0';

  if (row.totalCores) {
    if (row.freeCores === row.totalCores || !row.usedCores) {
      num = '0';
    } else if (row.usedCores === row.totalCores || !row.freeCores) {
      num = '100%';
    } else {
      num = (row.usedCores / row.totalCores) * 100 + '%';
    }
  }

  return num;
};

onMounted(async () => {
  await getAppInfo();
});
</script>

<style lang="scss" scoped>
.comp-hpc-list {
}

.content {
  height: 100%;

  .table {
    height: 100%;
    padding: 10px;
    background-color: #f2f3f5;

    .chart-box {
      width: 100%;
      height: 350px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .chart-box-left,
      .chart-box-right {
        width: calc(50% - 5px);
        height: 100%;
        background-color: #fff;
      }
    }

    .pege-table {
      width: 100%;
      height: calc(100% - 360px);
      margin-top: 10px;
      background-color: #fff;
    }
  }

  .white {
    background-color: #fff;
  }
}

.img-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;

  .img {
    border-radius: 2px;
  }
}
</style>
