package com.ygtx.gxt.service.impl;

import java.util.List;

import com.ygtx.common.core.domain.entity.SysDept;
import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.utils.DateUtils;
import com.ygtx.system.service.ISysDeptService;
import com.ygtx.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ygtx.gxt.mapper.GxtEquipmentMapper;
import com.ygtx.gxt.domain.GxtEquipment;
import com.ygtx.gxt.service.IGxtEquipmentService;
import com.ygtx.common.utils.StringUtils;
import com.ygtx.common.exception.ServiceException;
import javax.validation.Validator;
import com.ygtx.common.annotation.DataScope;
import com.ygtx.common.core.domain.entity.SysRole;
import com.ygtx.common.core.domain.model.LoginUser;
import com.ygtx.common.utils.SecurityUtils;
import com.ygtx.framework.aspectj.DataScopeAspect;
import java.util.ArrayList;

/**
 * 设备管理Service业务层处理
 * 
 * @author ouyj
 * @date 2025-10-28
 */
@Service
public class GxtEquipmentServiceImpl implements IGxtEquipmentService 
{
    @Autowired
    private GxtEquipmentMapper gxtEquipmentMapper;
    
    @Autowired
    private ISysUserService sysUserService;
    
    @Autowired
    private ISysDeptService sysDeptService;
    
    @Autowired
    protected Validator validator;

    /**
     * 查询设备管理
     * 
     * @param equipmentId 设备管理主键
     * @return 设备管理
     */
    @Override
    public GxtEquipment selectGxtEquipmentByEquipmentId(Long equipmentId)
    {
        return gxtEquipmentMapper.selectGxtEquipmentByEquipmentId(equipmentId);
    }

    /**
     * 查询设备管理列表
     * 
     * @param gxtEquipment 设备管理
     * @return 设备管理
     */
    @Override
    @DataScope(deptAlias = "t", userAlias = "")
    public List<GxtEquipment> selectGxtEquipmentList(GxtEquipment gxtEquipment)
    {
        // 添加业务特定的数据权限过滤
        addBusinessDataScopeFilter(gxtEquipment);
        return gxtEquipmentMapper.selectGxtEquipmentList(gxtEquipment);
    }

    /**
     * 查询所有品牌列表（去重）
     * 
     * @return 品牌列表
     */
    @Override
    public List<String> selectBrandList()
    {
        return gxtEquipmentMapper.selectBrandList();
    }

    /**
     * 根据品牌查询机型列表（去重）
     * 
     * @param brand 品牌
     * @return 机型列表
     */
    @Override
    public List<String> selectModelListByBrand(String brand)
    {
        return gxtEquipmentMapper.selectModelListByBrand(brand);
    }

    /**
     * 根据设备编码查询设备管理
     * 
     * @param equipmentCode 设备编码
     * @return 设备管理
     */
    @Override
    public GxtEquipment selectGxtEquipmentByEquipmentCode(String equipmentCode)
    {
        return gxtEquipmentMapper.selectGxtEquipmentByEquipmentCode(equipmentCode);
    }

    /**
     * 根据设备编码、维保中心和场站查询设备管理
     * 
     * @param equipment 设备信息
     * @return 设备管理
     */
    @Override
    public GxtEquipment selectGxtEquipmentByCodeAndLocation(GxtEquipment equipment)
    {
        return gxtEquipmentMapper.selectGxtEquipmentByCodeAndLocation(equipment);
    }

    /**
     * 新增设备管理
     * 
     * @param gxtEquipment 设备管理
     * @return 结果
     */
    @Override
    public int insertGxtEquipment(GxtEquipment gxtEquipment)
    {
        // 验证是否存在相同的设备（根据风机编号、维保中心和场站判断唯一性）
        GxtEquipment existingEquipment = gxtEquipmentMapper.selectGxtEquipmentByCodeAndLocation(gxtEquipment);
        if (existingEquipment != null) {
            throw new ServiceException("设备已存在：风机编号 " + gxtEquipment.getEquipmentCode() 
                + " 在维保中心[" + gxtEquipment.getMaintenanceCenter() + "]场站[" + gxtEquipment.getStation() + "]已存在");
        }
        
        gxtEquipment.setCreateTime(DateUtils.getNowDate());
        return gxtEquipmentMapper.insertGxtEquipment(gxtEquipment);
    }

