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.model.vo.AnalysisItemCountVO;
import cn.cslg.pas.common.utils.CacheUtils;
import cn.cslg.pas.common.utils.Response;
import cn.cslg.pas.common.utils.ResponseEnum;
import cn.cslg.pas.common.utils.StringUtils;
import cn.cslg.pas.service.DataAnalysisService;
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.*;

/**
 * <p>
 * 数据分析 前端控制器
 * </p>
 *
 * @author 王岩
 * @since 2021-12-23
 */
@Tag(name = "分析")
@RestController
@RequestMapping(Constants.API_VERSION_V2 + "/data/analysis")
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class DataAnalysisController {

    private final CacheUtils cacheUtils;
    private final DataAnalysisService dataAnalysisService;

    @GetMapping("patentNum")
    @Operation(summary = "说选专利数量")
    public String getPatentNum(String patentKey) {
        Integer count = cacheUtils.getSelectPatentNum(patentKey);
        if (count == 0) {
            return Response.error("专利临时列表已失效");
        }
        return Response.success(count);
    }

    @Permission(roles = {1, 2, 4})
    @PostMapping("count")
    @Operation(summary = "统计结果")
    public String getCount(@RequestBody AnalysisItemCountVO countVO) {
        String id = cacheUtils.getSelectPatentIds(countVO.getPatentKey());
        if (StringUtils.isEmpty(id)) {
            return Response.error(ResponseEnum.QUERY_CACHE_ERROR);
        }
        if (countVO.getType().equals(21)) {
            return Response.success(dataAnalysisService.getMapCount(countVO));
        }
        if (countVO.getSchema().getY().getField() != 0) {
            return Response.success(dataAnalysisService.getMatrix(countVO, id));
        } else {
            return Response.success(dataAnalysisService.getCount2(
                    countVO.getSource().getX(),
                    countVO.getSchema().getX().getType(),
                    countVO.getPatentKey(),
                    countVO.getSchema().getX().getField(),
                    countVO.getSchema().getX().getExpand(),
                    countVO.getSchema().getX().getMerge(),
                    countVO.getSchema().getX().getPtype(),
                    countVO.getProjectId(),
                    id,
                    0
            ));
        }
    }
}
