package com.aucma.report.controller;

import com.aucma.common.core.controller.BaseController;
import com.aucma.common.core.domain.AjaxResult;
import com.aucma.common.core.page.PageDomain;
import com.aucma.common.core.page.TableDataInfo;
import com.aucma.common.core.page.TableSupport;
import com.aucma.report.domain.DeviceParamReportQuery;
import com.aucma.report.service.IDeviceParamAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

/**
 * 设备参数分析Controller
 *
 * @author Codex
 */
@RestController
@RequestMapping("/report/deviceParamAnalysis")
public class DeviceParamAnalysisController extends BaseController {

    @Autowired
    private IDeviceParamAnalysisService deviceParamAnalysisService;

    /**
     * 查询参数选项
     */
    @PreAuthorize("@ss.hasPermi('baseDeviceParamVal:trace:list')")
    @GetMapping("/paramOptions")
    public AjaxResult paramOptions(DeviceParamReportQuery query) {
        return success(deviceParamAnalysisService.selectParamOptions(query));
    }

    /**
     * 查询参数异常报表
     */
    @PreAuthorize("@ss.hasPermi('baseDeviceParamVal:trace:list')")
    @GetMapping("/anomaly/list")
    public TableDataInfo anomalyList(DeviceParamReportQuery query) {
        return buildPageData(deviceParamAnalysisService.selectParamAnomalyList(query));
    }

    /**
     * 查询参数趋势/SPC报表
     */
    @PreAuthorize("@ss.hasPermi('baseDeviceParamVal:trace:list')")
    @GetMapping("/spc")
    public AjaxResult spc(DeviceParamReportQuery query) {
        return success(deviceParamAnalysisService.getSpcReport(query));
    }

    /**
     * 查询模具/物料/产品切换追溯报表
     */
    @PreAuthorize("@ss.hasPermi('baseDeviceParamVal:trace:list')")
    @GetMapping("/switch/list")
    public TableDataInfo switchList(DeviceParamReportQuery query) {
        return buildPageData(deviceParamAnalysisService.selectSwitchTraceList(query));
    }

    private TableDataInfo buildPageData(List<?> fullList) {
        List<?> safeList = fullList == null ? Collections.emptyList() : fullList;
        PageDomain pageDomain = TableSupport.buildPageRequest();
        int pageNum = Math.max(pageDomain.getPageNum(), 1);
        int pageSize = Math.max(pageDomain.getPageSize(), 1);
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, safeList.size());
        List<?> pageRows = fromIndex >= safeList.size() ? Collections.emptyList() : safeList.subList(fromIndex, toIndex);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setMsg("查询成功");
        rspData.setRows(pageRows);
        rspData.setTotal(safeList.size());
        return rspData;
    }
}