    /**
     * 修改设备管理
     * 
     * @param gxtEquipment 设备管理
     * @return 结果
     */
    @Override
    public int updateGxtEquipment(GxtEquipment gxtEquipment)
    {
        // 验证是否存在相同的设备（根据风机编号、维保中心和场站判断唯一性），但排除当前设备本身
        GxtEquipment existingEquipment = gxtEquipmentMapper.selectGxtEquipmentByCodeAndLocation(gxtEquipment);
        if (existingEquipment != null && !existingEquipment.getEquipmentId().equals(gxtEquipment.getEquipmentId())) {
            throw new ServiceException("设备已存在：风机编号 " + gxtEquipment.getEquipmentCode() 
                + " 在维保中心[" + gxtEquipment.getMaintenanceCenter() + "]场站[" + gxtEquipment.getStation() + "]已存在");
        }
        
        gxtEquipment.setUpdateTime(DateUtils.getNowDate());
        return gxtEquipmentMapper.updateGxtEquipment(gxtEquipment);
    }

    /**
     * 批量删除设备管理
     * 
     * @param equipmentIds 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteGxtEquipmentByEquipmentIds(Long[] equipmentIds)
    {
        return gxtEquipmentMapper.deleteGxtEquipmentByEquipmentIds(equipmentIds);
    }

    /**
     * 删除设备管理信息
     * 
     * @param equipmentId 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteGxtEquipmentByEquipmentId(Long equipmentId)
    {
        return gxtEquipmentMapper.deleteGxtEquipmentByEquipmentId(equipmentId);
    }

    /**
     * 查询所有维保中心列表（去重）
     *
     * @return 维保中心列表
     */
    @Override
    public List<String> selectMaintenanceCenterList()
    {
        return gxtEquipmentMapper.selectMaintenanceCenterList();
    }

    /**
     * 根据维保中心查询场站列表（去重）
     *
     * @param maintenanceCenter 维保中心
     * @return 场站列表
     */
    @Override
    public List<String> selectStationListByMaintenanceCenter(String maintenanceCenter)
    {
        return gxtEquipmentMapper.selectStationListByMaintenanceCenter(maintenanceCenter);
    }

    /**
     * 查询所有机型列表（去重）
     * 
     * @return 机型列表
     */
    @Override
    public List<String> selectAllModels()
    {
        return gxtEquipmentMapper.selectAllModels();
    }

    /**
     * 导入设备管理数据
     * 
     * @param equipmentList 设备管理数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importGxtEquipment(List<GxtEquipment> equipmentList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(equipmentList) || equipmentList.size() == 0)
        {
            throw new ServiceException("导入设备数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 1;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (GxtEquipment equipment : equipmentList)
        {
            try
            {
                row++;
                if (StringUtils.isEmpty(equipment.getEquipmentCode())) {
                    throw new ServiceException("第" + row + "行风机编号不能为空！");
                }
                if (StringUtils.isEmpty(equipment.getMaintenanceCenter())) {
                    throw new ServiceException("第" + row + "行维保中心不能为空！");
                }
                if (StringUtils.isEmpty(equipment.getStation())) {
                    throw new ServiceException("第" + row + "行场站不能为空！");
                }
                if (StringUtils.isEmpty(equipment.getBrand())) {
                    throw new ServiceException("第" + row + "行品牌不能为空！");
                }
                if (StringUtils.isEmpty(equipment.getModel())) {
                    throw new ServiceException("第" + row + "行机型不能为空！");
                }
                
                // 处理维保中心和场站的部门ID
                processDeptInfo(equipment);
                if (equipment.getMaintenanceCenterId() == null) {
                    throw new ServiceException("第" + row + "行找不到匹配的维保中心部门！");
                }
                if (equipment.getStationId() == null) {
                    throw new ServiceException("第" + row + "行找不到匹配的设备场站部门！");
                }
                // 处理责任人信息
                processResponsiblePerson(equipment);
                
                // 验证是否存在这个设备（根据风机编号、维保中心和场站判断唯一性）
                GxtEquipment e = gxtEquipmentMapper.selectGxtEquipmentByCodeAndLocation(equipment);
                if (StringUtils.isNull(e))
                {
                    equipment.setCreateBy(operName);
                    equipment.setCreateTime(DateUtils.getNowDate());
                    gxtEquipmentMapper.insertGxtEquipment(equipment);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、风机编号 " + equipment.getEquipmentCode() + " 导入成功");

                }
                else if (isUpdateSupport)
                {
                    equipment.setEquipmentId(e.getEquipmentId());
                    equipment.setUpdateBy(operName);
                    equipment.setUpdateTime(DateUtils.getNowDate());
                    gxtEquipmentMapper.updateGxtEquipment(equipment);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、风机编号 " + equipment.getEquipmentCode() + " 更新成功");

                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、风机编号 " + equipment.getEquipmentCode() 
                        + " 在维保中心[" + equipment.getMaintenanceCenter() + "]场站[" + equipment.getStation() + "]已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、风机编号 " + equipment.getEquipmentCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    
    /**
     * 处理设备责任人信息
     * 根据责任人姓名查找系统用户，如果找到唯一用户则设置责任人ID
     * 
     * @param equipment 设备对象
     */
    private void processResponsiblePerson(GxtEquipment equipment) {
        // 如果责任人姓名不为空，则尝试查找对应的用户
        if (StringUtils.isNotEmpty(equipment.getResponsiblePersonName())) {
            List<SysUser> users = sysUserService.selectUserByNickName(equipment.getResponsiblePersonName());
            // 如果只找到一个用户，则设置责任人ID
            if (users != null && users.size() == 1) {
                equipment.setResponsiblePersonId(users.get(0).getUserId());
            }
            // 如果找到多个用户或未找到用户，则不设置责任人ID，保持原值
        }
    }
    
