package com.goomood.phm.service.impl;

import com.goomood.common.exception.ServiceException;
import com.goomood.common.utils.DateUtils;
import com.goomood.common.utils.StringUtils;
import com.goomood.common.utils.bean.BeanUtils;
import com.goomood.common.utils.bean.BeanValidators;
import com.goomood.phm.domain.FaultMonitor;
import com.goomood.phm.domain.FaultRecord;
import com.goomood.phm.mapper.FaultMonitorMapper;
import com.goomood.phm.service.IFaultMonitorService;
import com.goomood.phm.service.IFaultRecordService;
import com.goomood.phm.utils.PhmConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 故障监控Service业务层处理
 * 
 * @author goomood
 * @date 2024-11-17
 */
@Service
public class FaultMonitorServiceImpl implements IFaultMonitorService {
    @Autowired
    private FaultMonitorMapper faultMonitorMapper;

    @Autowired
    private IFaultRecordService faultRecordService;


    @Autowired
    protected Validator validator;

    /**
     * 查询故障监控
     *
     * @param id 故障监控主键
     * @return 故障监控
     */
    @Override
    public FaultMonitor selectFaultMonitorById(Long id) {
        return faultMonitorMapper.selectFaultMonitorById(id);
    }

    /**
     * 查询故障监控列表
     *
     * @param faultMonitor 故障监控
     * @return 故障监控
     */
    @Override
    public List<FaultMonitor> selectFaultMonitorList(FaultMonitor faultMonitor) {
        return faultMonitorMapper.selectFaultMonitorList(faultMonitor);
    }

    /**
     * 新增故障监控
     *
     * @param faultMonitor 故障监控
     * @return 结果
     */
    @Override
    @Transactional(readOnly = false)
    public int insertFaultMonitor(FaultMonitor faultMonitor) {
        faultMonitor.setCreateTime(DateUtils.getNowDate());
        int res = faultMonitorMapper.insertFaultMonitor(faultMonitor);
        saveFaultRecord(faultMonitor);
        return res;
    }

    /**
     * 修改故障监控
     *
     * @param faultMonitor 故障监控
     * @return 结果
     */
    @Override
    @Transactional(readOnly = false)
    public int updateFaultMonitor(FaultMonitor faultMonitor) {
        faultMonitor.setUpdateTime(DateUtils.getNowDate());
        int res = faultMonitorMapper.updateFaultMonitor(faultMonitor);
        FaultMonitor entity = this.selectFaultMonitorById(faultMonitor.getId());
        saveFaultRecord(entity);
        return res;
    }

    /**
     * 批量删除故障监控
     *
     * @param ids 需要删除的故障监控主键
     * @return 结果
     */
    @Override
    public int deleteFaultMonitorByIds(Long[] ids) {
        return faultMonitorMapper.deleteFaultMonitorByIds(ids);
    }

    /**
     * 删除故障监控信息
     *
     * @param id 故障监控主键
     * @return 结果
     */
    @Override
    public int deleteFaultMonitorById(Long id) {
        return faultMonitorMapper.deleteFaultMonitorById(id);
    }


    /**
     * 更新故障记录
     *
     * @param faultMonitor
     * @return
     */
    public int saveFaultRecord(FaultMonitor faultMonitor) {
        if (StringUtils.isNotEmpty(faultMonitor.getStatus()) && faultMonitor.getStatus().equals(PhmConstants.FAULT_STATUS_CLOSED)) {
            FaultRecord faultRecord = new FaultRecord();
            BeanUtils.copyProperties(faultMonitor, faultRecord, "id");
            return faultRecordService.insertFaultRecord(faultRecord);
        }
        return 0;
    }


    @Override
    public int getUnprocessedFaultCount() {
        return faultMonitorMapper.countUnprocessedFaults(PhmConstants.FAULT_STATUS_OPEN);
    }


    /**
     * 导入接口
     *
     * @param faultMonitors
     * @return
     */
    @Override
    public String importFaultMonitor(List<FaultMonitor> faultMonitors) {
        if (CollectionUtils.isEmpty(faultMonitors)) {
            throw new ServiceException("导入故障监控数据不能为空！");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (FaultMonitor monitor : faultMonitors) {
            try {
                BeanValidators.validateWithException(validator, monitor);
                monitor.setStatus(PhmConstants.FAULT_STATUS_OPEN);
                this.insertFaultMonitor(monitor);
                successNum++;
                successMsg.append("<br/>" + successNum + "、故障监控 " + monitor.getFaultyPartName() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、故障监控 " + monitor.getFaultyPartName() + " 导入失败：";
                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();
    }
}
