package com.ygtx.gxt.service.impl;

import java.util.List;
import com.ygtx.common.utils.DateUtils;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ygtx.system.service.ISysUserService;
import com.ygtx.common.core.domain.entity.SysUser;
import java.util.List;

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

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

    /**
     * 查询设备管理列表
     * 
     * @param gxtEquipment 设备管理
     * @return 设备管理
     */
    @Override
    public List<GxtEquipment> selectGxtEquipmentList(GxtEquipment 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)
    {
        // 处理责任人信息
        processResponsiblePerson(gxtEquipment);
        gxtEquipment.setCreateTime(DateUtils.getNowDate());
        return gxtEquipmentMapper.insertGxtEquipment(gxtEquipment);
    }

    /**
     * 修改设备管理
     * 
     * @param gxtEquipment 设备管理
     * @return 结果
     */
    @Override
    public int updateGxtEquipment(GxtEquipment gxtEquipment)
    {
        // 处理责任人信息
        processResponsiblePerson(gxtEquipment);
        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);
    }

    /**
     * 导入设备管理数据
     * 
     * @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;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (GxtEquipment equipment : equipmentList)
        {
            try
            {
                if (StringUtils.isEmpty(equipment.getEquipmentCode())) {
                    throw new ServiceException("风机编号不能为空！");
                }
                if (StringUtils.isEmpty(equipment.getMaintenanceCenter())) {
                    throw new ServiceException("维保中心不能为空！");
                }
                if (StringUtils.isEmpty(equipment.getStation())) {
                    throw new ServiceException("场站不能为空！");
                }
                if (StringUtils.isEmpty(equipment.getBrand())) {
                    throw new ServiceException("品牌不能为空！");
                }
                if (StringUtils.isEmpty(equipment.getModel())) {
                    throw new ServiceException("机型不能为空！");
                }
                
                // 处理责任人信息
                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，保持原值
        }
    }
}