package org.jk.rag.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.jk.common.core.domain.R;
import org.jk.common.excel.utils.ExcelUtil;
import org.jk.common.idempotent.annotation.RepeatSubmit;
import org.jk.common.log.annotation.Log;
import org.jk.common.log.enums.BusinessType;
import org.jk.common.mybatis.core.page.PageQuery;
import org.jk.common.mybatis.core.page.TableDataInfo;
import org.jk.common.satoken.utils.LoginHelper;
import org.jk.common.web.core.BaseController;
import org.jk.rag.domain.EvaluationTaskHistory;
import org.jk.rag.domain.bo.EvaluationTaskHistoryBo;
import org.jk.rag.domain.entity.JkDocumentPythonParams;
import org.jk.rag.domain.vo.EvaluationTaskVo;
import org.jk.rag.mapper.JkEvaluationTaskMapper;
import org.jk.rag.service.IEvaluationTaskHistoryService;
import org.jk.rag.service.IJkDatasetService;
import org.jk.rag.service.IJkEvaluationTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 【评测任务】Controller
 *
 * @author takai
 * @date 2025-05-28
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/deepseek/evaluation")
public class JkEvaluationTaskController extends BaseController {
    private final IJkEvaluationTaskService evaluationTaskService;

    private final IEvaluationTaskHistoryService evaluationTaskHistoryService;

    private final JkEvaluationTaskMapper jkEvaluationTaskMapper;
    /**
     * 查询评测任务列表
     */

    @GetMapping("/pageList")
    public TableDataInfo<EvaluationTaskVo> pageList(String name, PageQuery pageQuery) {
        Page<EvaluationTaskVo> list = evaluationTaskService.selectPageList(name, pageQuery);
        return TableDataInfo.build(list);
    }

    /**
     * 创建评测任务
     */
    @SaCheckPermission("evaluationTool:evaluationTask:add")
    @PostMapping("/create")
    @RepeatSubmit
    public R<String> create(@RequestBody EvaluationTaskVo evaluationTaskVo) {
        boolean exitFlg = evaluationTaskService.checkName(evaluationTaskVo.getTaskName());
        if (!exitFlg) {
            return R.fail("评测任务名称已存在");
        }
        if(evaluationTaskVo.getFlg()) {
            evaluationTaskVo.setStatus("1");
            evaluationTaskVo.setCreateBy(LoginHelper.getUserId());
            evaluationTaskVo.setTenantId(LoginHelper.getTenantId());
            evaluationTaskVo.setStartTime(new Date());
            Long taskId = evaluationTaskService.insertEvaluationTask(evaluationTaskVo);
            evaluationTaskVo.setTaskId(taskId);
            // 异步执行处理任务
            CompletableFuture.runAsync(() -> {
                try {
                    evaluationTaskService.beginTask(evaluationTaskVo);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        } else {
            evaluationTaskVo.setStatus("0");
            evaluationTaskService.insertEvaluationTask(evaluationTaskVo);
        }

        return R.ok("创建成功");
    }

    @SaCheckPermission("evaluationTool:evaluationTask:start")
    @PostMapping("/taskBegin")
    @RepeatSubmit
    public R<String> taskBegin(@RequestBody EvaluationTaskVo evaluationTaskVo) {
        evaluationTaskVo.setStatus("1");
        evaluationTaskVo.setCreateBy(LoginHelper.getUserId());
        evaluationTaskVo.setTenantId(LoginHelper.getTenantId());
        evaluationTaskVo.setStartTime(new Date());
        evaluationTaskService.edit(evaluationTaskVo);
        // 异步执行处理任务
        CompletableFuture.runAsync(() -> {
            try {
                evaluationTaskService.beginTask(evaluationTaskVo);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return R.ok("操作成功");
    }

    /**
     * python文档解析回调接口
     *
     * @param evaluationTaskVo
     * @return
     * @throws Exception
     */
    @PutMapping("/editEvaluationTaskByPython") //@RequestPart DocumentParams documentParams,
    @RepeatSubmit
    public R<Void> editEvaluationTaskByPython(@RequestBody EvaluationTaskVo evaluationTaskVo) {
        evaluationTaskVo.setEndTime(new Date());
        evaluationTaskService.edit(evaluationTaskVo);
        EvaluationTaskVo queryTask = jkEvaluationTaskMapper.selectVoById(evaluationTaskVo.getTaskId());
        EvaluationTaskHistoryBo evaluationTaskHistory = new EvaluationTaskHistoryBo();
        BeanUtils.copyProperties(evaluationTaskVo,evaluationTaskHistory);
        evaluationTaskHistory.setTaskName(queryTask.getTaskName());
        evaluationTaskHistory.setStartTime(queryTask.getStartTime());
        evaluationTaskHistory.setTaskDescription(queryTask.getTaskDescription());
        evaluationTaskHistory.setEvaluationType(queryTask.getEvaluationType());
        evaluationTaskHistory.setReviewRag(queryTask.getReviewRag());
        evaluationTaskHistory.setEmbeddingId(queryTask.getEmbeddingId());
        evaluationTaskHistory.setCreateTime(new Date());
        evaluationTaskHistory.setModel(queryTask.getModel());
        evaluationTaskHistory.setTenantId(queryTask.getTenantId());
        evaluationTaskHistory.setEvaluationData(queryTask.getEvaluationData());
        evaluationTaskHistoryService.insertByBo(evaluationTaskHistory);
        return R.ok();
    }

    @SaCheckPermission("evaluationTool:evaluationTask:del")

    @DeleteMapping("/delete/{taskId}")
    @RepeatSubmit
    public R<String> deleteById(@PathVariable Long taskId) {
        evaluationTaskService.deleteById(taskId);
        return R.ok("删除成功");
    }
}
