package cn.cslg.pas.controller;

import cn.cslg.pas.common.core.annotation.Permission;
import cn.cslg.pas.common.core.base.Constants;
import cn.cslg.pas.common.utils.JsonUtils;
import cn.cslg.pas.common.utils.Response;
import cn.cslg.pas.common.utils.ResponseEnum;
import cn.cslg.pas.common.utils.SecurityUtils.LoginUtils;
import cn.cslg.pas.common.utils.StringUtils;
import cn.cslg.pas.common.utils.auth.checkAuth;
import cn.cslg.pas.domain.Report;
import cn.cslg.pas.common.model.vo.ReportVO;
import cn.cslg.pas.service.ReportService;
import cn.cslg.pas.common.utils.CacheUtils;
import cn.dev33.satoken.stp.StpUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Tag(name = "报告")
@RestController
@RequestMapping(Constants.API_VERSION_V2 + "/report")
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class ReportController {
    private final ReportService reportService;
    private final CacheUtils cacheUtils;
    private final LoginUtils loginUtils;

    @GetMapping("list")
    @Operation(summary = "报告列表")
    public String getList(ReportVO params) {
        return Response.success(reportService.getReportList(params));
    }

    @GetMapping("{id}")
    @Operation(summary = "根据ID获取报告")
    public String getById(@PathVariable Integer id) {
        return Response.success(reportService.getReportById(id));
    }

    @PostMapping("delete")
    @Operation(summary = "删除报告")
    public String deleteById(@RequestBody List<Integer> ids) {
        return Response.success(reportService.deleteById(ids));
    }


    @checkAuth(FunId = "/workspace/folder/analyticSystem/generateReport")
    @Permission(roles = {2})
    @PostMapping("add")
    @Operation(summary = "创建报告")
    public String add(@RequestBody Report report) {
        String id = cacheUtils.getSelectPatentIds(report.getPatentKey());
        if (StringUtils.isEmpty(id)) {
            return Response.error(ResponseEnum.QUERY_CACHE_ERROR);
        }
        report.setStatus(0);
        report.setCreateBy(loginUtils.getId());
        report.setCfg(JsonUtils.objectToJson(report.getPatentList()));
        report.setCreateTime(new Date());
        report.insert();
        report.setPatentIds(StringUtils.changeStringToInteger(id, ","));
        reportService.add(report);
        return Response.success(report.getId());
    }

    @GetMapping("patent")
    @Operation(summary = "获取待分析的专利")
    public String getPatentList(String patentKey, Integer projectId) {
        String id = cacheUtils.getSelectPatentIds(patentKey);
        if (StringUtils.isEmpty(id)) {
            return Response.error(ResponseEnum.QUERY_CACHE_ERROR);
        }
        return Response.success(reportService.getPatentList(StringUtils.changeStringToInteger(id, ","), projectId));
    }
}
