package com.ygtx.gxt.controller;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.util.StringUtil;
import com.ygtx.common.constant.HttpStatus;
import com.ygtx.common.core.domain.entity.SysDept;
import com.ygtx.common.core.page.PageDomain;
import com.ygtx.common.core.page.TableSupport;
import com.ygtx.gxt.domain.*;
import com.ygtx.gxt.domain.GxtUserScoreSubmissionDTO;
import com.ygtx.gxt.service.*;
import com.ygtx.system.service.ISysConfigService;
import com.ygtx.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ygtx.common.annotation.Log;
import com.ygtx.common.core.controller.BaseController;
import com.ygtx.common.core.domain.AjaxResult;
import com.ygtx.common.enums.BusinessType;
import com.ygtx.common.utils.poi.ExcelUtil;
import com.ygtx.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;

/**
 * 用户月度评分统计表Controller
 * 
 * @author ruoyi
 * @date 2025-11-03
 */
@RestController
@RequestMapping("/gxt/userscore")
@Api(tags = "用户月度评分统计")
public class GxtUserScoreController extends BaseController
{
    @Autowired
    private IGxtUserScoreService gxtUserScoreService;

    @Autowired
    private IGxtMonthScoreService gxtMonthScoreService;

    @Autowired
    private IGxtUserFanInspectionScoreService userFanInspectionScoreService;

    @Autowired
    private IGxtUserRepairProjectScoreService userRepairProjectScoreService;

    @Autowired
    private IGxtUserRuntimeScoreService userRuntimeScoreService;

    @Autowired
    private IGxtCoefficientScoreService coefficientScoreService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IGxtWorkOrderService gxtWorkOrderService;

    /**
     * 查询用户月度评分统计表列表
     */
    @PreAuthorize("@ss.hasPermi('gxt:userscorereview:list')")
    @ApiOperation("查询用户月度评分统计表列表")
    @GetMapping("/list")
    public TableDataInfo list(GxtUserScore gxtUserScore)
    {
        startPage();
        List<GxtUserScore> list = gxtUserScoreService.selectGxtUserScoreList(gxtUserScore);
        return getDataTable(list);
    }

