<template>
  <div class="base-dlg">
    <BaseDialog :visible.sync="dialogShow" :width="`750px`"
      :title="type === 'add' ? $t('resourcesManagement.addResScene') : $t('resourcesManagement.editResScene')"
      @open="open" @opened="opened" @close="close" @closed="closed">
      <div class="dlg-content">
        <div class="form">
          <div class="form-row">
            <div class="title required">
              <span>{{ $t('resourcesManagement.resSceneName') }}</span>
            </div>
            <div class="content">
              <el-input v-model="dataInfo.SceneName" placeholder="" maxlength="255"></el-input>
            </div>
          </div>
          <div class="form-row">
            <div class="title required">
              <span>{{ $t('resourcesManagement.jobType') }}</span>
            </div>
            <div class="content">
              <el-select v-model="dataInfo.JobType" :disabled="type === 'edit'">
                <el-option v-for="item in taskTypeList" :key="item.k" :label="item.v" :value="item.k" />
              </el-select>
            </div>
          </div>
          <div class="form-row">
            <div class="title required">
              <span>{{ $t('resourcesManagement.isExclusive') }}</span>
            </div>
            <div class="content">
              <el-select v-model="dataInfo.IsExclusive" @change="changeIsExclusive">
                <el-option v-for="item in isExclusiveList" :key="item.k" :label="item.v" :value="item.k" />
              </el-select>
            </div>
          </div>
          <div class="form-row" v-if="dataInfo.IsExclusive === '1'">
            <div class="title required">
              <span>{{ $t('resourcesManagement.exclusiveOrg') }}</span>
            </div>
            <div class="content">
              <el-input v-model="dataInfo.ExclusiveOrg" :placeholder="$t('resourcesManagement.exclusiveOrgTips')"
                maxlength="255">
              </el-input>
            </div>
          </div>
          <div class="form-row">
            <div class="title required">
              <span>{{ $t('resourcesManagement.computeCluster') }}</span>
            </div>
            <div class="content">
              <el-select v-model="dataInfo.Cluster" @change="changeCluster" :disabled="type === 'edit'">
                <el-option v-for="item in clusterList" :key="item.k" :label="item.v" :value="item.k" />
              </el-select>
            </div>
          </div>
          <div class="form-row">
            <div class="title">
              <span>{{ $t('resourcesManagement.resQueue') }}</span>
            </div>
            <div class="content">
              <el-select v-model="dataInfo.QueueId" @change="changeQueue" :disabled="type === 'edit'">
                <el-option v-for="item in queueList" :key="item.k" :label="item.v" :value="item.k" />
              </el-select>
            </div>
          </div>
          <div class="form-row">
            <div class="title required">
              <span>{{ $t('resourcesManagement.resourceSpecification') }}</span>
            </div>
            <div class="content">
              <el-select v-model="dataInfo.SpecIds" multiple collapse-tags class="specSel">
                <el-option v-for="item in specsList" :label="item.v" :key="item.k" :value="item.k">
                  <span v-html="item.v"></span>
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="form-row" style="margin-top: 20px">
            <div class="title"></div>
            <div class="content">
              <el-button type="primary" class="btn confirm-btn" @click="confirm">{{ $t('confirm') }}</el-button>
              <el-button class="btn" @click="cancel">{{ $t('cancel') }}</el-button>
            </div>
          </div>
        </div>
      </div>
    </BaseDialog>
  </div>
</template>
<script>
import BaseDialog from '~/components/BaseDialog.vue';
import { getResQueueCode, getResSpecificationListAll, addResScene, updateResScene } from '~/apis/modules/resources';
import { JOB_TYPE, CLUSTERS, ACC_CARD_TYPE, SPECIFICATION_STATUS } from '~/const';
import { getListValueWithKey } from '~/utils';

