package com.ygtx.gxt.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.*;
import java.time.format.DateTimeFormatter;

import com.ygtx.common.core.domain.entity.SysDept;
import com.ygtx.common.core.domain.entity.SysRole;
import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.core.domain.model.LoginUser;
import com.ygtx.common.utils.SecurityUtils;
import com.ygtx.common.utils.StringUtils;
import com.ygtx.framework.aspectj.DataScopeAspect;
import com.ygtx.gxt.domain.*;
import com.ygtx.gxt.mapper.*;
import com.ygtx.system.domain.SysPostHomePage;
import com.ygtx.system.mapper.SysDeptMapper;
import com.ygtx.system.mapper.SysPostHomePageMapper;
import com.ygtx.system.mapper.SysRoleMapper;
import com.ygtx.system.mapper.SysUserMapper;
import com.ygtx.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ygtx.gxt.service.IGxtMonthScoreService;

/**
 * 月度统计表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-11-12
 */
@Service
public class GxtMonthScoreServiceImpl implements IGxtMonthScoreService 
{
    @Autowired
    private GxtMonthScoreMapper gxtMonthScoreMapper;

    @Autowired
    private GxtCoefficientScoreMapper gxtCoefficientScoreMapper;

    @Autowired
    private GxtMonthRuntimeMapper gxtMonthRuntimeMapper;

    @Autowired
    private GxtMonthFanInspectionMapper gxtMonthFanInspectionMapper;

    @Autowired
    private GxtMonthRepairProjectMapper gxtMonthRepairProjectMapper;

    @Autowired
    private GxtUserScoreMapper gxtUserScoreMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private GxtMonthScoreLogMapper gxtMonthScoreLogMapper;

    @Autowired
    private GxtWorkOrderMapper gxtWorkOrderMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private GxtDeviceRuntimeMapper gxtDeviceRuntimeMapper;

    @Autowired
    private GxtDeviceRuntimePersonMapper gxtDeviceRuntimePersonMapper;

    @Autowired
    private GxtWorkOrderPersonMapper gxtWorkOrderPersonMapper;

    @Autowired
    private GxtRepairOrderMapper gxtRepairOrderMapper;

    @Autowired
    private GxtRepairOrderPersonMapper gxtRepairOrderPersonMapper;

    @Autowired
    private SysPostHomePageMapper sysPostHomePageMapper;

    @Autowired
    private ISysConfigService configService;

    /**
     * 查询月度统计表
     * 
     * @param id 月度统计表主键
     * @return 月度统计表
     */
    @Override
    public GxtMonthScore selectGxtMonthScoreById(Long id)
    {
        return gxtMonthScoreMapper.selectGxtMonthScoreById(id);
    }


    @Override
    public GxtMonthScore getGxtMonthScoreByParams(Integer rtType,String monthPeriod,Long deptId)
    {
        return getGxtMonthScoreByNoAdd(rtType,monthPeriod,deptId);
    }

    @Override
    public List<GxtWorkOrder> getWorkOrderByMonth(String model, String inspectionTypeId, Long pid, String monthPeriod) {
        GxtWorkOrder workOrder = new GxtWorkOrder();
        workOrder.setModel(model);
        workOrder.setInspectionType(inspectionTypeId);
        workOrder.setPcsStationPid(pid);
        workOrder.setMonthPeriod(monthPeriod);
        workOrder.setWorkOrderStatus("archived");
        addBusinessDataScopeFilter(workOrder);
        return gxtWorkOrderMapper.selectGxtWorkOrderListByMonth(workOrder);
    }



