<template>
  <div>
    <div class="title"><span>{{ $t('resourcesManagement.resSceneManagement') }}</span></div>
    <div class="tools-bar">
      <div>
        <el-select class="select" size="medium" v-model="selTaskType" @change="selectChange">
          <el-option v-for="item in taskTypeList" :key="item.k" :label="item.v" :value="item.k" />
        </el-select>
        <el-select class="select" size="medium" v-model="selIsExclusive" @change="selectChange">
          <el-option v-for="item in isExclusiveList" :key="item.k" :label="item.v" :value="item.k" />
        </el-select>
        <el-select class="select" size="medium" v-model="selAiCenter" @change="selectChange">
          <el-option v-for="item in aiCenterList" :key="item.k" :label="item.v" :value="item.k" />
        </el-select>
        <el-select class="select" size="medium" v-model="selQueue" @change="selectChange">
          <el-option v-for="item in queueList" :key="item.k" :label="item.v" :value="item.k" />
        </el-select>
      </div>
      <div>
        <el-button type="primary" icon="el-icon-plus" size="medium" @click="showDialog('add')">
          {{ $t('resourcesManagement.addResSceneBtn') }}</el-button>
      </div>
    </div>
    <div class="table-container">
      <div style="min-height:600px;">
        <el-table border :data="tableData" style="width: 100%" v-loading="loading" stripe>
          <el-table-column prop="ID" label="ID" align="center" header-align="center" width="60"></el-table-column>
          <el-table-column prop="SceneName" :label="$t('resourcesManagement.resSceneName')" align="center"
            header-align="center"></el-table-column>
          <el-table-column prop="JobTypeStr" :label="$t('resourcesManagement.jobType')" align="center"
            header-align="center" width="120">
          </el-table-column>
          <el-table-column prop="IsExclusiveStr" :label="$t('resourcesManagement.isExclusive')" align="center"
            header-align="center" width="120">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.IsExclusive ? 'red' : '' }">{{ scope.row.IsExclusiveStr }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ExclusiveOrg" :label="$t('resourcesManagement.exclusiveOrg')" align="center"
            header-align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.IsExclusive ? scope.row.ExclusiveOrg : '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="AiCenterStr" :label="$t('resourcesManagement.aiCenter')" align="center"
            header-align="center">
            <template slot-scope="scope">
              <div v-if="!scope.row.Queues.length">--</div>
              <div v-for="item in scope.row.Queues" :key="item.QueueId">
                <span>{{ item.AiCenterName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="QueueStr" :label="$t('resourcesManagement.resQueue')" align="center"
            header-align="center">
            <template slot-scope="scope">
              <div v-if="!scope.row.Queues.length">--</div>
              <div v-for="item in scope.row.Queues" :key="item.QueueId">
                <span>{{ item.QueueStr }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="SpecsList" :label="$t('resourcesManagement.resourceSpecification')" align="left"
            header-align="center" min-width="180">
            <template slot-scope="scope">
              <div v-for="item in scope.row.SpecsList" :key="item.k">
                <span>{{ item.v }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('operation')" align="center" header-align="center" width="100">
            <template slot-scope="scope">
              <span class="op-btn" @click="showDialog('edit', scope.row)">{{ $t('edit') }}</span>
              <span class="op-btn" style="color:red" @click="deleteRow(scope.row)">{{ $t('delete') }}</span>
            </template>
          </el-table-column>
          <template slot="empty">
            <span style="font-size: 12px">{{
                loading ? $t('loading') : $t('noData')
            }}</span>
          </template>
        </el-table>
      </div>
      <div class="__r_p_pagination">
        <div style="margin-top: 2rem">
          <div class="center">
            <el-pagination background @current-change="currentChange" :current-page="pageInfo.curpage"
              :page-sizes="pageInfo.pageSizes" :page-size="pageInfo.pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <SceneDialog :visible.sync="sceneDialogShow" :type="sceneDialogType" :data="sceneDialogData"
      @confirm="sceneDialogConfirm"></SceneDialog>
  </div>
</template>

<script>
import SceneDialog from '../components/SceneDialog.vue';
import { getQueueList, getResQueueCode, getResSceneList, updateResScene, getAiCenterList } from '~/apis/modules/resources';
import { JOB_TYPE, CLUSTERS, ACC_CARD_TYPE } from '~/const';
import { getListValueWithKey } from '~/utils';
import { formatDate } from 'element-ui/lib/utils/date-util';

export default {
  data() {
    return {
      selTaskType: '',
      taskTypeList: [{ k: '', v: this.$t('resourcesManagement.allJobType') }, ...JOB_TYPE],
      selIsExclusive: '',
      isExclusiveList: [{ k: '', v: this.$t('resourcesManagement.allExclusiveAndCommonUse') }, { k: '1', v: this.$t('resourcesManagement.exclusive') }, { k: '2', v: this.$t('resourcesManagement.commonUse') }],
      selQueue: '',
      queueList: [{ k: '', v: this.$t('resourcesManagement.allResQueue') }],
      clusterList: [...CLUSTERS],
      selAiCenter: '',
      aiCenterList: [{ k: '', v: this.$t('resourcesManagement.allAiCenter') }],
      accCardTypeList: [...ACC_CARD_TYPE],
      loading: false,
      tableData: [],
      pageInfo: {
        curpage: 1,
        pageSize: 10,
        pageSizes: [10],
        total: 0,
      },
      sceneDialogShow: false,
      sceneDialogType: 'add',
      sceneDialogData: {},
    };
  },
  components: { SceneDialog },
  methods: {
    getAiCenterList() {
      getAiCenterList().then(res => {
        res = res.data;
        if (res.Code === 0) {
          const list = res.Data;
          const data = list.map(item => {
            return {
              k: item.AiCenterCode,
              v: item.AiCenterName
            };
          });
          this.aiCenterList.splice(1, Infinity, ...data);
        }
      }).catch(err => {
        console.log(err);
      });
    },
    getQueueList() {
      getResQueueCode().then(res => {
        res = res.data;
        if (res.Code === 0) {
          const data = res.Data;
          const list = [];
          for (let i = 0, iLen = data.length; i < iLen; i++) {
            const item = data[i];
            list.push({
              k: item.ID,
              v: `${item.QueueCode}(${getListValueWithKey(this.clusterList, item.Cluster)} - ${item.AiCenterName})`,
            });
          }
          this.queueList.push(...list);
        }
      }).catch(err => {
        console.log(err);
      });
    },
    getTableData() {
      const params = {
        jobType: this.selTaskType,
        IsExclusive: this.selIsExclusive,
        queue: this.selQueue,
        center: this.selAiCenter,
        page: this.pageInfo.curpage,
        pagesize: this.pageInfo.pageSize,
      };
      this.loading = true;
      getResSceneList(params).then(res => {
        this.loading = false;
        res = res.data;
        if (res.Code === 0) {
          const list = res.Data.List;
          const data = list.map((item) => {
            const Specs = item.Specs;
            const specsList = [];
            const queues = [];
            const queueIds = [];
            let cluster = '';
            for (let i = 0, iLen = Specs.length; i < iLen; i++) {
              const Spec = Specs[i];
              // const NGPU = `${Spec.ComputeResource}:${Spec.AccCardsNum === 0 ? '0' : Spec.AccCardsNum + '*' + getListValueWithKey(this.accCardTypeList, Spec.AccCardType)}`;
              const NGPU = `${Spec.ComputeResource}:${Spec.AccCardsNum + '*' + getListValueWithKey(this.accCardTypeList, Spec.AccCardType)}`;
              specsList.push({
                k: Spec.ID,
                v: `${NGPU}, CPU:${Spec.CpuCores}, ${this.$t('resourcesManagement.gpuMem')}:${Spec.GPUMemGiB}GB, ${this.$t('resourcesManagement.mem')}:${Spec.MemGiB}GB, ${this.$t('resourcesManagement.shareMem')}:${Spec.ShareMemGiB}GB, ${this.$t('resourcesManagement.unitPrice')}:${Spec.UnitPrice}${this.$t('resourcesManagement.point_hr')}`,
              });
              cluster = Spec.Cluster;
              if (queueIds.indexOf(Spec.QueueId) < 0) {
                queues.push({
                  QueueId: Spec.QueueId,
                  QueueCode: Spec.QueueCode,
                  AiCenterCode: Spec.AiCenterCode,
                  AiCenterName: Spec.AiCenterName,
                  QueueStr: `${Spec.QueueCode}(${getListValueWithKey(this.clusterList, Spec.Cluster)} - ${Spec.AiCenterName})`,
                });
                queueIds.push(Spec.QueueId);
              }
            }
            return {
              ID: item.ID,
              SceneName: item.SceneName,
              JobType: item.JobType,
              JobTypeStr: getListValueWithKey(this.taskTypeList, item.JobType),
              IsExclusive: item.IsExclusive,
              IsExclusiveStr: getListValueWithKey(this.isExclusiveList, item.IsExclusive ? '1' : '2'),
              ExclusiveOrg: item.ExclusiveOrg,
              Cluster: cluster,
              QueueIds: queueIds,
              Queues: queues,
              SpecsList: specsList,
            }
          });
          this.tableData = data;
          this.pageInfo.total = res.Data.TotalSize;
        }
      }).catch(err => {
        console.log(err);
        this.loading = false;
      });
    },
    selectChange() {
      this.pageInfo.curpage = 1;
      this.getTableData();
    },
    currentChange(val) {
      this.pageInfo.curpage = val;
      this.getTableData();
    },
    deleteRow(row) {
      this.$confirm(this.$t('resourcesManagement.resSceneDeleteConfirm'), this.$t('tips'), {
        confirmButtonText: this.$t('confirm1'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning',
        lockScroll: false,
      }).then(() => {
        updateResScene({
          action: 'delete',
          ID: row.ID,
        }).then(res => {
          res = res.data;
          if (res.Code === 0) {
            this.$message({
              type: 'success',
              message: this.$t('submittedSuccessfully')
            });
            this.getTableData();
          } else {
            this.$message({
              type: 'error',
              message: this.$t('submittedFailed')
            });
          }
        }).catch(err => {
          this.$message({
            type: 'error',
            message: this.$t('submittedFailed')
          });
        });
      }).catch(() => { });
    },
    showDialog(type, data) {
      this.sceneDialogType = type;
      this.sceneDialogData = data ? {
        ID: data.ID,
        SceneName: data.SceneName,
        JobType: data.JobType,
        IsExclusive: data.IsExclusive ? '1' : '2',
        ExclusiveOrg: data.ExclusiveOrg,
        Cluster: data.Cluster,
        QueueIds: data.QueueIds,
        SpecIds: data.SpecsList.map((item) => item.k),
      } : {};
      this.sceneDialogShow = true;
    },
    sceneDialogConfirm() {
      this.sceneDialogShow = false;
      this.getTableData();
    }
  },
  mounted() {
    this.getAiCenterList();
    this.getQueueList();
    this.getTableData();
  },
  beforeDestroy() {
  },
};
</script>

<style scoped lang="less">
.title {
  height: 30px;
  display: flex;
  align-items: center;
  margin-bottom: 5px;

  span {
    font-weight: 700;
    font-size: 16px;
    color: rgb(16, 16, 16);
  }
}

.tools-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;

  .select {
    margin-right: 10px;

    /deep/ .el-input__inner {
      border-radius: 0;
    }
  }
}

.table-container {
  margin-bottom: 16px;

  /deep/ .el-table__header {
    th {
      background: rgb(245, 245, 246);
      font-size: 12px;
      color: rgb(36, 36, 36);
    }
  }

  /deep/ .el-table__body {
    td {
      font-size: 12px;
    }
  }

  .op-btn {
    cursor: pointer;
    font-size: 12px;
    color: rgb(25, 103, 252);
    margin: 0 5px;
  }
}

.center {
  display: flex;
  justify-content: center;
}
</style>
