 package com.huatek.busi.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.huatek.busi.service.generatro.BusiOfflineGeneratorRepairService;
import com.huatek.busi.vo.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huatek.busi.common.BusiConstant.DealStatus;
import com.huatek.busi.common.BusiConstant.EqType;
import com.huatek.busi.common.BusiConstant.WarningType;
import com.huatek.busi.common.SiteConstants.SiteTreeEnum;
import com.huatek.busi.common.SiteConstants.Status;
import com.huatek.busi.dao.BusiEqmMalfunctionDao;
import com.huatek.busi.dao.BusiEqmWarningDao;
import com.huatek.busi.dto.BusiEqmMalfunctionDto;
import com.huatek.busi.entity.BusiEqmMalfunction;
import com.huatek.busi.entity.BusiEqmWarning;
import com.huatek.busi.entity.BusiExternalEquipment;
import com.huatek.busi.entity.BusiSiteTree;
import com.huatek.busi.mapper.BusiEqmMalfunctionMapper;
import com.huatek.busi.service.BusiEqmMalfunctionService;
import com.huatek.busi.service.BusiEqmWarningService;
import com.huatek.busi.service.BusiExternalEquipmentService;
import com.huatek.busi.service.BusiSensorService;
import com.huatek.busi.service.BusiSiteTreeService;
import com.huatek.busi.service.Other.BusiOfflineOtherRepairService;
import com.huatek.busi.service.arrester.BusiOfflineArresterBrandService;
import com.huatek.busi.service.arrester.BusiOfflineArresterRepairService;
import com.huatek.busi.service.gis.BusiOfflineGisBrandService;
import com.huatek.busi.service.gis.BusiOfflineGisRepairService;
import com.huatek.busi.service.transformer.BusiOfflineTransformerBrandService;
import com.huatek.busi.service.transformer.BusiOfflineTransformerRepairService;
import com.huatek.frame.base.util.BeanUtils;
import com.huatek.torch.sql.beans.LocalUser;
import com.huatek.torch.util.tools.UserUtil;
import com.huatek.torch.util.uuid.Uuid;

import lombok.extern.slf4j.Slf4j;

/**
 * 故障单
 * @author buck_guo
 * @date 2019/09/17
 */
@Slf4j
@Component
@Service(interfaceClass = BusiEqmMalfunctionService.class)
@Transactional(rollbackFor = Exception.class)
public class BusiEqmMalfunctionServiceImpl implements BusiEqmMalfunctionService {
    @Autowired
    private BusiEqmMalfunctionMapper busiEqmMalfunctionMapper;
    @Autowired
    private BusiEqmMalfunctionDao busiEqmMalfunctionDao;
    @Autowired
    private BusiOfflineTransformerRepairService busiOfflineTransformerRepairService;
    @Autowired
    private BusiOfflineGisRepairService busiOfflineGisRepairService;
    @Autowired
    private BusiOfflineArresterRepairService busiOfflineArresterRepairService;
    @Autowired
    private BusiOfflineOtherRepairService busiOfflineOtherRepairService;
    @Autowired
    private BusiSiteTreeService busiSiteTreeService;
    @Autowired
    private BusiSensorService busiSensorService;
    @Autowired
    private BusiExternalEquipmentService busiExternalEquipmentService;
    @Autowired
    private BusiOfflineTransformerBrandService busiOfflineTransformerBrandService;
    @Autowired
    private BusiOfflineGisBrandService busiOfflineGisBrandService;
    @Autowired
    private BusiOfflineArresterBrandService busiOfflineArresterBrandService;
    @Reference(check = false)
    private BusiEqmWarningService busiEqmWarningService;
    @Autowired
    private BusiEqmWarningDao busiEqmWarningDao;
    @Autowired
    private BusiOfflineGeneratorRepairService busiOfflineGeneratorRepairService;
    