    /**
     * 添加业务特定的数据权限过滤条件
     * 基于角色的数据范围进行自定义权限控制
     *
     * @param gxtWorkOrder 维保工单查询条件
     */
    private void addBusinessDataScopeFilter(GxtWorkOrder gxtWorkOrder) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return;
        }

        SysUser currentUser = loginUser.getUser();
        if (currentUser == null) {
            return;
        }

        // 如果是超级管理员，不过滤数据
        if (currentUser.isAdmin()) {
            return;
        }

        // 获取用户角色
        List<SysRole> roles = currentUser.getRoles();
        if (roles == null || roles.isEmpty()) {
            return;
        }

        // 检查是否有"全部数据"权限的角色，如果有则不过滤
        boolean hasAllDataPermission = roles.stream()
                .anyMatch(role -> DataScopeAspect.DATA_SCOPE_ALL.equals(role.getDataScope()));

        // 如果有任何一个角色有全部数据权限，则不过滤
        if (!hasAllDataPermission) {
            // 构建业务特定的数据权限SQL
            StringBuilder businessSql = new StringBuilder();

            // 遍历用户角色，根据角色的数据范围添加业务特定的权限控制
            for (SysRole role : roles) {
                String dataScope = role.getDataScope();

                // 自定义数据权限 - 根据角色的数据范围值来控制查询条件
                if (DataScopeAspect.DATA_SCOPE_CUSTOM.equals(dataScope)) {
                    // 获取具有自定义数据权限的角色ID列表
                    List<String> customRoleIds = new ArrayList<>();
                    for (SysRole r : roles) {
                        if (DataScopeAspect.DATA_SCOPE_CUSTOM.equals(r.getDataScope())) {
                            customRoleIds.add(String.valueOf(r.getRoleId()));
                        }
                    }

                    // 构建自定义数据权限查询条件
                    if (businessSql.length() > 0) {
                        businessSql.append(" OR ");
                    }

                    if (customRoleIds.size() > 1) {
                        // 多个自定义数据权限角色使用IN查询
                        businessSql.append("(t.pcs_station_pid IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                                .append(String.join(",", customRoleIds))
                                .append("))")
                                .append(" OR t.pcs_station_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                                .append(String.join(",", customRoleIds))
                                .append("))")
                                .append(" OR t.gxt_center_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                                .append(String.join(",", customRoleIds))
                                .append(")))");
                    } else {
                        // 单个自定义数据权限角色查询
                        businessSql.append("(t.pcs_station_pid IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                                .append(role.getRoleId())
                                .append(")")
                                .append(" OR t.pcs_station_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                                .append(role.getRoleId())
                                .append(")")
                                .append(" OR t.gxt_center_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                                .append(role.getRoleId())
                                .append("))");
                    }
                    continue;
                }

                // 部门数据权限 - 适用于部门负责人角色
                if (DataScopeAspect.DATA_SCOPE_DEPT.equals(dataScope)) {
                    if (businessSql.length() > 0) {
                        businessSql.append(" OR ");
                    }
                    businessSql.append("(t.pcs_station_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR t.pcs_station_pid = ")
                            .append(currentUser.getDeptId())
                            .append(" OR t.gxt_center_id = ")
                            .append(currentUser.getDeptId())
                            .append(")");
                    continue;
                }

                // 部门及以下数据权限
                if (DataScopeAspect.DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
                    if (businessSql.length() > 0) {
                        businessSql.append(" OR ");
                    }
                    businessSql.append("(t.pcs_station_id IN ")
                            .append("(SELECT dept_id FROM sys_dept WHERE dept_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR FIND_IN_SET(")
                            .append(currentUser.getDeptId())
                            .append(", ancestors))")
                            .append(" OR t.pcs_station_pid IN ")
                            .append("(SELECT dept_id FROM sys_dept WHERE dept_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR FIND_IN_SET(")
                            .append(currentUser.getDeptId())
                            .append(", ancestors))")
                            .append(" OR t.gxt_center_id IN ")
                            .append("(SELECT dept_id FROM sys_dept WHERE dept_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR FIND_IN_SET(")
                            .append(currentUser.getDeptId())
                            .append(", ancestors)))");
                    continue;
                }

                // 仅本人数据权限 - 适用于主检修员角色
                if (DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope)) {
                    if (businessSql.length() > 0) {
                        businessSql.append(" OR ");
                    }
                    businessSql.append("(t.team_leader_id = ")
                            .append(currentUser.getUserId())
                            .append(" OR t.assign_user_id = ")
                            .append(currentUser.getUserId())
                            .append(" OR t.accept_user_id = ")
                            .append(currentUser.getUserId())
                            .append(" OR t.id IN (SELECT order_id FROM gxt_work_order_person WHERE user_id = ")
                            .append(currentUser.getUserId())
                            .append(") ")
                            .append(" OR t.create_by = '")
                            .append(currentUser.getUserName())
                            .append("')");
                    continue;
                }
            }
            String selfData = configService.selectConfigByKey("gxt.oder.selfData");
            if (StringUtils.isNotEmpty(selfData) && "1".equals(selfData)) {
                if (businessSql.length() > 0) {
                    businessSql.append(" OR ");
                }
                businessSql.append("(t.team_leader_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR t.assign_user_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR t.accept_user_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR t.id IN (SELECT order_id FROM gxt_work_order_person WHERE user_id = ")
                        .append(currentUser.getUserId())
                        .append(") ")
                        .append(" OR t.create_by = '")
                        .append(currentUser.getUserName())
                        .append("')");
            }
            // 如果构建了业务特定的过滤条件，则添加到查询参数中
            if (businessSql.length() > 0) {
                String businessDataScopeSql = " AND (" + businessSql.toString() + ")";
                gxtWorkOrder.getParams().put("businessDataScope", businessDataScopeSql);
            }
        }
        // 对于已作废(work_order_status = 'invalid')的工单，只有admin用户才能查看
        if (!SecurityUtils.isAdmin(currentUser.getUserId())) {
            String invalidFilterSql = " AND (t.work_order_status != 'invalid')";
            if (gxtWorkOrder.getParams().get("businessDataScope") != null) {
                String existingSql = gxtWorkOrder.getParams().get("businessDataScope").toString();
                gxtWorkOrder.getParams().put("businessDataScope", existingSql + invalidFilterSql);
            } else {
                gxtWorkOrder.getParams().put("businessDataScope", invalidFilterSql);
            }
        }
    }





    /**
     * 添加业务特定的数据权限过滤条件
     * 基于角色的数据范围进行自定义权限控制
     *
     * @param gxtRepairOrder 维修工单查询条件
     */
    private void addBusinessDataScopeFilter(GxtRepairOrder gxtRepairOrder) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return;
        }

        SysUser currentUser = loginUser.getUser();
        if (currentUser == null) {
            return;
        }

        // 如果是超级管理员，不过滤数据
        if (currentUser.isAdmin()) {
            return;
        }

        // 获取用户角色
        List<SysRole> roles = currentUser.getRoles();
        if (roles == null || roles.isEmpty()) {
            return;
        }

        // 检查是否有"全部数据"权限的角色，如果有则不过滤
        boolean hasAllDataPermission = roles.stream()
                .anyMatch(role -> DataScopeAspect.DATA_SCOPE_ALL.equals(role.getDataScope()));

        // 如果有任何一个角色有全部数据权限，则不过滤
        if (!hasAllDataPermission) {
            // 构建业务特定的数据权限SQL
            StringBuilder businessSql = new StringBuilder();

            // 遍历用户角色，根据角色的数据范围添加业务特定的权限控制
            for (SysRole role : roles) {
                String dataScope = role.getDataScope();

                // 自定义数据权限 - 根据角色的数据范围值来控制查询条件
                if (DataScopeAspect.DATA_SCOPE_CUSTOM.equals(dataScope)) {
                    // 获取具有自定义数据权限的角色ID列表
                    List<String> customRoleIds = new ArrayList<>();
                    for (SysRole r : roles) {
                        if (DataScopeAspect.DATA_SCOPE_CUSTOM.equals(r.getDataScope())) {
                            customRoleIds.add(String.valueOf(r.getRoleId()));
                        }
                    }

                    // 构建自定义数据权限查询条件
                    if (businessSql.length() > 0) {
                        businessSql.append(" OR ");
                    }

                    if (customRoleIds.size() > 1) {
                        // 多个自定义数据权限角色使用IN查询
                        businessSql.append("(t.pcs_station_pid IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                                .append(String.join(",", customRoleIds))
                                .append("))")
                                .append(" OR t.pcs_station_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                                .append(String.join(",", customRoleIds))
                                .append("))")
                                .append(" OR t.gxt_center_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                                .append(String.join(",", customRoleIds))
                                .append(")))");
                    } else {
                        // 单个自定义数据权限角色查询
                        businessSql.append("(t.pcs_station_pid IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                                .append(role.getRoleId())
                                .append(")")
                                .append(" OR t.pcs_station_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                                .append(role.getRoleId())
                                .append(")")
                                .append(" OR t.gxt_center_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                                .append(role.getRoleId())
                                .append("))");
                    }
                    continue;
                }

                // 部门数据权限 - 适用于部门负责人角色
                if (DataScopeAspect.DATA_SCOPE_DEPT.equals(dataScope)) {
                    if (businessSql.length() > 0) {
                        businessSql.append(" OR ");
                    }
                    businessSql.append("(t.pcs_station_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR t.pcs_station_pid = ")
                            .append(currentUser.getDeptId())
                            .append(" OR t.gxt_center_id = ")
                            .append(currentUser.getDeptId())
                            .append(")");
                    continue;
                }

                // 部门及以下数据权限
                if (DataScopeAspect.DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
                    if (businessSql.length() > 0) {
                        businessSql.append(" OR ");
                    }
                    businessSql.append("(t.pcs_station_id IN ")
                            .append("(SELECT dept_id FROM sys_dept WHERE dept_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR FIND_IN_SET(")
                            .append(currentUser.getDeptId())
                            .append(", ancestors))")
                            .append(" OR t.pcs_station_pid IN ")
                            .append("(SELECT dept_id FROM sys_dept WHERE dept_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR FIND_IN_SET(")
                            .append(currentUser.getDeptId())
                            .append(", ancestors))")
                            .append(" OR t.gxt_center_id IN ")
                            .append("(SELECT dept_id FROM sys_dept WHERE dept_id = ")
                            .append(currentUser.getDeptId())
                            .append(" OR FIND_IN_SET(")
                            .append(currentUser.getDeptId())
                            .append(", ancestors)))");
                    continue;
                }

                // 仅本人数据权限 - 适用于主检修员角色
                if (DataScopeAspect.DATA_SCOPE_SELF.equals(dataScope)) {
                    if (businessSql.length() > 0) {
                        businessSql.append(" OR ");
                    }
                    businessSql.append("(t.team_leader_id = ")
                            .append(currentUser.getUserId())
                            .append(" OR t.assign_user_id = ")
                            .append(currentUser.getUserId())
                            .append(" OR t.accept_user_id = ")
                            .append(currentUser.getUserId())
                            .append(" OR t.id IN (SELECT order_id FROM gxt_repair_order_person WHERE user_id = ")
                            .append(currentUser.getUserId())
                            .append(") ")
                            .append(" OR t.create_by = '")
                            .append(currentUser.getUserName())
                            .append("')");
                    continue;
                }
            }
            String selfData = configService.selectConfigByKey("gxt.oder.selfData");
            if (StringUtils.isNotEmpty(selfData) && "1".equals(selfData)) {
                if (businessSql.length() > 0) {
                    businessSql.append(" OR ");
                }
                businessSql.append("(t.team_leader_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR t.assign_user_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR t.accept_user_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR t.id IN (SELECT order_id FROM gxt_repair_order_person WHERE user_id = ")
                        .append(currentUser.getUserId())
                        .append(") ")
                        .append(" OR t.create_by = '")
                        .append(currentUser.getUserName())
                        .append("')");
            }
            // 如果构建了业务特定的过滤条件，则添加到查询参数中
            if (businessSql.length() > 0) {
                String businessDataScopeSql = " AND (" + businessSql.toString() + ")";
                gxtRepairOrder.getParams().put("businessDataScope", businessDataScopeSql);
            }
        }
        // 对于已作废(work_order_status = 'invalid')的工单，只有admin用户才能查看
        if (!SecurityUtils.isAdmin(currentUser.getUserId())) {
            String invalidFilterSql = " AND (t.work_order_status != 'invalid')";
            if (gxtRepairOrder.getParams().get("businessDataScope") != null) {
                String existingSql = gxtRepairOrder.getParams().get("businessDataScope").toString();
                gxtRepairOrder.getParams().put("businessDataScope", existingSql + invalidFilterSql);
            } else {
                gxtRepairOrder.getParams().put("businessDataScope", invalidFilterSql);
            }
        }
    }

    @Override
    public List<GxtRepairOrder> getRepairOrderByMonth(String maintenanceType, Long pid, String monthPeriod) {
        GxtRepairOrder repairOrder = new GxtRepairOrder();
        repairOrder.setMaintenanceType(maintenanceType);
        repairOrder.setPcsStationPid(pid);
        repairOrder.setMonthPeriod(monthPeriod);
        repairOrder.setWorkOrderStatus("archived");
        addBusinessDataScopeFilter(repairOrder);
        return gxtRepairOrderMapper.selectGxtRepairOrderListByMonth(repairOrder);
    }

    private GxtMonthScore getGxtMonthScoreByNoAdd(Integer rtType,String monthPeriod,Long deptId) {
        Long userId = SecurityUtils.getUserId();
        String userAccount = SecurityUtils.getUsername();
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        String deptName = SecurityUtils.getLoginUser().getUser().getDept().getDeptName();
        if (deptId==null || deptId==0L) {
            SysDept dept = sysDeptMapper.selectDeptById(SecurityUtils.getDeptId());
            if (dept!=null && dept.getStatus().equals("0") && dept.getLevel().equals("3")) {
                deptId = dept.getDeptId();
                deptName = dept.getDeptName();
            }else if (dept!=null && dept.getParentId()!=null){
                SysDept parentDept = sysDeptMapper.selectDeptById(dept.getParentId());
                if (parentDept!=null && parentDept.getStatus().equals("0") && parentDept.getLevel().equals("3")) {
                    deptId = parentDept.getDeptId();
                    deptName = parentDept.getDeptName();
                }
            }
        }
        // 上月评分系数
        YearMonth yearMonth = YearMonth.parse(monthPeriod);

        YearMonth previousMonth = yearMonth.minusMonths(1);

        String previousMonthStr = previousMonth.format(DateTimeFormatter.ofPattern("yyyy-MM"));

        // 2. 获取该月的最后一天的最后一刻（LocalDateTime）
        LocalDateTime endOfMonth = yearMonth.atEndOfMonth()
                .atTime(23, 59, 59);

        // 3. 转换为 java.util.Date（需要指定时区）
        Date endTime = Date.from(endOfMonth.atZone(ZoneId.systemDefault()).toInstant());

        BigDecimal numWork = BigDecimal.ONE;
        BigDecimal numRepair = BigDecimal.ONE;

        GxtCoefficientScore pc = new GxtCoefficientScore();
        pc.setMonthPeriod(previousMonthStr);
        pc.setDeptId(deptId);
        List<GxtCoefficientScore> pcList = gxtCoefficientScoreMapper.selectGxtCoefficientScoreList(pc);
        if (!pcList.isEmpty()) {
            if (pcList.get(0).getRepairOrderCoefficient()!=null) {
                numRepair = pcList.get(0).getRepairOrderCoefficient();
            }
            if (pcList.get(0).getWorkOrderCoefficient()!=null) {
                numWork = pcList.get(0).getWorkOrderCoefficient();
            }
        }

        GxtMonthScore monthScore = new GxtMonthScore();
        monthScore.setMonthPeriod(monthPeriod);
        monthScore.setDeptId(deptId);
        List<GxtMonthScore> monthScoreList = selectGxtMonthScoreList(monthScore);
        if (monthScoreList.isEmpty() || monthScoreList.get(0).getStatus()==0) {
            if (deptId==null || deptId==0L) {
                monthScore.setStatus(4);
                return monthScore;
            }

            if (monthScoreList.isEmpty()) {
                // 新增
                monthScore.setStatus(0);
                monthScore.setPersionId(userId);
                monthScore.setCreateTime(new Date());
                monthScore.setCreateBy(userAccount);
                gxtMonthScoreMapper.insertGxtMonthScore(monthScore);
            }else {
                monthScore = monthScoreList.get(0);
            }

            // 本月维保工单统计
            GxtCoefficientScore coefficientScore = new GxtCoefficientScore();
            coefficientScore.setMonthPeriod(monthPeriod);
            coefficientScore.setDeptId(deptId);
            List<GxtCoefficientScore> coefficientScoreList = gxtCoefficientScoreMapper.selectGxtCoefficientScoreList(coefficientScore);
            if (!coefficientScoreList.isEmpty()) {
                coefficientScore = coefficientScoreList.get(0);
            } else {
                coefficientScore.setDetpName(deptName);
                coefficientScore.setPlannedCount(0);
                coefficientScore.setActualCount(0);
                coefficientScore.setStatus(0);
                coefficientScore.setCreateBy(userAccount);
                coefficientScore.setCreateTime(new Date());
                gxtCoefficientScoreMapper.insertGxtCoefficientScore(coefficientScore);
            }
            monthScore.setCoefficientScore(coefficientScore);

            // 月度运行时长统计
            addDeviceRuntime(monthPeriod,endTime);
            // 设备运行情况
            GxtMonthRuntime monthRuntime = new GxtMonthRuntime();
            monthRuntime.setMonthPeriod(monthPeriod);
            monthRuntime.setDeptId(deptId);
            List<GxtMonthRuntime> monthRuntimes = gxtMonthRuntimeMapper.selectGxtMonthRuntimeList(monthRuntime);
            if (monthRuntimes.isEmpty()) {
                monthRuntimes = gxtMonthRuntimeMapper.selectGxtMonthRuntimeListByAdd(monthRuntime);
                if (!monthRuntimes.isEmpty()) {
                    for (GxtMonthRuntime runtime:monthRuntimes) {
                        runtime.setMonthScoreId(monthScore.getId());
                        runtime.setMonthPeriod(monthPeriod);
                        gxtMonthRuntimeMapper.insertGxtMonthRuntime(runtime);
                    }
                }
            }
            monthScore.setMonthRuntimes(monthRuntimes);
        } else {
            // 月度评分主表
            monthScore = monthScoreList.get(0);

            // 本月维保工单统计
            GxtCoefficientScore coefficientScore = new GxtCoefficientScore();
            coefficientScore.setMonthPeriod(monthPeriod);
            coefficientScore.setDeptId(deptId);
            List<GxtCoefficientScore> coefficientScoreList = gxtCoefficientScoreMapper.selectGxtCoefficientScoreList(coefficientScore);
            if (!coefficientScoreList.isEmpty()) {
                monthScore.setCoefficientScore(coefficientScoreList.get(0));
            }

            // 设备运行情况
            GxtMonthRuntime monthRuntime = new GxtMonthRuntime();
            monthRuntime.setMonthScoreId(monthScore.getId());
            List<GxtMonthRuntime> monthRuntimes = gxtMonthRuntimeMapper.selectGxtMonthRuntimeList(monthRuntime);
            monthScore.setMonthRuntimes(monthRuntimes);
        }

        // 维保机型类型统计
        GxtMonthFanInspection monthFanInspection = new GxtMonthFanInspection();
        monthFanInspection.setDeptId(deptId);
        monthFanInspection.setMonthPeriod(monthPeriod);
        List<GxtMonthFanInspection> monthFanInspections = gxtMonthFanInspectionMapper.selectGxtMonthFanInspectionListByTwice(monthFanInspection);
        List<GxtMonthFanInspection> fanInspectionList = new ArrayList<>();
        if (!monthFanInspections.isEmpty()) {
            while (true) {
                boolean isBreak = true;
                for (GxtMonthFanInspection fanInspection : monthFanInspections) {
                    if (fanInspection.getInspectionTypeId().contains(",")) {
                        String[] ids = fanInspection.getInspectionTypeId().split(",");
                        for (int i = 0; i < ids.length; i++) {
                            GxtMonthFanInspection ft = new GxtMonthFanInspection();
                            ft.setModel(fanInspection.getModel());
                            ft.setDeviceCount(fanInspection.getDeviceCount());
                            ft.setInspectionTypeId(ids[i]);
                            fanInspectionList.add(ft);
                        }
                        monthFanInspections.remove(fanInspection);
                        isBreak = false;
                        break;
                    }
                }
                if (isBreak) {
                    break;
                }
            }
            if (!fanInspectionList.isEmpty()) {
                for (GxtMonthFanInspection inspection:fanInspectionList) {
                    boolean isAdd = true;
                    for (GxtMonthFanInspection fanInspection : monthFanInspections) {
                        if (fanInspection.getModel().equals(inspection.getModel()) && fanInspection.getInspectionTypeId().equals(inspection.getInspectionTypeId())) {
                            fanInspection.setDeviceCount(fanInspection.getDeviceCount()+inspection.getDeviceCount());
                            isAdd = false;
                            break;
                        }
                    }
                    if (isAdd) {
                        monthFanInspections.add(inspection);
                    }
                }
            }
        }
        monthScore.setMonthFanInspections(monthFanInspections);

        // 根据维保机型类型统计维保工单
        List<GxtWorkOrder> workOrderList = new ArrayList<>();
        if (!monthFanInspections.isEmpty()) {
            GxtMonthFanInspection fanInspection = monthFanInspections.get(0);
            workOrderList = getWorkOrderByMonth(fanInspection.getModel(),fanInspection.getInspectionTypeId(),deptId,monthPeriod);
        }
        monthScore.setWorkOrderList(workOrderList);

        // 维修工单详情
        GxtMonthRepairProject monthRepairProject = new GxtMonthRepairProject();
        monthRepairProject.setDeptId(deptId);
        monthRepairProject.setMonthPeriod(monthPeriod);
        List<GxtMonthRepairProject> monthRepairProjects = gxtMonthRepairProjectMapper.selectGxtMonthRepairProjectListByTwice(monthRepairProject);
        monthScore.setMonthRepairProjects(monthRepairProjects);

        // 根据维修类型统计维修工单
        List<GxtRepairOrder> repairOrderList = new ArrayList<>();
        if (!monthRepairProjects.isEmpty()) {
            GxtMonthRepairProject repairProject = monthRepairProjects.get(0);
            repairOrderList = getRepairOrderByMonth(repairProject.getMaintenanceType(), deptId, monthPeriod);
        }
        monthScore.setRepairOrderList(repairOrderList);

        // 组员考核得分
        GxtUserScore userScore = new GxtUserScore();
        userScore.setMonthScoreId(monthScore.getId());
        if (rtType==0) {
            userScore.setUserName(userAccount);
            userScore.setNickName(nickName);
        }else {
            userScore.setRankPermission(getJXY());
        }
        List<GxtUserScore> userScores = gxtUserScoreMapper.selectGxtUserScoreList(userScore);

        // 更新全组扣分情况
//        if (monthScore.getCoefficientScore()!=null && monthScore.getCoefficientScore().getGroupDeduction()!=null) {
//
//            BigDecimal groupDeduction = monthScore.getCoefficientScore().getGroupDeduction();
//            if (monthScore.getCoefficientScore().getStatus()!=null && monthScore.getCoefficientScore().getStatus()==1) {
//                // 不扣分
//                for (GxtUserScore item:userScores) {
//                    GxtDeviceRuntimePerson deviceRuntimePerson = new GxtDeviceRuntimePerson();
//                    deviceRuntimePerson.setPersonId(item.getUserId());
//                    deviceRuntimePerson.setMonthPeriod(monthPeriod);
//                    List<GxtDeviceRuntimePerson> peopleScore = gxtDeviceRuntimePersonMapper.selectGxtDeviceRuntimePersonList(deviceRuntimePerson);
//                    BigDecimal runTimeScore = BigDecimal.ZERO;
//                    if (!peopleScore.isEmpty()) {
//                        for (GxtDeviceRuntimePerson person:peopleScore) {
//                            if (person.getScore()!=null) {
//                                runTimeScore = runTimeScore.add(person.getScore());
//                            }
//                        }
//                    }
//                    BigDecimal finalScore = (item.getMaintenanceTotalScore().add(runTimeScore).multiply(numWork)).add(item.getRepairTotalScore().multiply(numRepair));
//                    if (item.getFinalScore().compareTo(finalScore)==0) {
//                        break;
//                    }
//                    item.setFinalScore(finalScore);
//                    item.setUpdateBy(userAccount);
//                    item.setUpdateTime(new Date());
//                    gxtUserScoreMapper.updateGxtUserScore(item);
//                }
//            }else {
//                // 扣分
//                for (GxtUserScore item:userScores) {
//                    GxtDeviceRuntimePerson deviceRuntimePerson = new GxtDeviceRuntimePerson();
//                    deviceRuntimePerson.setPersonId(item.getUserId());
//                    deviceRuntimePerson.setMonthPeriod(monthPeriod);
//                    List<GxtDeviceRuntimePerson> peopleScore = gxtDeviceRuntimePersonMapper.selectGxtDeviceRuntimePersonList(deviceRuntimePerson);
//                    BigDecimal runTimeScore = BigDecimal.ZERO;
//                    if (!peopleScore.isEmpty()) {
//                        for (GxtDeviceRuntimePerson person:peopleScore) {
//                            if (person.getScore()!=null) {
//                                runTimeScore = runTimeScore.add(person.getScore());
//                            }
//                        }
//                    }
//                    BigDecimal finalScore = (item.getMaintenanceTotalScore().add(runTimeScore).multiply(numWork)).add(item.getRepairTotalScore().multiply(numRepair));
//                    finalScore = finalScore.subtract(groupDeduction);
//                    if (item.getFinalScore().compareTo(finalScore)==0) {
//                        break;
//                    }
//                    item.setFinalScore(finalScore);
//                    item.setUpdateBy(userAccount);
//                    item.setUpdateTime(new Date());
//                    gxtUserScoreMapper.updateGxtUserScore(item);
//                }
//            }
//        }
        monthScore.setUserScores(userScores);
        return monthScore;
    }

    private String getJXY() {
        SysPostHomePage postHomePage = new SysPostHomePage();
        postHomePage.setStatus("0");
        postHomePage.setHomePageType("5");
        List<SysPostHomePage> list = sysPostHomePageMapper.selectSysPostHomePageList(postHomePage);
        if (!list.isEmpty()) {
            postHomePage = list.get(0);
            String permission = "";
            SysUser user = new SysUser();
            user.setStatus("0");
            user.setDelFlag("0");
            user.setRankPermission(postHomePage.getPostIds());
            List<SysUser> users = sysUserMapper.selectUserListByDeptId(user);
            if (!users.isEmpty()) {
                for (SysUser sysUser : users) {
                    permission += "," + sysUser.getUserId();
                }
                permission = permission.substring(1);
            }
            return permission;
        }
        return "";
    }


    @Override
    public GxtMonthScore getGxtMonthScoreByParams(Integer rtType,Long id) {
        GxtMonthScore monthScore = gxtMonthScoreMapper.selectGxtMonthScoreById(id);
        if (monthScore==null) {
            return null;
        }
        return getGxtMonthScoreByParams(rtType,monthScore.getMonthPeriod(), monthScore.getDeptId());
    }

    /**
     * 月度运行时长统计
     * @param monthPeriod
     */
    private void addDeviceRuntime(String monthPeriod,Date endTime) {
        GxtDeviceRuntime gxtDeviceRuntime = new GxtDeviceRuntime();
        gxtDeviceRuntime.setMonthPeriod(monthPeriod);
        List<GxtDeviceRuntime> deviceRuntimes = gxtDeviceRuntimeMapper.selectGxtDeviceRuntimeList(gxtDeviceRuntime);
        if (deviceRuntimes.isEmpty()) {
            deviceRuntimes = gxtDeviceRuntimeMapper.selectGxtDeviceRuntimeByRepairOrder(gxtDeviceRuntime);
            if (!deviceRuntimes.isEmpty()) {
                for (GxtDeviceRuntime deviceRuntime:deviceRuntimes) {
                    deviceRuntime.setMonthPeriod(monthPeriod);
                    deviceRuntime.setStatTime(new Date());
                    deviceRuntime.setCreateBy(SecurityUtils.getUsername());
                    deviceRuntime.setCreateTime(new Date());
                    if (deviceRuntime.getRepairOrderId()!=null){
                        GxtRepairOrder repairOrder = gxtRepairOrderMapper.selectGxtRepairOrderById(deviceRuntime.getRepairOrderId());
                        if (repairOrder!=null) {
                            deviceRuntime.setDeptId(repairOrder.getPcsStationPid());
                            gxtDeviceRuntimeMapper.insertGxtDeviceRuntime(deviceRuntime);
                            Long leaderId = repairOrder.getTeamLeaderId();
                            GxtRepairOrderPerson repairOrderPerson = new GxtRepairOrderPerson();
                            repairOrderPerson.setOrderId(deviceRuntime.getRepairOrderId());
                            List<GxtRepairOrderPerson> orderPersonList = gxtRepairOrderPersonMapper.selectGxtRepairOrderPersonList(repairOrderPerson);
                            if (!orderPersonList.isEmpty()) {
                                BigDecimal num = new BigDecimal(orderPersonList.size());
                                BigDecimal personScore = deviceRuntime.getScroe().divide(num, 2, RoundingMode.HALF_UP);
                                for (GxtRepairOrderPerson workOrderPerson:orderPersonList) {
                                    GxtDeviceRuntimePerson person = new GxtDeviceRuntimePerson();
                                    person.setDeviceRuntimId(deviceRuntime.getId());
                                    person.setPersonId(workOrderPerson.getUserId());
                                    if (leaderId!=null && workOrderPerson.getUserId().equals(leaderId)) {
                                        person.setIsLeader(1);
                                    }else {
                                        person.setIsLeader(0);
                                    }
                                    person.setScore(personScore);
                                    person.setMonthPeriod(monthPeriod);
                                    person.setStatus(0);
                                    person.setCreateBy(SecurityUtils.getUsername());
                                    person.setCreateTime(new Date());
                                    gxtDeviceRuntimePersonMapper.insertGxtDeviceRuntimePerson(person);
                                }
                            }
                        }
                    }
                }
            }
            GxtDeviceRuntime orderRuntime = new GxtDeviceRuntime();
            orderRuntime.setMonthPeriod(monthPeriod);
            orderRuntime.setFaultTime(endTime);
            List<GxtDeviceRuntime> orderRuntimes = gxtDeviceRuntimeMapper.selectGxtDeviceRuntimeByWorkOrder(orderRuntime);
            if (!orderRuntimes.isEmpty()) {
                for (GxtDeviceRuntime deviceRuntime:orderRuntimes) {
                    deviceRuntime.setMonthPeriod(monthPeriod);
                    deviceRuntime.setStatTime(new Date());
                    deviceRuntime.setCreateBy(SecurityUtils.getUsername());
                    deviceRuntime.setCreateTime(new Date());
                    if (deviceRuntime.getWorkOrderId()!=null) {
                        GxtWorkOrder workOrder = gxtWorkOrderMapper.selectGxtWorkOrderById(deviceRuntime.getWorkOrderId());
                        if (workOrder!=null) {
                            deviceRuntime.setDeptId(workOrder.getPcsStationPid());
                            gxtDeviceRuntimeMapper.insertGxtDeviceRuntime(deviceRuntime);
                            Long leaderId = workOrder.getTeamLeaderId();
                            List<GxtWorkOrderPerson> orderPersonList = gxtWorkOrderPersonMapper.selectGxtWorkOrderPersonByOrderId(deviceRuntime.getWorkOrderId());
                            if (!orderPersonList.isEmpty()) {
                                BigDecimal num = new BigDecimal(orderPersonList.size());
                                BigDecimal personScore = deviceRuntime.getScroe().divide(num, 2, RoundingMode.HALF_UP);
                                for (GxtWorkOrderPerson workOrderPerson:orderPersonList) {
                                    GxtDeviceRuntimePerson person = new GxtDeviceRuntimePerson();
                                    person.setDeviceRuntimId(deviceRuntime.getId());
                                    person.setPersonId(workOrderPerson.getUserId());
                                    if (leaderId!=null && workOrderPerson.getUserId().equals(leaderId)) {
                                        person.setIsLeader(1);
                                    }else {
                                        person.setIsLeader(0);
                                    }
                                    person.setScore(personScore);
                                    person.setMonthPeriod(monthPeriod);
                                    person.setStatus(0);
                                    person.setCreateBy(SecurityUtils.getUsername());
                                    person.setCreateTime(new Date());
                                    gxtDeviceRuntimePersonMapper.insertGxtDeviceRuntimePerson(person);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public List<GxtMonthScore> getMonthScoreList(GxtMonthScore monthScore) {
        return gxtMonthScoreMapper.selectGxtMonthScoreListByStatus(monthScore);
    }

    @Override
    public void submitGxtMonthScore(GxtMonthScore monthScore) {
        if (monthScore.getPreviousStatus()!=null && monthScore.getPreviousStatus()>monthScore.getStatus()) {
            return;
        }
        if (monthScore.getStatus()==1 || monthScore.getStatus()==2 || monthScore.getStatus()==3) {
            GxtMonthScoreLog monthScoreLog = new GxtMonthScoreLog();
            monthScore.setUpdateBy(SecurityUtils.getUsername());
            monthScore.setUpdateTime(new Date());
            gxtMonthScoreMapper.updateGxtMonthScore(monthScore);
            GxtCoefficientScore coefficientScore = monthScore.getCoefficientScore();
            if (coefficientScore!=null) {
                coefficientScore.setUpdateBy(SecurityUtils.getUsername());
                coefficientScore.setUpdateTime(new Date());
                gxtCoefficientScoreMapper.updateGxtCoefficientScore(coefficientScore);
                monthScoreLog.setExplainCode(coefficientScore.getExplainCode());
                monthScoreLog.setFeedbackStatus(coefficientScore.getStatus());
            }
            monthScoreLog.setMonthScoreId(monthScore.getId());
            monthScoreLog.setOperator(SecurityUtils.getUserId());
            monthScoreLog.setPresentStatus(monthScore.getStatus());
            monthScoreLog.setPreviousStatus(monthScore.getPreviousStatus());
            monthScoreLog.setMonthPeriod(monthScore.getMonthPeriod());
            monthScoreLog.setDeptId(monthScore.getDeptId());
            monthScoreLog.setCreateBy(SecurityUtils.getUsername());
            monthScoreLog.setCreateTime(new Date());
            monthScoreLog.setFeedbackContent(monthScore.getFeedbackContent());
            gxtMonthScoreLogMapper.insertGxtMonthScoreLog(monthScoreLog);
        }
    }

    /**
     * 查询月度统计表列表
     * 
     * @param gxtMonthScore 月度统计表
     * @return 月度统计表
     */
    @Override
    public List<GxtMonthScore> selectGxtMonthScoreList(GxtMonthScore gxtMonthScore)
    {
        return gxtMonthScoreMapper.selectGxtMonthScoreList(gxtMonthScore);
    }

    /**
     * 新增月度统计表
     * 
     * @param gxtMonthScore 月度统计表
     * @return 结果
     */
    @Override
    public int insertGxtMonthScore(GxtMonthScore gxtMonthScore)
    {
        return gxtMonthScoreMapper.insertGxtMonthScore(gxtMonthScore);
    }

    /**
     * 修改月度统计表
     * 
     * @param gxtMonthScore 月度统计表
     * @return 结果
     */
    @Override
    public int updateGxtMonthScore(GxtMonthScore gxtMonthScore)
    {
        return gxtMonthScoreMapper.updateGxtMonthScore(gxtMonthScore);
    }

    /**
     * 批量删除月度统计表
     * 
     * @param ids 需要删除的月度统计表主键
     * @return 结果
     */
    @Override
    public int deleteGxtMonthScoreByIds(Long[] ids)
    {
        return gxtMonthScoreMapper.deleteGxtMonthScoreByIds(ids);
    }

    /**
     * 删除月度统计表信息
     * 
     * @param id 月度统计表主键
     * @return 结果
     */
    @Override
    public int deleteGxtMonthScoreById(Long id)
    {
        return gxtMonthScoreMapper.deleteGxtMonthScoreById(id);
    }

    public void generateAllSummary() {

    }
}