package com.ygtx.gxt.service.impl;

import java.util.List;
import java.util.ArrayList;

import com.ygtx.common.core.domain.entity.SysDept;
import com.ygtx.common.utils.DateUtils;
import com.ygtx.common.utils.StringUtils;
import com.ygtx.gxt.mapper.GxtEquipmentMapper;
import com.ygtx.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ygtx.gxt.mapper.GxtFaultCodesMapper;
import com.ygtx.gxt.domain.GxtFaultCodes;
import com.ygtx.gxt.service.IGxtFaultCodesService;

/**
 * 故障代码管理Service业务层处理
 *
 * @author ouyj
 * @date 2025-10-29
 */
@Service
public class GxtFaultCodesServiceImpl implements IGxtFaultCodesService
{
    @Autowired
    private GxtFaultCodesMapper gxtFaultCodesMapper;

    @Autowired
    private GxtEquipmentMapper gxtEquipmentMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询故障代码管理
     *
     * @param id 故障代码管理主键
     * @return 故障代码管理
     */
    @Override
    public GxtFaultCodes selectGxtFaultCodesById(Long id)
    {
        return gxtFaultCodesMapper.selectGxtFaultCodesById(id);
    }

    /**
     * 查询故障代码管理列表
     *
     * @param gxtFaultCodes 故障代码管理
     * @return 故障代码管理
     */
    @Override
    public List<GxtFaultCodes> selectGxtFaultCodesList(GxtFaultCodes gxtFaultCodes)
    {
        return gxtFaultCodesMapper.selectGxtFaultCodesList(gxtFaultCodes);
    }