    /**
     * 人员评分页面数据获取
     * @param rtType
     * @param monthPeriod
     * @return
     */
    @ApiOperation("人员评分页面数据获取")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "rtType", value = "类型", required = true, dataType = "Integer", paramType = "query", dataTypeClass = Integer.class),
        @ApiImplicitParam(name = "monthPeriod", value = "月份周期", required = true, dataType = "String", paramType = "query", dataTypeClass = String.class)
    })
    @GetMapping("/getUserScoreInfo")
    public AjaxResult getUserScoreInfo(@RequestParam Integer rtType, @RequestParam String monthPeriod) {
        if (rtType==null) {
            rtType = 0;
        }
        Long userId = getUserId();
        Long deptId = getDeptId();
        if (rtType==1) {
            GxtUserScore userScore = new GxtUserScore();
            userScore.setMonthPeriod(monthPeriod);
            userScore.setDeptId(deptId);
            List<GxtUserScore> search = gxtUserScoreService.selectGxtUserScoreList(userScore);
            if (search.isEmpty()) {
                // 当月没有评分，需要创建
                rtType = 2;
            }
        }
        String permission = configService.selectConfigByKey("gxt.user.scorePage");
        List<GxtUserScore> userScoreList = gxtUserScoreService.selectGxtUserScoreListByCondition(rtType, monthPeriod, userId, deptId, permission);
        List<GxtUserFanInspectionScore> userFanInspectionScoreList = userFanInspectionScoreService.selectFanInspectionScoreByCondition(rtType,monthPeriod,userId,deptId, permission);
        List<GxtUserRepairProjectScore> userRepairProjectScoreList = userRepairProjectScoreService.selectUserRepairProjectScoreByCondition(rtType,monthPeriod,userId,deptId,permission);
        List<GxtUserRuntimeScore> userRuntimeScoreList = userRuntimeScoreService.selectGxtUserRuntimeScoreListByRtTypeAndMonth(rtType,monthPeriod,userId,deptId,permission);
        GxtCoefficientScore coefficientScore = new GxtCoefficientScore();
        coefficientScore.setMonthPeriod(monthPeriod);
        List<GxtCoefficientScore> coefficientScoreList = coefficientScoreService.selectGxtCoefficientScoreList(coefficientScore);
        AjaxResult ajax = AjaxResult.success();
        if (StringUtil.isNotEmpty(permission)) {
            ajax.put("userScoreList", userScoreList);
            ajax.put("userFanInspectionScoreList", userFanInspectionScoreList);
            ajax.put("userRepairProjectScoreList", userRepairProjectScoreList);
            ajax.put("userRuntimeScoreList", userRuntimeScoreList);
        }
        ajax.put("coefficientScoreList",coefficientScoreList);
        return ajax;
    }

    /**
     * 月度工分汇总页面数据获取
     * @param rtType
     * @param monthPeriod
     * @return
     */
    @ApiOperation("月度工分汇总页面数据获取")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "rtType", value = "类型", required = true, dataType = "Integer", paramType = "query", dataTypeClass = Integer.class),
        @ApiImplicitParam(name = "monthPeriod", value = "月份周期", required = true, dataType = "String", paramType = "query", dataTypeClass = String.class),
        @ApiImplicitParam(name = "deptId", value = "部门ID", required = true, dataType = "Long", paramType = "query", dataTypeClass = Long.class)
    })
    @GetMapping("/getScoreSummary")
    public AjaxResult getScoreSummary(@RequestParam Integer rtType, @RequestParam String monthPeriod, @RequestParam Long deptId) {
        if (rtType==null) {
            rtType = 0;
        }
        String permission = configService.selectConfigByKey("gxt.user.scorePage");
        GxtMonthScore monthScore = gxtMonthScoreService.getGxtMonthScoreByParams(rtType,monthPeriod,deptId);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("monthScore", monthScore);
        return ajax;
    }

    @GetMapping("/getWorkOrderByMonth")
    public TableDataInfo getWorkOrderByMonth(GxtWorkOrder workOrder) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        List<GxtWorkOrder> list = gxtMonthScoreService.getWorkOrderByMonth(workOrder.getModel(),workOrder.getInspectionType(),workOrder.getPcsStationPid(),workOrder.getMonthPeriod());
        List<GxtWorkOrder> result = new ArrayList<>();
        int total = list.size();
        if (pageNum!=null&&pageSize!=null) {
            if (pageNum!=null && pageSize!=null) {
                int from = (pageNum-1) * pageSize;
                int to = pageNum * pageSize;
                if (to>=total) {
                    result.addAll(list.subList(from,total));
                }else {
                    result.addAll(list.subList(from, to));
                }
            }
        }
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(HttpStatus.SUCCESS);
        dataInfo.setMsg("查询成功");
        dataInfo.setTotal(total);
        dataInfo.setRows(result);
        return dataInfo;
    }

    @GetMapping("/getRepairOrderByMonth")
    public TableDataInfo getRepairOrderByMonth(GxtRepairOrder repairOrder) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        List<GxtRepairOrder> list = gxtMonthScoreService.getRepairOrderByMonth(repairOrder.getMaintenanceType(),repairOrder.getPcsStationPid(),repairOrder.getMonthPeriod());
        List<GxtRepairOrder> result = new ArrayList<>();
        int total = list.size();
        if (pageNum!=null&&pageSize!=null) {
            if (pageNum!=null && pageSize!=null) {
                int from = (pageNum-1) * pageSize;
                int to = pageNum * pageSize;
                if (to>=total) {
                    result.addAll(list.subList(from,total));
                }else {
                    result.addAll(list.subList(from, to));
                }
            }
        }
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(HttpStatus.SUCCESS);
        dataInfo.setMsg("查询成功");
        dataInfo.setTotal(total);
        dataInfo.setRows(result);
        return dataInfo;
    }

    @ApiOperation("根据ID获取月度工分汇总")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "rtType", value = "类型", required = true, dataType = "Integer", paramType = "query", dataTypeClass = Integer.class),
        @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long", paramType = "query", dataTypeClass = Long.class)
    })
    @GetMapping("/getScoreSummaryById")
    public AjaxResult getScoreSummaryById(@RequestParam Integer rtType, @RequestParam Long id) {
        if (rtType==null) {
            rtType = 0;
        }
        String permission = configService.selectConfigByKey("gxt.user.scorePage");
        GxtMonthScore monthScore = gxtMonthScoreService.getGxtMonthScoreByParams(rtType,id);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("monthScore", monthScore);
        return ajax;
    }

    /**
     * 月度工分汇总列表数据获取
     * @return
     */
    @ApiOperation("月度工分汇总列表数据获取")
    @GetMapping("/getMonthScoreList")
    public TableDataInfo getMonthScoreList(SysDept sysDept) {
        startPage();
        List<SysDept> monthScoreList = gxtWorkOrderService.getSummaryList(sysDept);
        return getDataTable(monthScoreList);
    }

    /**
     * 统一提交人员评分页面的所有数据
     */
    @ApiOperation("统一提交人员评分页面的所有数据")
    @PostMapping("/submitMonthScore")
    public AjaxResult submitMonthScore(@RequestBody GxtMonthScore monthScore)
    {
        try {
            if (monthScore==null || monthScore.getStatus()==null) {
                return AjaxResult.error("提交失败: 表单为空");
            }
            GxtMonthScore monthScoreNew = gxtMonthScoreService.getGxtMonthScoreByParams(1,monthScore.getMonthPeriod(), monthScore.getDeptId());
            if (monthScoreNew!=null && !monthScoreNew.getStatus().equals(monthScore.getPreviousStatus())) {
                return AjaxResult.error("提交失败: 表单已被更新，请重新查看！");
            }
            gxtMonthScoreService.submitGxtMonthScore(monthScore);
        } catch (Exception e) {
            return AjaxResult.error("提交失败: " + e.getMessage());
        }
        return AjaxResult.success("提交成功");
    }

    @ApiOperation("获取汇总月份列表")
    @ApiImplicitParam(name = "deptId", value = "部门ID", required = true, dataType = "Long", paramType = "query", dataTypeClass = Long.class)
    @GetMapping("/getSummaryMonths")
    public AjaxResult getSummaryMonths(@RequestParam Long deptId) {
        if (deptId==0L) {
            deptId = getDeptId();
        }
        List<Map<String, String>> dictList = new ArrayList<>();
        LocalDate now = LocalDate.now();
        LocalDate lastMonth = now.minusMonths(1);
        String lastMonthValue = lastMonth.format(DateTimeFormatter.ofPattern("yyyy-MM"));
        dictList.add(new HashMap<String, String>() {{
            put("value", lastMonthValue);
            put("label", lastMonth.format(DateTimeFormatter.ofPattern("yyyy年MM月")));
        }});
        GxtMonthScore monthScore = new GxtMonthScore();
        monthScore.setDeptId(deptId);
        List<GxtMonthScore> monthScoreList = gxtMonthScoreService.selectGxtMonthScoreList(monthScore);
        if (!monthScoreList.isEmpty()) {
            Collections.sort(monthScoreList, new Comparator<GxtMonthScore>() {
                @Override
                public int compare(GxtMonthScore o1, GxtMonthScore o2) {
                    return o2.getMonthPeriod().compareTo(o1.getMonthPeriod());
                }
            });
            dictList.clear();
            for (GxtMonthScore monthScore1:monthScoreList) {
                String monthValue = monthScore1.getMonthPeriod();
                String[] months = monthValue.split("-");
                String monthLabel = months[0] + "年" + months[1] + "月";
                dictList.add(new HashMap<String, String>() {{
                    put("value", monthValue);
                    put("label", monthLabel);
                }});
            }
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("dictList", dictList);
        return ajax;
    }

    /**
     * 导出用户月度评分统计表列表
     */
    @Log(title = "用户月度评分统计表", businessType = BusinessType.EXPORT)
    @ApiOperation("导出用户月度评分统计表列表")
    @PostMapping("/export")
    public void export(HttpServletResponse response, GxtUserScore gxtUserScore)
    {
        List<GxtUserScore> list = gxtUserScoreService.selectGxtUserScoreList(gxtUserScore);
        ExcelUtil<GxtUserScore> util = new ExcelUtil<GxtUserScore>(GxtUserScore.class);
        util.exportExcel(response, list, "用户月度评分统计表数据");
    }

    /**
     * 获取用户月度评分统计表详细信息
     */
    @ApiOperation("获取用户月度评分统计表详细信息")
    @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(gxtUserScoreService.selectGxtUserScoreById(id));
    }

    /**
     * 新增用户月度评分统计表
     */
    @Log(title = "用户月度评分统计表", businessType = BusinessType.INSERT)
    @ApiOperation("新增用户月度评分统计表")
    @PostMapping
    public AjaxResult add(@RequestBody GxtUserScore gxtUserScore)
    {
        return toAjax(gxtUserScoreService.insertGxtUserScore(gxtUserScore));
    }

    /**
     * 修改用户月度评分统计表
     */
    @Log(title = "用户月度评分统计表", businessType = BusinessType.UPDATE)
    @ApiOperation("修改用户月度评分统计表")
    @PutMapping
    public AjaxResult edit(@RequestBody GxtUserScore gxtUserScore)
    {
        return toAjax(gxtUserScoreService.updateGxtUserScore(gxtUserScore));
    }

    /**
     * 删除用户月度评分统计表
     */
    @Log(title = "用户月度评分统计表", businessType = BusinessType.DELETE)
    @ApiOperation("删除用户月度评分统计表")
    @ApiImplicitParam(name = "ids", value = "主键ID数组", required = true, dataType = "Long[]", paramType = "path", dataTypeClass = Long[].class)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(gxtUserScoreService.deleteGxtUserScoreByIds(ids));
    }
    
    /**
     * 统一提交人员评分页面的所有数据
     */
    @PreAuthorize("@ss.hasPermi('gxt:userscorepage:edit')")
    @Log(title = "人员评分提交", businessType = BusinessType.UPDATE)
    @ApiOperation("统一提交人员评分页面的所有数据")
    @PostMapping("/submitAllScores")
    public AjaxResult submitAllScores(@RequestBody GxtUserScoreSubmissionDTO submissionDTO)
    {
        try {
            // 保存系数与定检台数统计数据（根据monthPeriod查询是否存在记录）
            if (submissionDTO.getCoefficientScoreList() != null) {
                for (GxtCoefficientScore score : submissionDTO.getCoefficientScoreList()) {
                    score.setMonthPeriod(submissionDTO.getMonthPeriod());
                    // 根据monthPeriod查询是否存在记录
                    GxtCoefficientScore queryCondition = new GxtCoefficientScore();
                    queryCondition.setMonthPeriod(submissionDTO.getMonthPeriod());
                    List<GxtCoefficientScore> existingList = coefficientScoreService.selectGxtCoefficientScoreList(queryCondition);
                    
                    if (!existingList.isEmpty()) {
                        // 如果存在记录，则更新第一条记录
                        GxtCoefficientScore existingScore = existingList.get(0);
                        score.setId(existingScore.getId());
                        coefficientScoreService.updateGxtCoefficientScore(score);
                    } else {
                        // 如果不存在记录，则新增
                        score.setSubitemCoefficient(BigDecimal.valueOf(0.5));
                        score.setSubitemCoefficientSum(BigDecimal.valueOf(0.5));
                        coefficientScoreService.insertGxtCoefficientScore(score);
                    }
                }
            }
            
            // 保存安全运行工单列表数据（根据monthPeriod和userName查询是否存在记录）
            if (submissionDTO.getUserRuntimeScoreList() != null) {
                for (GxtUserRuntimeScore score : submissionDTO.getUserRuntimeScoreList()) {
                    score.setMonthPeriod(submissionDTO.getMonthPeriod());
                    // 根据monthPeriod和userName查询是否存在记录
                    GxtUserRuntimeScore queryCondition = new GxtUserRuntimeScore();
                    queryCondition.setMonthPeriod(submissionDTO.getMonthPeriod());
                    queryCondition.setUserName(score.getUserName());
                    queryCondition.setUserId(score.getUserId());
                    List<GxtUserRuntimeScore> existingList = userRuntimeScoreService.selectGxtUserRuntimeScoreList(queryCondition);
                    
                    if (!existingList.isEmpty()) {
                        // 如果存在记录，则更新第一条记录
                        GxtUserRuntimeScore existingScore = existingList.get(0);
                        score.setId(existingScore.getId());
                        userRuntimeScoreService.updateGxtUserRuntimeScore(score);
                    } else {
                        // 如果不存在记录，则新增
                        userRuntimeScoreService.insertGxtUserRuntimeScore(score);
                    }
                }
            }
            
            // 保存维保机组类型评分数据（根据monthPeriod和userName查询是否存在记录）
            if (submissionDTO.getUserFanInspectionScoreList() != null) {
                for (GxtUserFanInspectionScore score : submissionDTO.getUserFanInspectionScoreList()) {
                    score.setMonthPeriod(submissionDTO.getMonthPeriod());
                    // 根据monthPeriod和userName查询是否存在记录
                    GxtUserFanInspectionScore queryCondition = new GxtUserFanInspectionScore();
                    queryCondition.setMonthPeriod(submissionDTO.getMonthPeriod());
                    queryCondition.setUserName(score.getUserName());
                    queryCondition.setUserId(score.getUserId());
                    List<GxtUserFanInspectionScore> existingList = userFanInspectionScoreService.selectGxtUserFanInspectionScoreList(queryCondition);
                    
                    if (!existingList.isEmpty()) {
                        // 如果存在记录，则更新第一条记录
                        GxtUserFanInspectionScore existingScore = existingList.get(0);
                        score.setId(existingScore.getId());
                        userFanInspectionScoreService.updateGxtUserFanInspectionScore(score);
                    } else {
                        // 如果不存在记录，则新增
                        userFanInspectionScoreService.insertGxtUserFanInspectionScore(score);
                    }
                }
            }

            // 保存场站负责人评分列表数据（根据monthPeriod和userName查询是否存在记录）
            if (submissionDTO.getUserRepairProjectScoreList() != null) {
                for (GxtUserRepairProjectScore score : submissionDTO.getUserRepairProjectScoreList()) {
                    score.setMonthPeriod(submissionDTO.getMonthPeriod());
                    // 根据monthPeriod和userName查询是否存在记录
                    GxtUserRepairProjectScore queryCondition = new GxtUserRepairProjectScore();
                    queryCondition.setMonthPeriod(submissionDTO.getMonthPeriod());
                    queryCondition.setUserName(score.getUserName());
                    queryCondition.setUserId(score.getUserId());
                    List<GxtUserRepairProjectScore> existingList = userRepairProjectScoreService.selectGxtUserRepairProjectScoreList(queryCondition);

                    if (!existingList.isEmpty()) {
                        // 如果存在记录，则更新第一条记录
                        GxtUserRepairProjectScore existingScore = existingList.get(0);
                        score.setId(existingScore.getId());
                        userRepairProjectScoreService.updateGxtUserRepairProjectScore(score);
                    } else {
                        // 如果不存在记录，则新增
                        userRepairProjectScoreService.insertGxtUserRepairProjectScore(score);
                    }
                }
            }
            
            // 保存检修员得分列表数据（根据monthPeriod和userName查询是否存在记录）
            if (submissionDTO.getMaintenanceUserScoreData() != null) {
                for (GxtUserScore score : submissionDTO.getMaintenanceUserScoreData()) {
                    score.setMonthPeriod(submissionDTO.getMonthPeriod());
                    score.setCreateBy(getUsername());
                    score.setCreateTime(new Date());
                    // 根据monthPeriod和userName查询是否存在记录
                    GxtUserScore queryCondition = new GxtUserScore();
                    queryCondition.setMonthPeriod(submissionDTO.getMonthPeriod());
                    queryCondition.setUserName(score.getUserName());
                    List<GxtUserScore> existingList = gxtUserScoreService.selectGxtUserScoreList(queryCondition);
                    
                    if (!existingList.isEmpty()) {
                        // 如果存在记录，则更新第一条记录
                        GxtUserScore existingScore = existingList.get(0);
                        score.setId(existingScore.getId());
                        gxtUserScoreService.updateGxtUserScore(score);
                    } else {
                        // 如果不存在记录，则新增
                        gxtUserScoreService.insertGxtUserScore(score);
                    }
                }
            }
            
            // 保存维修员最终得分列表数据（根据monthPeriod和userName查询是否存在记录）
            if (submissionDTO.getRepairUserScoreData() != null) {
                for (GxtUserScore score : submissionDTO.getRepairUserScoreData()) {
                    score.setMonthPeriod(submissionDTO.getMonthPeriod());
                    score.setCreateBy(getUsername());
                    score.setCreateTime(new Date());
                    // 根据monthPeriod和userName查询是否存在记录
                    GxtUserScore queryCondition = new GxtUserScore();
                    queryCondition.setMonthPeriod(submissionDTO.getMonthPeriod());
                    queryCondition.setUserName(score.getUserName());
                    List<GxtUserScore> existingList = gxtUserScoreService.selectGxtUserScoreList(queryCondition);
                    
                    if (!existingList.isEmpty()) {
                        // 如果存在记录，则更新第一条记录
                        GxtUserScore existingScore = existingList.get(0);
                        score.setId(existingScore.getId());
                        gxtUserScoreService.updateGxtUserScore(score);
                    } else {
                        // 如果不存在记录，则新增
                        gxtUserScoreService.insertGxtUserScore(score);
                    }
                }
            }
            
            return AjaxResult.success("评分提交成功");
        } catch (Exception e) {
            return AjaxResult.error("评分提交失败: " + e.getMessage());
        }
    }
}