    @Override
    public PageInfo<BusiEqmMalfunctionVo> selectBusiEqmMalfunctionPage(BusiEqmMalfunctionDto busiEqmMalfunctionDto) {
        return PageHelper.startPage(busiEqmMalfunctionDto.getPage(), busiEqmMalfunctionDto.getLimit())
            .doSelectPageInfo(() -> busiEqmMalfunctionMapper.selectBusiEqmMalfunctionPage(busiEqmMalfunctionDto));
    }
    
    
    @Override
    public void doDeal(String token, List<String> warningIds, String dealMsg) {
        if(CollectionUtils.isEmpty(warningIds)) {
            return;
        }
        LocalUser user = UserUtil.getLocalUser(token);
        for(String warningId : warningIds) {
            String dealStatus = busiEqmMalfunctionMapper.lockDealStatus(warningId);
            if(DealStatus.DEALED.equals(dealStatus)) {
                log.warn("已处理：{}", warningId);
                continue;
            }
            BusiEqmMalfunction busiEqmMalfunction = busiEqmMalfunctionDao.get(warningId);
            if(busiEqmMalfunction == null) {
                log.debug("故障信息不存在！ ID：{}", warningId);
                continue ;
            }
            busiEqmMalfunction.setDealStatus(DealStatus.DEALED);
            busiEqmMalfunction.setDealMsg(dealMsg);
            busiEqmMalfunction.setProcessingTime(LocalDateTime.now());
            if(user != null) {
                busiEqmMalfunction.setProcessingUser(user.getUid());
            }
            busiEqmMalfunctionDao.updateLocal(busiEqmMalfunction);
            //油色谱三比值需要同步出来告警单
            if(StringUtils.isNotEmpty(busiEqmMalfunction.getWarningId()) && StringUtils.isNotEmpty(busiEqmMalfunction.getThreeRatio())) {
            	 BusiEqmWarning busiEqmWarning = busiEqmWarningDao.get(busiEqmMalfunction.getWarningId());
            	if (ObjectUtils.isNotEmpty(busiEqmWarning)) {
            		if (busiEqmWarning.getDealStatus().equals(DealStatus.TO_DEAL)) {
                        busiEqmWarning.setDealStatus(DealStatus.DEALED);
                        busiEqmWarning.setDealMsg(dealMsg);
                        busiEqmWarning.setWarningType(WarningType.FAULT);
                        busiEqmWarning.setProcessingTime(LocalDateTime.now());
                        if(user != null) {
                            busiEqmWarning.setProcessingUser(user.getUid());
                        }
                        busiEqmWarningDao.updateLocal(busiEqmWarning);
            		}
            	}
            }
        }
    }


    @Override
    public void toRepair(String token, List<String> warningIds, String dealMsg) {
        if(CollectionUtils.isEmpty(warningIds)) {
            return;
        }
        LocalUser user = UserUtil.getLocalUser(token);
        for(String warningId : warningIds) {
            BusiEqmMalfunction busiEqmMalfunction = busiEqmMalfunctionDao.get(warningId);
            if(busiEqmMalfunction == null) {
                log.debug("故障信息不存在！ ID：{}", warningId);
                continue ;
            }
            //处理故障单
            busiEqmMalfunction.setDealStatus(DealStatus.DEALED);
            busiEqmMalfunction.setDealMsg(dealMsg);
            busiEqmMalfunction.setProcessingTime(LocalDateTime.now());
            if(user != null) {
                busiEqmMalfunction.setProcessingUser(user.getUid());
            }
            busiEqmMalfunction.setProcessingTime(LocalDateTime.now());
            busiEqmMalfunctionDao.updateLocal(busiEqmMalfunction);
            //带三比值油色谱告警同步处理
            //油色谱三比值需要同步出来告警单
            if(StringUtils.isNotEmpty(busiEqmMalfunction.getWarningId()) && StringUtils.isNotEmpty(busiEqmMalfunction.getThreeRatio())) {
            	 BusiEqmWarning busiEqmWarning = busiEqmWarningDao.get(busiEqmMalfunction.getWarningId());
            	if (ObjectUtils.isNotEmpty(busiEqmWarning)) {
            		if (busiEqmWarning.getDealStatus().equals(DealStatus.TO_DEAL)) {
                        busiEqmWarning.setDealStatus(DealStatus.DEALED);
                        busiEqmWarning.setDealMsg(dealMsg);
                        busiEqmWarning.setWarningType(WarningType.FAULT);
                        busiEqmWarning.setProcessingTime(LocalDateTime.now());
                        if(user != null) {
                            busiEqmWarning.setProcessingUser(user.getUid());
                        }
                        busiEqmWarningDao.updateLocal(busiEqmWarning);
            		}
            	}
            }
            //转检修
            if(EqType.EQ_TYPE1.equals(busiEqmMalfunction.getEqType())) {
                busiOfflineTransformerRepairService.toRepair(token, busiEqmMalfunction);
            }else if(EqType.EQ_TYPE2.equals(busiEqmMalfunction.getEqType())) {
                busiOfflineGisRepairService.toRepair(token, busiEqmMalfunction);
            }else if(EqType.EQ_TYPE3.equals(busiEqmMalfunction.getEqType())) {
                busiOfflineArresterRepairService.toRepair(token, busiEqmMalfunction);
            }else if(EqType.EQ_TYPE5.equals(busiEqmMalfunction.getEqType())) {
            	busiOfflineOtherRepairService.toRepair(token, busiEqmMalfunction);
            }else if(EqType.EQ_TYPE6.equals(busiEqmMalfunction.getEqType())) {
                busiOfflineGeneratorRepairService.toRepair(token, busiEqmMalfunction);
            }else {
                log.warn("故障转检修单！告警：{}，大类：{}", warningId, busiEqmMalfunction.getEqType());
            }
        }
    }

