<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="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="任务数" prop="subtaskNum">-->
<!--        <el-input-->
<!--          v-model="queryParams.subtaskNum"-->
<!--          placeholder="请输入任务数"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="开始时间" prop="startTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.startTime"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择开始时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="结束时间" prop="endTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.endTime"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择结束时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="完成率" prop="progress">-->
<!--        <el-input-->
<!--          v-model="queryParams.progress"-->
<!--          placeholder="请输入完成率"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="准确率" prop="accuracyRate">-->
<!--        <el-input-->
<!--          v-model="queryParams.accuracyRate"-->
<!--          placeholder="请输入准确率"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="召回率" prop="recallRate">-->
<!--        <el-input-->
<!--          v-model="queryParams.recallRate"-->
<!--          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="['biz:task: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="['biz:task: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="['biz:task:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['biz:detail:import']"
        >导入</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['biz:detail:export']"
        >选择任务导出任务详情</el-button>
      </el-col>
      <el-col :span="1.5" >
        <el-button

          type='success'
          plain
          icon="el-icon-video-play"
          size="mini"
          @click="handleRun"
        >验证运行</el-button>

      </el-col>
      <el-col :span="1.5" >
        <el-button

          type='info'
          plain
          icon="el-icon-document"
          size="mini"
          @click="gettraindata"
        >查询训练数据</el-button>

      </el-col>
      <el-col :span="1.5" >
        <el-button

          type='info'
          plain
          icon="el-icon-document"
          size="mini"
          @click="getverificationdata"
        >查询验证数据</el-button>

      </el-col>
<!--      <el-col :span="1.5" >-->
<!--        <el-button-->

<!--          type='danger'-->
<!--          plain-->
<!--          icon="el-icon-video-pause"-->
<!--          size="mini"-->
<!--          @click="handleRun"-->
<!--        >终止</el-button>-->

<!--      </el-col>-->

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" class="custom-selection"/>
      <el-table-column label="任务编号" align="center" prop="id" />
      <el-table-column label="任务名称" align="center" prop="taskName" :show-overflow-tooltip='true'  />
      <el-table-column label="状态" align="center" prop="taskStatus" :show-overflow-tooltip='true' />
      <el-table-column label="任务数" align="center" prop="subtaskNum" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="准确率" align="center" prop="accuracyRate" />
      <el-table-column label="召回率" align="center" prop="recallRate" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip='true' />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['biz:task:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['biz:task: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"
    />
    <!-- 任务详情导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改验证任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form  style="border:1px solid #C0C0C0;padding: 5px;margin: auto" ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务数" prop="subtaskNum">
          <el-input v-model="form.subtaskNum" placeholder="请输入任务数" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完成率" prop="progress">
          <el-input v-model="form.progress" placeholder="请输入完成率" />
        </el-form-item>
        <el-form-item label="准确率" prop="accuracyRate">
          <el-input v-model="form.accuracyRate" placeholder="请输入准确率" />
        </el-form-item>
        <el-form-item label="召回率" prop="recallRate">
          <el-input v-model="form.recallRate" placeholder="请输入召回率" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="训练数据" :visible.sync="traindatavisible" width="800px" append-to-body>

      <el-table v-loading = tloading :data="traindataset" >
        <el-table-column label="使用场景" align="center" prop="useScene" />
        <el-table-column label="查询条件" align="center" prop="searchCondition" />
        <el-table-column label="标准结果1" align="center" prop="result1" />
        <el-table-column label="标准结果2" align="center" prop="result2" />
        <el-table-column label="标准结果3" align="center" prop="result3" />
        <el-table-column label="标准结果4" align="center" prop="result4" />
        <el-table-column label="标准结果5" align="center" prop="result5" />
        <el-table-column label="trained" align="center" >1</el-table-column>
        <el-table-column label="tested" align="center" >0</el-table-column>
      </el-table>

      <pagination
        v-show="ttotal>0"
        :total="ttotal"
        :page.sync="query.pageNum"
        :limit.sync="query.pageSize"
        @pagination="gettraindata"
      />
    </el-dialog>
    <el-dialog title="验证数据" :visible.sync="verificationdatavisible" width="800px" append-to-body>

      <el-table v-loading = vloading :data="verificationtabledata" >
        <el-table-column label="使用场景" align="center" prop="useScene" />
        <el-table-column label="查询条件" align="center" prop="searchCondition" />
        <el-table-column label="标准结果1" align="center" prop="result1" />
        <el-table-column label="标准结果2" align="center" prop="result2" />
        <el-table-column label="标准结果3" align="center" prop="result3" />
        <el-table-column label="标准结果4" align="center" prop="result4" />
        <el-table-column label="标准结果5" align="center" prop="result5" />
        <el-table-column label="计算结果1" align="center" prop="calculate1" />
        <el-table-column label="计算结果2" align="center" prop="calculate2" />
        <el-table-column label="计算结果3" align="center" prop="calculate3" />
        <el-table-column label="计算结果4" align="center" prop="calculate4" />
        <el-table-column label="计算结果5" align="center" prop="calculate5" />

        <el-table-column label="trained" align="center" >0</el-table-column>
        <el-table-column label="tested" align="center" >1</el-table-column>
      </el-table>
      <pagination
        v-show="vtotal>0"
        :total="vtotal"
        :page.sync="vpageNum"
        :limit.sync="vpageSize"
        @pagination="getverificationdata"
      />
    </el-dialog>

    <el-dialog
      :title=progresstitle
      :visible.sync="dialogVisible"
      width="20%"
      style="top:225px"
      >
      <div  align="center">
        <el-progress
          type="circle"
          :percentage="ProgressMap[taskidToIndexMap.get(ids[0])]"
          width="80"
          :status="progressStatus"
        ></el-progress>
      </div>


    </el-dialog>
  </div>




</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask } from "@/api/biz/task";
import { verification,getTraindataset,updateDetails,getUpdatedDetails } from "@/api/biz/detail";
import { getToken } from "@/utils/auth";
import {Loading, Message} from "element-ui";
import service from "../../../utils/request";
import errorCode from "../../../utils/errorCode";
import dayjs from "dayjs";
import {updateDetail} from "../../../api/biz/detail";
export default {
  name: "Task",
  data() {
    return {
      progresstitle:'',
      dialogVisible:false,
      // 遮罩层
      loading: true,
      vloading:true,
      tloading:true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      ttotal:0,
      vtotal:0,
      // 验证任务表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        taskStatus: null,
        subtaskNum: null,
        startTime: null,
        endTime: null,
        progress: null,
        accuracyRate: null,
        recallRate: null,
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/biz/detail/importData"
      },
      traindatavisible:false,
      verificationdatavisible:false,
      traindataset:[],
      verificationdataset:[],
      ProgressMap: [],
      taskidToIndexMap: new Map(),
      verificationtabledata:[],
      progressStatus:'',
      query :{
        pageNum: 1,
        pageSize: 10,
      },
      vpageNum:1,
      vpageSize:10,
    };

  },
  created() {
    this.getList();
  },
  // computed: {
  //   progressStatus() {
  //     return this.Progress === 100 ? 'success' : '';
  //   },
  // },
  methods: {


    gettraindata(){
      getTraindataset(this.query).then(res=>{
        this.traindatavisible = true
        // console.log(res)

          this.tloading = false
          this.ttotal = res.total;
          this.traindataset = res.rows


      })

    },
    getverificationdata(){


      if(this.ids.length===0){
        this.$modal.msg("请先选择查看的任务！")
        return
      }
      getUpdatedDetails(this.ids, this.vpageNum, this.vpageSize ).then(res=>{
        this.verificationdatavisible = true
        console.log(res)
        this.verificationtabledata = res.list
        this.vloading = false
        this.vtotal = res.total;

      })


    },

    handleRun() {
      if(this.ids.length>1) {
        this.$modal.msg("不能选择多个任务！")
        return ;
      }
      if(this.ids.length===0){
        this.$modal.msg("请先选中验证任务！")
        return ;
      }
      this.progresstitle = "验证任务"+this.ids[0]+"运行"
      this.progressStatus = ''
      this.dialogVisible = true
      let taskids = this.ids;
      const dayjs = require('dayjs');

      for (let taskid of taskids) {
        let index = this.taskidToIndexMap.get(taskid)
        getTask(taskid).then(response => {

          let task = response.data;
          task.startTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
          let code = 0;
          this.ProgressMap[index] = 0;
          verification(taskid).then(res => {
            let result = JSON.parse(res.data).data
            code = res.code;
            if (res.code === 200) {
              this.verificationdataset = result.dataSet;

              //更新任务详情表
              updateDetails(this.verificationdataset).then(res1=>{
                console.log(res1.msg)
              })

              // console.log(this.verificationdataset)

              task.accuracyRate = result.accuracyRate+'%'
              task.recallRate = result.recallRate+'%'
              task.endTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
              task.taskStatus = '运行成功';
              task.progress = 100;
              //这里需要更新数据库task
              updateTask(task).then(res2=>{
                console.log(res2.msg)
              })
            }
          });

          // 使用闭包确保每个循环迭代中创建一个新的 taskid
          const createInterval = (taskId) => {
            // 模拟进度变化，每0.1秒更新一次，共更新100次
            const intervalId = setInterval(() => {
              let idx = this.taskidToIndexMap.get(taskId)
              // this.ProgressMap[index] = this.ProgressMap[index] + 1
              this.$set(this.ProgressMap, idx, this.ProgressMap[idx] + 1);
              if(code!==200&&code!==0){
                clearInterval(intervalId);
                this.$message.error('任务' + taskId + '运行失败!');
              }
              // 如果进度达到100%，清除定时器并调用后端算法
              if (this.ProgressMap[idx] >= 100) {
                this.$set(this.ProgressMap, idx, 0);
                clearInterval(intervalId);
                this.progressStatus = 'success'
                this.dialogVisible = false

                if(code===200){
                    this.$message.success('任务' + taskId + '运行成功!');
                    this.getList();
                }
              }
            }, 100);
          };

          // 调用闭包函数，传入当前的 taskid

          createInterval(taskid);
        });
      }
    },

    /** 查询验证任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        let task;
        let idx = 0;
        for(task of this.taskList){
          this.taskidToIndexMap.set(task.id, idx)
          // this.ProgressMap.push(task.progress)
          this.ProgressMap.push(0)
          idx++;
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskName: null,
        taskStatus: null,
        subtaskNum: null,
        startTime: null,
        endTime: null,
        progress: null,
        accuracyRate: null,
        recallRate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    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.reset();
      this.open = true;
      this.title = "添加验证任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改验证任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除验证任务编号为"' + ids + '"的数据项？').then(function() {
        return delTask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});

    },
    /** 导出按钮操作 */
    handleExport() {

      if(this.ids.length===0) {
        this.importTemplate()
      }else {
        // this.download('biz/detail/export', this.ids, `taskdetail_${new Date().getTime()}.xlsx`)
        let downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })

        let taskids = this.ids;
        return service.post('biz/detail/export', taskids, {
          headers: { 'Content-Type': 'application/json' },
          responseType: 'blob',

        }).then(async (data) => {
          // Debug: 输出实际的响应 Content-Type
          // console.log(data)
          // console.log("Response Content-Type:", data.type);

          const isBlob = (data.type !== 'application/json');
          if (isBlob) {
            const blob = new Blob([data])
            saveAs(blob, `taskdetail_${new Date().getTime()}.xlsx`)
          } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
            Message.error(errMsg);
          }
          downloadLoadingInstance.close();
        }).catch((error) => {
          console.error(error)
          Message.error('下载文件出现错误，请联系管理员！')
          downloadLoadingInstance.close();
        })
      }

    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "任务详情导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('biz/detail/importTemplate', {
      }, `taskdetail_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
     // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
// 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }

  }
};
</script>

<style>

 .el-checkbox__inner {
  border-color: #8492a6 !important;
}
 .app-container {
   min-height: 100vh;
   background: radial-gradient(circle at 10% 20%, #3A71A8 0%, rgb(239, 249, 249) 90%);
 }

</style>