    /**
     * 处理维保中心和场站的部门ID信息
     * 根据维保中心和场站名称查找对应的部门信息
     * 
     * @param equipment 设备对象
     */
    private void processDeptInfo(GxtEquipment equipment) {
        // 处理维保中心ID
        if (StringUtils.isNotEmpty(equipment.getMaintenanceCenter())) {
            SysDept dept = new SysDept();
            dept.setDeptNameNoLike(equipment.getMaintenanceCenter());
            dept.setLevel("2"); // 维保中心层级为2
            List<SysDept> depts = sysDeptService.selectDeptList(dept);
            // 如果只找到一个维保中心，则设置维保中心ID
            if (depts != null && depts.size() == 1) {
                equipment.setMaintenanceCenterId(depts.get(0).getDeptId());
            }
        }
        
        // 处理场站ID
        if (StringUtils.isNotEmpty(equipment.getStation())) {
            /*SysDept dept = new SysDept();
            dept.setDeptNameNoLike(equipment.getStation());
            dept.setLevel("3"); // 场站层级为3
            List<SysDept> deptsA = sysDeptService.selectDeptList(dept);
            // 如果只找到一个场站，则设置场站ID
            if (deptsA != null && deptsA.size() == 1) {
                equipment.setStationId(deptsA.get(0).getDeptId());
            }else{
                dept.setDeptNameNoLike(equipment.getStation());
                dept.setLevel("4"); // 场站层级为4
                List<SysDept> deptsB = sysDeptService.selectDeptList(dept);
                if (deptsB != null && deptsB.size() == 1) {
                    equipment.setStationId(deptsB.get(0).getDeptId());
                }
            }*/
            SysDept dept = new SysDept();
            dept.setLevel("4"); // 场站层级为4
            dept.setDeptNameNoLike(equipment.getStation());
            List<SysDept> depts = sysDeptService.selectDeptList(dept);
            // 如果只找到一个场站，则设置场站ID
            if (depts != null && depts.size() == 1) {
                equipment.setStationId(depts.get(0).getDeptId());
            }
        }
    }
    
    /**
     * 添加业务特定的数据权限过滤条件
     * 基于角色的数据范围进行自定义权限控制
     *
     * @param gxtEquipment 设备管理查询条件
     */
    private void addBusinessDataScopeFilter(GxtEquipment gxtEquipment) {
        // 获取当前登录用户
        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;
        }

        // 构建业务特定的数据权限SQL
        StringBuilder businessSql = new StringBuilder();
        
        // 遍历用户角色，根据角色的数据范围添加业务特定的权限控制
        for (SysRole role : roles) {
            String dataScope = role.getDataScope();
            
            // 如果是全部数据权限，则不过滤
            if (DataScopeAspect.DATA_SCOPE_ALL.equals(dataScope)) {
                businessSql.setLength(0); // 清空之前的条件
                break; // 全部数据权限，跳出循环
            }
            
            // 自定义数据权限 - 根据角色的数据范围值来控制查询条件
            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.maintenance_center_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                              .append(String.join(",", customRoleIds))
                              .append("))")
                              .append(" OR t.station_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id IN (")
                              .append(String.join(",", customRoleIds))
                              .append(")))");
                } else {
                    // 单个自定义数据权限角色查询
                    businessSql.append("(t.maintenance_center_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ")
                              .append(role.getRoleId())
                              .append(")")
                              .append(" OR t.station_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.station_id = ")
                          .append(currentUser.getDeptId())
                          .append(" OR t.maintenance_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.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.maintenance_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.responsible_person_id = ")
                        .append(currentUser.getUserId())
                        .append(" OR t.create_by = '")
                        .append(currentUser.getUserName())
                        .append("')");
                continue;
            }
        }

        // 如果构建了业务特定的过滤条件，则添加到查询参数中
        if (businessSql.length() > 0) {
            String businessDataScopeSql = " AND (" + businessSql.toString() + ")";
            gxtEquipment.getParams().put("businessDataScope", businessDataScopeSql);
        }
    }
}