    @Override
    public void warningToMalfunction(String token, BusiEqmWarning busiEqmWarning,String malfunctionSource) {
        BusiEqmMalfunction busiEqmMalfunction =  new BusiEqmMalfunction();
        busiEqmMalfunction.setId(Uuid.getUUID());
        busiEqmMalfunction.setWarningId(busiEqmWarning.getId());
        busiEqmMalfunction.setSensorId(busiEqmWarning.getSensorId());
        busiEqmMalfunction.setSiteId(busiEqmWarning.getSiteId());
        busiEqmMalfunction.setEqType(busiEqmWarning.getEqType());
        busiEqmMalfunction.setGzType(busiEqmWarning.getGzType());
        busiEqmMalfunction.setWarningTypeCode(busiEqmWarning.getWarningTypeCode());
        busiEqmMalfunction.setWarningMsg(busiEqmWarning.getWarningMsg());
        busiEqmMalfunction.setWarningTime(busiEqmWarning.getWarningTime());
        busiEqmMalfunction.setCreateTime(LocalDateTime.now());
        busiEqmMalfunction.setDelFlag(Status.NORMAL.getValue());
        busiEqmMalfunction.setDealStatus(DealStatus.TO_DEAL);
        busiEqmMalfunction.setMalfunctionSource(malfunctionSource);
        busiEqmMalfunction.setSiteId(busiEqmWarning.getSiteId());
        busiEqmMalfunction.setMainEquipmentId(busiEqmWarning.getMainEquipmentId());
        busiEqmMalfunction.setSubEquipmentId(busiEqmWarning.getSubEquipmentId());
        busiEqmMalfunction.setSubEquipmentInstallLocation(busiEqmWarning.getSubEquipmentInstallLocation());
        busiEqmMalfunction.setSubEquipmentBrand(busiEqmWarning.getSubEquipmentBrand());
        busiEqmMalfunction.setSubEquipmentManufactor(busiEqmWarning.getSubEquipmentManufactor());
        busiEqmMalfunction.setSensorBrand(busiEqmWarning.getSensorBrand());
        busiEqmMalfunction.setSensorManufactor(busiEqmWarning.getSensorManufactor());
        busiEqmMalfunction.setSensorInstallLocation(busiEqmWarning.getSensorInstallLocation());
        busiEqmMalfunction.setSubEquipmentName(busiEqmWarning.getSubEquipmentName());
        busiEqmMalfunction.setSensorName(busiEqmWarning.getSensorName());
        busiEqmMalfunction.setSubTreeId(busiEqmWarning.getSubTreeId());
        busiEqmMalfunction.setMainTreeId(busiEqmWarning.getMainTreeId());
        busiEqmMalfunction.setRunState(busiEqmWarning.getRunState());
        //图片类告警没有subTreeId、mainEquipmentId、subEquipmentId
        setSomeIds(busiEqmMalfunction);
        busiEqmMalfunctionDao.add(busiEqmMalfunction);
    }

    private void setSomeIds(BusiEqmMalfunction busiEqmMalfunction) {
        BusiSiteTree busiSiteTree = busiSiteTreeService.findByPK(busiEqmMalfunction.getMainTreeId());
        if(busiSiteTree == null) {
            return ;
        }
        SiteTreeEnum siteTreeEnum = null;
        String mainEquipmentId = null;
        if (SiteTreeEnum.BYQ_EQM.getValue().equals(busiSiteTree.getEquipmentType())) {
            siteTreeEnum = SiteTreeEnum.BYQ_EQM;
            BusiOfflineTransformerBrandVo brand = busiOfflineTransformerBrandService.getBusiOfflineTransformerBrandVo(null, busiEqmMalfunction.getMainTreeId());
            if(brand != null) {
                mainEquipmentId = brand.getId();
            }
        } else if (SiteTreeEnum.GIS_HL_EQM.getValue().equals(busiSiteTree.getEquipmentType())) {
            siteTreeEnum = SiteTreeEnum.GIS_HL_EQM;
            BusiOfflineGisBrandVo brand = busiOfflineGisBrandService.findBusiOfflineGISBrand(null, busiEqmMalfunction.getMainTreeId());
            if(brand != null) {
                mainEquipmentId = brand.getId();
            }
        } else if (SiteTreeEnum.BLQ_HL_EQM.getValue().equals(busiSiteTree.getEquipmentType())) {
            siteTreeEnum = SiteTreeEnum.BLQ_HL_EQM;
            BusiOfflineArresterBrandVo brand = busiOfflineArresterBrandService.getBusiOfflineArresterBrandInfo(null, busiEqmMalfunction.getMainTreeId());
            if(brand != null) {
                mainEquipmentId = brand.getId();
            }
        }
        if(StringUtils.isEmpty(busiEqmMalfunction.getMainEquipmentId()) 
            && !StringUtils.isEmpty(mainEquipmentId)) {
            busiEqmMalfunction.setMainEquipmentId(mainEquipmentId);
        }
        if(siteTreeEnum == null) {
            return ;
        }
        if(StringUtils.isEmpty(busiEqmMalfunction.getSubTreeId())) {
            BusiSensorVo busiSensorVo = busiSensorService.getBusiSensorVo(siteTreeEnum, busiEqmMalfunction.getSensorId());
            if(busiSensorVo == null) {
                return ;
            }
            busiEqmMalfunction.setSubTreeId(busiSensorVo.getSubTreeId());
            if(StringUtils.isEmpty(busiEqmMalfunction.getSubEquipmentId())) {
                BusiExternalEquipment ext = busiExternalEquipmentService.getByEquipmentId(busiSensorVo.getSubTreeId());
                if(ext != null) {
                    busiEqmMalfunction.setSubEquipmentId(ext.getId());
                }
            }
        }
    }