    /**
     * 验证故障代码是否唯一
     *
     * @param gxtFaultCodes 故障代码信息
     * @return 结果
     */
    @Override
    public boolean checkFaultCodeUnique(GxtFaultCodes gxtFaultCodes) {
        if(StringUtils.isNotEmpty(gxtFaultCodes.getFaultCode())){
            Long id = gxtFaultCodes.getId() == null ? -1L : gxtFaultCodes.getId();
            GxtFaultCodes info = gxtFaultCodesMapper.selectGxtFaultCodesByFaultCode(gxtFaultCodes.getFaultCode());
            if (info != null && info.getId().longValue() != id.longValue()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 新增故障代码管理
     *
     * @param gxtFaultCodes 故障代码管理
     * @return 结果
     */
    @Override
    public int insertGxtFaultCodes(GxtFaultCodes gxtFaultCodes)
    {
        gxtFaultCodes.setCreateTime(DateUtils.getNowDate());
        return gxtFaultCodesMapper.insertGxtFaultCodes(gxtFaultCodes);
    }

    /**
     * 修改故障代码管理
     *
     * @param gxtFaultCodes 故障代码管理
     * @return 结果
     */
    @Override
    public int updateGxtFaultCodes(GxtFaultCodes gxtFaultCodes)
    {
        gxtFaultCodes.setUpdateTime(DateUtils.getNowDate());
        return gxtFaultCodesMapper.updateGxtFaultCodes(gxtFaultCodes);
    }

    /**
     * 批量删除故障代码管理
     *
     * @param ids 需要删除的故障代码管理主键
     * @return 结果
     */
    @Override
    public int deleteGxtFaultCodesByIds(Long[] ids)
    {
        return gxtFaultCodesMapper.deleteGxtFaultCodesByIds(ids);
    }

    /**
     * 删除故障代码管理信息
     *
     * @param id 故障代码管理主键
     * @return 结果
     */
    @Override
    public int deleteGxtFaultCodesById(Long id)
    {
        return gxtFaultCodesMapper.deleteGxtFaultCodesById(id);
    }

    /**
     * 根据场站ID查询机型列表（从设备管理中获取）
     *
     * @param stationId 场站ID
     * @return 机型列表
     */
    @Override
    public List<String> selectModelListByStationId(Long stationId)
    {
        return gxtEquipmentMapper.selectModelListByStationId(stationId);
    }

    /**
     * 批量导入故障代码管理数据
     * 
     * @param faultCodesList 故障代码管理数据列表
     * @param updateSupport 是否支持更新
     * @param operName 操作用户
     * @return 导入结果信息
     */
    @Override
    public String importGxtFaultCodes(List<GxtFaultCodes> faultCodesList, Boolean updateSupport, String operName) {
        if (StringUtils.isNull(faultCodesList) || faultCodesList.size() == 0) {
            throw new RuntimeException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 1;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (GxtFaultCodes faultCodes : faultCodesList) {
            try {
                row++;
                // 验证必填字段
                if (StringUtils.isEmpty(faultCodes.getFaultBarcode())) {
                    failureNum++;
                    failureMsg.append("<br/>第" + row + "行故障条文为空");
                    continue;
                }
                if (StringUtils.isEmpty(faultCodes.getStation())) {
                    failureNum++;
                    failureMsg.append("<br/>第" + row + "行场站为空");
                    continue;
                }
                if (StringUtils.isEmpty(faultCodes.getModel())) {
                    failureNum++;
                    failureMsg.append("<br/>第" + row + "行机型为空");
                    continue;
                }

                SysDept dept = new SysDept();
                dept.setDeptNameNoLike(faultCodes.getStation());
                dept.setLevel("4");
                dept.setDelFlag("0");
                List<SysDept> depts = sysDeptService.selectDeptList(dept);
                // 如果只找到一个场站，则设置场站ID
                if (depts != null && depts.size() == 1) {
                    faultCodes.setStationId(depts.get(0).getDeptId());
                }else if(depts != null && depts.size() > 1){
                    failureNum++;
                    failureMsg.append("<br/>第" + row + "行找到多个相同名称的设备场站的部门数据");
                    continue;
                }else {
                    failureNum++;
                    failureMsg.append("<br/>第" + row + "行未找到该设备场站");
                    continue;
                }

                List<String> models = gxtEquipmentMapper.selectModelListByStationId(faultCodes.getStationId());

                if (models != null && !models.isEmpty()) {
                    if (!models.contains(faultCodes.getModel())) {
                        failureNum++;
                        failureMsg.append("<br/>第" + row + "行"+faultCodes.getStation()+"场站中未找到机型"+faultCodes.getModel());
                        continue;
                    }
                }else{
                    failureNum++;
                    failureMsg.append("<br/>第" + row + "行未找到该场站"+faultCodes.getStation()+"的机型数据");
                    continue;
                }
                // 检查是否已存在相同场站、机型、故障条文的组合数据
                GxtFaultCodes faultCodesByCondition = gxtFaultCodesMapper.selectGxtFaultCodesByStationModelBarcode(faultCodes);
                if (faultCodesByCondition == null) {
                    if(!checkGxtFaultCodesByStationModelFaultCode(faultCodes)){
                        failureNum++;
                        failureMsg.append("<br/>第" + row + "行场站、机型、故障代码组合已存在");
                        continue;
                    }
                    // 新增
                    faultCodes.setIsActive(0);
                    faultCodes.setCreateBy(operName);
                    faultCodes.setCreateTime(DateUtils.getNowDate());
                    insertGxtFaultCodes(faultCodes);
                    successNum++;
                } else if (updateSupport) {
                    // 更新
                    faultCodes.setId(faultCodesByCondition.getId());
                    if(!checkGxtFaultCodesByStationModelFaultCode(faultCodes)){
                        failureNum++;
                        failureMsg.append("<br/>第" + row + "行场站、机型、故障代码组合已存在");
                        continue;
                    }
                    faultCodes.setUpdateBy(operName);
                    faultCodes.setUpdateTime(DateUtils.getNowDate());
                    updateGxtFaultCodes(faultCodes);
                    successNum++;
                } else {
                    failureNum++;
                    failureMsg.append("<br/>第" + row + "行场站为 ").append(faultCodes.getStation())
                        .append("，机型为 ").append(faultCodes.getModel())
                        .append("，故障条文为 ").append(faultCodes.getFaultBarcode()).append(" 的数据已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>第" + row + "行场站为 " + faultCodes.getStation()
                    + "，机型为 " + faultCodes.getModel() + "，故障条文为 " + faultCodes.getFaultBarcode() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！导入成功共 " + successNum + " 条，导入失败共 " + failureNum + " 条，错误如下：");
            throw new RuntimeException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
            return successMsg.toString();
        }
    }

    @Override
    public boolean checkGxtFaultCodesByStationModelBarcode(GxtFaultCodes gxtFaultCodes) {
        Long id = gxtFaultCodes.getId() == null ? -1L : gxtFaultCodes.getId();
        GxtFaultCodes info = gxtFaultCodesMapper.selectGxtFaultCodesByStationModelBarcode(gxtFaultCodes);
        if (info != null && info.getId().longValue() != id.longValue()) {
            return false;
        }
        return true;
    }

    @Override
    public boolean checkGxtFaultCodesByStationModelFaultCode(GxtFaultCodes gxtFaultCodes) {
        if(StringUtils.isNotEmpty(gxtFaultCodes.getFaultCode())){
            Long id = gxtFaultCodes.getId() == null ? -1L : gxtFaultCodes.getId();
            GxtFaultCodes info = gxtFaultCodesMapper.selectGxtFaultCodesByStationModelFaultCode(gxtFaultCodes);
            if (info != null && info.getId().longValue() != id.longValue()) {
                return false;
            }
        }
        return true;
    }
}