export default {
  name: "SceneDialog",
  props: {
    visible: { type: Boolean, default: false },
    title: { type: String, default: '' },
    type: { type: String, defalut: 'add' },
    data: { type: Object, default: () => ({}) },
  },
  components: {
    BaseDialog
  },
  data() {
    return {
      dialogShow: false,
      dataInfo: {},
      taskTypeList: [...JOB_TYPE],
      clusterList: [...CLUSTERS],
      accCardTypeList: [...ACC_CARD_TYPE],
      statusList: [...SPECIFICATION_STATUS],
      isExclusiveList: [{ k: '2', v: this.$t('resourcesManagement.commonUse') }, { k: '1', v: this.$t('resourcesManagement.exclusive') }],
      queueList: [],
      specsList: [],
    };
  },
  watch: {
    visible: function (val) {
      this.dialogShow = val;
    },
  },
  methods: {
    resetDataInfo() {
      this.dataInfo = {
        SceneName: '',
        JobType: '',
        IsExclusive: '2',
        ExclusiveOrg: '',
        Cluster: '',
        QueueId: '',
        SpecIds: [],
      }
      this.queueList.splice(0, Infinity);
      this.specsList.splice(0, Infinity);
    },
    getQueueList(next) {
      return getResQueueCode({ cluster: this.dataInfo.Cluster }).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})`,
            });
          }
          list.unshift({
            k: '-1',
            v: this.$t('resourcesManagement.allResQueue'),
          });
          this.queueList.splice(0, Infinity, ...list);
          if (next) {
            if (this.type === 'add') {
              this.dataInfo.QueueId = '-1';
            }
            this.getResSpecificationList();
          }
        }
      }).catch(err => {
        console.log(err);
      });
    },
    getResSpecificationList() {
      const params = {
        cluster: this.dataInfo.Cluster,
        queue: this.dataInfo.QueueId === '-1' ? '' : this.dataInfo.QueueId,
        // status: 2,
        // page: 1,
      };
      return getResSpecificationListAll(params).then(res => {
        res = res.data;
        if (res.Code === 0) {
          const list = res.Data.List;
          const data = list.map((item) => {
            const Queue = item.Queue;
            const Spec = item.Spec;
            const NGPU = `${Queue.ComputeResource}:${Spec.AccCardsNum + '*' + getListValueWithKey(this.accCardTypeList, Queue.AccCardType)}`;
            const statusStr = Spec.Status != '2' ? `<span style="color:rgb(245, 34, 45)">(${getListValueWithKey(this.statusList, Spec.Status.toString())})</span>` : '';
            return {
              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')}${statusStr}`,
            }
          });
          this.specsList.splice(0, Infinity, ...data);
        }
      }).catch(err => {
        console.log(err);
      });
    },
    changeIsExclusive() {
      this.dataInfo.ExclusiveOrg = '';
    },
    changeCluster() {
      this.dataInfo.QueueId = '';
      this.dataInfo.SpecIds = [];
      this.queueList.splice(0, Infinity);
      this.specsList.splice(0, Infinity);
      this.getQueueList(true);
    },
    changeQueue() {
      this.dataInfo.SpecIds = [];
      this.specsList.splice(0, Infinity);
      this.getResSpecificationList();
    },
    open() {
      this.resetDataInfo();
      if (this.type === 'add') {
        //
      } else if (this.type === 'edit') {
        Object.assign(this.dataInfo, { ...this.data, QueueId: this.data.QueueIds.length === 1 ? this.data.QueueIds[0] : '-1' });
        this.queueList.splice(0, Infinity);
        this.specsList.splice(0, Infinity);
        this.getQueueList(true);
      }
      this.$emit("open");
    },
    opened() {
      this.$emit("opened");
    },
    close() {
      this.$emit("close");
    },
    closed() {
      this.$emit("closed");
      this.$emit("update:visible", false);
    },
    confirm() {
      if (!this.dataInfo.SceneName || !this.dataInfo.JobType || !this.dataInfo.SpecIds.length || (this.dataInfo.IsExclusive === '1' && !this.dataInfo.ExclusiveOrg)) {
        this.$message({
          type: 'info',
          message: this.$t('pleaseCompleteTheInformationFirst')
        });
        return;
      }
      const setApi = this.type === 'add' ? addResScene : updateResScene;
      setApi({
        ...this.dataInfo,
        action: this.type === 'edit' ? 'edit' : undefined,
        IsExclusive: this.dataInfo.IsExclusive === '1',
      }).then(res => {
        res = res.data;
        if (res.Code === 0) {
          this.$message({
            type: 'success',
            message: this.$t('submittedSuccessfully')
          });
          this.$emit("confirm");
        } else {
          this.$message({
            type: 'error',
            message: this.$t('submittedFailed')
          });
        }
      }).catch(err => {
        console.log(err);
        this.$message({
          type: 'error',
          message: this.$t('submittedFailed')
        });
      })

    },
    cancel() {
      this.dialogShow = false;
      this.$emit("update:visible", false);
    }
  },
  mounted() {
    this.resetDataInfo();
  },
};
</script>
<style scoped lang="less">
.dlg-content {
  margin: 20px 0 25px 0;
  display: flex;
  justify-content: center;

  .form {
    width: 600px;

    .form-row {
      display: flex;
      min-height: 42px;
      margin-bottom: 4px;

      .title {
        width: 160px;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        margin-right: 20px;
        color: rgb(136, 136, 136);
        font-size: 14px;

        &.required {
          span {
            position: relative;
          }

          span::after {
            position: absolute;
            right: -10px;
            top: -2px;
            vertical-align: top;
            content: '*';
            color: #db2828;
          }
        }
      }

      .content {
        width: 300px;
        display: flex;
        align-items: center;

        /deep/ .el-select {
          width: 100%;
        }
      }

      .specSel {
        /deep/ .el-tag.el-tag--info {
          max-width: 81%;
          display: flex;
          align-items: center;

          .el-select__tags-text {
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .el-tag__close {
            flex-shrink: 0;
            right: -5px;
          }
        }
      }
    }
  }

  .btn {
    color: rgb(2, 0, 4);
    background-color: rgb(194, 199, 204);
    border-color: rgb(194, 199, 204);

    &.confirm-btn {
      color: #fff;
      background-color: rgb(56, 158, 13);
      border-color: rgb(56, 158, 13);
    }
  }
}

.el-select-dropdown__item {
  padding-left: 26px !important;
}

.el-select-dropdown__item.selected::after {
  right: 0;
  left: 6px;
}
</style>
