<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="镜像名称" prop="mirrorName">
        <el-input
          v-model="queryParams.mirrorName"
          placeholder="请输入镜像名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mirror:manager:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mirror:manager:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mirror:manager:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="managerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column type="index" label="序号" align="center" :index="indexMethod" width="50"/>
      <el-table-column label="镜像名称" align="center" prop="mirrorName"/>
      <el-table-column label="镜像版本" align="center" prop="mirrorVersion"/>
      <el-table-column label="所属模型" align="center" prop="datasetId"/>
      <el-table-column label="运行环境" align="center" prop="runEnvironment">
        <template slot-scope="scope">
          <span>{{
              (runEnvironmentList.find(item => item.value == scope.row.runEnvironment) || {}).label || 'Unknown'
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="架构类型" align="center" prop="modelFrame">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ai_frame_type" :value="scope.row.modelFrame"/>
        </template>
      </el-table-column>
      <el-table-column label="语言" align="center" prop="language">
        <template slot-scope="scope">
          <span>{{ (languageList.find(item => item.value == scope.row.language) || {}).label || 'Unknown' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="镜像文件" align="center" prop="mirrorPath">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDownload(scope.row.mirrorPath,scope.row.modelFileName)"
            v-hasPermi="['model:manager:edit']"
          >下载
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="接口文档" align="center" prop="modelFrame">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDownload(scope.row.documentPath,scope.row.manualFileName)"
            v-hasPermi="['model:manager:edit']"
          >下载
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleSee(scope.row.documentPath)"
            v-hasPermi="['model:manager:remove']"
          >查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mirror:manager:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mirror:manager:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改镜像管理对话框 -->
    <custom-dialog :title="title" :get-list="getList" :open="open" :mirror-id="mirrorId" @dialog-cancel="handleCancel"/>
  </div>
</template>

<script>
import { listManager, delManager } from '@/api/dataCenter/mirror'
import customDialog from '../mirror/child/customDialog.vue'
import { Base64 } from 'js-base64'
import { encryptCBC } from '../../../utils/aescbc'

export default {
  name: 'Mirror',
  dicts: ['ai_annotate_type', 'ai_frame_type'],
  components: { customDialog },
  data() {
    return {
      runEnvironmentList: [{
        value: '0',
        label: 'CPU'
      },
        {
          value: '1',
          label: 'GPU'
        }],
      languageList: [
        { 'value': '0', 'label': 'Java' },
        { 'value': '1', 'label': 'Python' },
        { 'value': '2', 'label': 'JavaScript (Node.js)' },
        { 'value': '3', 'label': 'PHP' },
        { 'value': '4', 'label': 'C# (.NET)' },
        { 'value': '5', 'label': 'Ruby' },
        { 'value': '6', 'label': 'Go (Golang)' },
        { 'value': '7', 'label': 'C/C++' },
        { 'value': '8', 'label': 'Kotlin' },
        { 'value': '9', 'label': 'Rust' },
        { 'value': '10', 'label': 'Scala' },
        { 'value': '11', 'label': 'Perl' },
        { 'value': '12', 'label': 'Swift' },
        { 'value': '13', 'label': 'Elixir' }
      ],
      mirrorId: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 镜像管理表格数据
      managerList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mirrorName: null
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
    },
    /** 查询镜像管理列表 */
    getList() {
      this.loading = true
      listManager(this.queryParams).then(response => {
        this.managerList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.title = '添加'
      this.mirrorId = null
      this.open = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.mirrorId = row.id || this.ids[0]
      this.title = '修改'
      this.open = true

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除数据项？').then(function() {
        return delManager(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    handleCancel() {
      this.open = false
    },
    handleDownload(url, fileName) {
      // 创建一个 XMLHttpRequest 对象
      const xhr = new XMLHttpRequest()
      // 设置响应类型为 blob，这样能处理二进制数据等各种类型的文件内容
      xhr.responseType = 'blob'
      // 监听请求的加载完成事件
      xhr.onload = function() {
        if (this.status === 200) {
          // 获取响应内容（以 blob 形式）
          const blob = this.response
          // 创建一个用于下载的链接元素
          const downloadLink = document.createElement('a')
          // 为链接元素生成一个临时的 URL，指向 blob 数据
          downloadLink.href = URL.createObjectURL(blob)
          // 设置下载链接的下载属性（指定文件名）
          downloadLink.download = fileName
          // 模拟点击链接来触发下载
          downloadLink.click()
          // 释放创建的临时 URL 资源
          URL.revokeObjectURL(downloadLink.href)
        }
      }
      // 监听请求的错误事件
      xhr.onerror = function() {
        console.error('下载请求出现错误')
      }
      // 打开请求，使用 GET 方法去获取资源
      xhr.open('GET', `${JSON.parse(localStorage.getItem('minIoUrl')).minioUrl}${url}`, true)
      // 发送请求
      xhr.send()
    },
    handleSee(url) {
      let b64Encoded = Base64.encode(`${JSON.parse(localStorage.getItem('minIoUrl')).minioUrl}${url}`)
      window.open(`http://192.168.0.14:8012/onlinePreview?url=${b64Encoded}&token=${this.generateToken()}`, '_blank')
    },
    generateToken() {
      // 获取当前时间戳（以秒为单位）
      const currentTimeStamp = Math.floor(Date.now())
      // 将时间戳转换为字符串
      const timeStampString = currentTimeStamp.toString()
      return encryptCBC(timeStampString)
    }
  }
}
</script>