    @Override
    public int saveBusiEqmMalfunction(String token, BusiEqmMalfunctionDto busiEqmMalfunctionDto) {
        BusiEqmMalfunction busiEqmMalfunction = new BusiEqmMalfunction();
        BeanUtils.copyPropertiesWithIgnoreNull(busiEqmMalfunctionDto, busiEqmMalfunction);
        LocalUser user = UserUtil.getLocalUser(token);
        busiEqmMalfunction.setCreateTime(LocalDateTime.now());
        busiEqmMalfunction.setId(Uuid.getUUID());
        if (user != null) {            
            busiEqmMalfunction.setCreateName(user.getUserName());
            busiEqmMalfunction.setCreateUser(user.getUid());
        }
        return busiEqmMalfunctionDao.add(busiEqmMalfunction);
    }

    @Override
    public List<BusiEqmMalfunction> isFinishedOverhaul(List<String> malfunctionIds) {
        List<BusiEqmMalfunction> list = new ArrayList<BusiEqmMalfunction>();
        if(CollectionUtils.isEmpty(malfunctionIds)) {
            return list;
        }
        else
        {
            for(String malfunctionId : malfunctionIds) {
                //根据故障ID查询故障信息
                BusiEqmMalfunction busiEqmMalfunction = busiEqmMalfunctionDao.get(malfunctionId);
                if(busiEqmMalfunction != null) 
                {
                    if(EqType.EQ_TYPE1.equals(busiEqmMalfunction.getEqType())) {
                        BusiOfflineTransformerRepairVo obj = busiOfflineTransformerRepairService.isFinishedOverhaul(malfunctionId);
                        if(obj!=null)
                        {
                            list.add(busiEqmMalfunctionDao.get(malfunctionId));
                        }
                    }else if(EqType.EQ_TYPE2.equals(busiEqmMalfunction.getEqType())) {
                        BusiOfflineGisRepairVo obj = busiOfflineGisRepairService.isFinishedOverhaul(malfunctionId);
                        if(obj!=null)
                        {
                            list.add(busiEqmMalfunctionDao.get(malfunctionId));
                        }
                    }else if(EqType.EQ_TYPE3.equals(busiEqmMalfunction.getEqType())) {
                        BusiOfflineArresterRepairVo obj = busiOfflineArresterRepairService.isFinishedOverhaul(malfunctionId);
                        if(obj!=null)
                        {
                            list.add(busiEqmMalfunctionDao.get(malfunctionId));
                        }
                    } else if(EqType.EQ_TYPE6.equals(busiEqmMalfunction.getEqType())) {
                        BusiOfflineGeneratorRepairVo obj = busiOfflineGeneratorRepairService.isFinishedOverhaul(malfunctionId);
                        if(obj!=null)
                        {
                            list.add(busiEqmMalfunctionDao.get(malfunctionId));
                        }
                    }
                }
            }
        }
        return list;
    }


    @Override
    public BusiEqmMalfunctionVo queryUnprocessedEqmMalfunction(String warningId) {
        return busiEqmMalfunctionMapper.queryUnprocessedEqmMalfunction(warningId);
    }


    @Override
    public BusiEqmMalfunctionVo findMalfunctionById(String id) {
         return busiEqmMalfunctionMapper.findMalfunctionById(id);
    }
}
