package com.gyee.wisdom.alarm.sharding.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gyee.wisdom.alarm.sharding.config.ConfigProperties;
import com.gyee.wisdom.alarm.sharding.entity.FaultHistory;
import com.gyee.wisdom.alarm.sharding.entity.FaultInfo;
import com.gyee.wisdom.alarm.sharding.entity.FaultSnap;
import com.gyee.wisdom.alarm.sharding.mapper.FaultHisotryMapper;
import com.gyee.wisdom.alarm.sharding.mapper.FaultInfoMapper;
import com.gyee.wisdom.alarm.sharding.mapper.FaultSnapMapper;
import com.gyee.wisdom.alarm.sharding.util.SnowflakeGenerator;
import com.gyee.wisdom.common.utils.DateUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @descrition:
 * @author:Wanghs
 * @date:2020-06-10
 */
@Service
public class FaultInfoService {

    Logger logger = LogManager.getLogger(FaultInfoService.class);

    @Autowired
    private FaultInfoMapper faultInfoMapper;

    @Autowired
    private ConfigProperties configProperties;

    @Autowired
    private FaultHisotryMapper faultHisotryMapper;

    @Autowired
    private FaultSnapMapper faultSnapMapper;


    public List<FaultInfo> queryFaultInfo(String stationId, String keyword, String startTime, String endTime, Integer messageType) throws Exception {
        if (keyword != null && keyword.trim() != "")
            keyword = "%" + keyword.trim() + "%";
        startTime = startTime.trim();
        endTime = endTime.trim();
        Date dtStart = null;
        Date dtEnd = null;
        if (startTime != null && startTime != "") {
            if (startTime.length() < 19)
                dtStart = DateUtil.parseDate(startTime);
            else
                dtStart = DateUtil.parseDate1(startTime);
        }
        if (endTime != null && endTime != "") {
            if (endTime.length() < 19)
                dtEnd = DateUtil.parseDate(endTime);
            else
                dtEnd = DateUtil.parseDate1(endTime);
        }


        if (dtStart == null || dtEnd == null)
            return null;

        if (dtEnd.before(dtStart) || dtEnd.before(configProperties.getSetupDate()))
            return null;

        if (dtStart.before(configProperties.getSetupDate()))
            dtStart = configProperties.getSetupDate();

        Date dtNow = new Date();
        if (dtStart.after(dtNow))
            return null;

        if (dtEnd.after(dtNow))
            dtEnd = dtNow;

        if (null != keyword && keyword.equals("%tomis%")) {

            return faultInfoMapper.queryFaultInfo(stationId, "", dtStart, dtEnd, messageType, "123");
        } else {
            return faultInfoMapper.queryFaultInfo(stationId, keyword, dtStart, dtEnd, messageType, "");

        }
    }

    public List<FaultSnap> queryByTimeAndStation(String startTime, String endTime, String stationId) {

        Date dtStart = DateUtil.parseDate(startTime);
        Date dtEnd = DateUtil.parseDate(endTime);
        return faultSnapMapper.queryByTimeAndStation(dtStart, dtEnd, stationId);
    }


    public IPage<FaultInfo> queryFaultInfo(Page page, String stationId, String keyword,String cateGory1, String startTime, String endTime, Integer isOpened) throws Exception {
        if (keyword != null && keyword.trim() != "")
            keyword = "%" + keyword.trim() + "%";
        startTime = startTime.trim();
        endTime = endTime.trim();
        Date dtStart = null;
        Date dtEnd = null;
        if (startTime != null && startTime != "") {
            if (startTime.length() < 19)
                dtStart = DateUtil.parseDate(startTime);
            else
                dtStart = DateUtil.parseDate1(startTime);
        }
        if (endTime != null && endTime != "") {
            if (endTime.length() < 19)
                dtEnd = DateUtil.parseDate(endTime);
            else
                dtEnd = DateUtil.parseDate1(endTime);
        }


        if (dtStart == null || dtEnd == null)
            return null;

        if (dtEnd.before(dtStart) || dtEnd.before(configProperties.getSetupDate()))
            return null;

        if (dtStart.before(configProperties.getSetupDate()))
            dtStart = configProperties.getSetupDate();

        Date dtNow = new Date();
        if (dtStart.after(dtNow))
            return null;

        if (dtEnd.after(dtNow))
            dtEnd = dtNow;

        return faultInfoMapper.queryFaultInfo1(page, stationId, keyword,cateGory1, dtStart, dtEnd, isOpened);
    }

    public List<FaultInfo> getRecentFault(String faultTime) {
        faultTime = faultTime.trim();

        Date dtFault = null;
        if (faultTime != null && faultTime != "") {
            if (faultTime.length() < 19)
                dtFault = DateUtil.parseDate(faultTime);
            else
                dtFault = DateUtil.parseDate1(faultTime);
        }

        if (dtFault == null)
            return null;

        return faultInfoMapper.getRecentFault(dtFault);
    }


    public List<FaultInfo> getTopNumFault(String topNum) throws Exception {
        topNum = topNum.trim();

        int num = Integer.parseInt(topNum);
        if (num < 1)
            return null;
        if (num > 2000)
            num = 2000;

        return faultInfoMapper.getTopNumFault(num);
    }


    public void saveFaultHistory(FaultHistory faultHistory) throws Exception {
        int code;
//        if (faultHistory.getId() == null || faultHistory.getId() <= 0) {
//            faultHistory.setId(SnowflakeGenerator.generateId());
//            code = faultHisotryMapper.insert(faultHistory);
//        } else
        code = faultHisotryMapper.updateHistoryById(faultHistory);
        logger.info("数据库操作状态:{}", code > 0 ? "Y" : "N");
    }


    public FaultHistory queryFaultHistoryById(Long historyId) throws Exception {
        return faultHisotryMapper.queryFaultHistoryById(historyId);
    }


    public List<FaultSnap> queryMultiFaultSnap(String snapIds) throws Exception {
        snapIds = snapIds.trim();
        if (snapIds == "")
            return null;

//        String ids = "'" + snapIds.replace(",", "','") + "'";
        String[] ids = snapIds.split(",");

        return faultSnapMapper.queryMultiFaultSnap(ids);
    }


    public FaultSnap queryByTagId(String tagId) {
        return faultSnapMapper.queryByTagId(tagId);
    }


    public void faultClear(Date startTime, Date endTime) throws Exception {
        faultHisotryMapper.faultClear(startTime, endTime);
    }

    public void confirmBatch(long faultHistoryId, int confirmType, String userName, long alarmSnpaId) throws Exception {
        //根据故障历史id,获取到相应历史数据,并获取faultSnapId,再进行批量确认
        FaultHistory history = faultHisotryMapper.queryFaultHistoryById(faultHistoryId);

        long faultSnapId = history.getSnapId();

        faultHisotryMapper.batchConfirm(faultSnapId, confirmType, userName, alarmSnpaId);

    }


    public void saveFaultSnaps(List<FaultSnap> faultSnaps) {

        if (faultSnaps == null || faultSnaps.size() == 0)
            return;

        List<FaultSnap> insertSnaps = new ArrayList<>();
        List<FaultSnap> updateSnaps = new ArrayList<>();
        List<FaultHistory> faultHistoryList = new ArrayList<>();

        for (FaultSnap snap : faultSnaps) {
            if (snap.getId() == null || snap.getId() <= 0) {
                snap.setId(SnowflakeGenerator.generateId());
                insertSnaps.add(snap);
            } else {
                updateSnaps.add(snap);
            }

            FaultHistory his = createFaultHistory(snap);
            faultHistoryList.add(his);
        }

        if (insertSnaps.size() > 0)
            faultSnapMapper.batchInsert(insertSnaps);

        if (updateSnaps.size() > 0)
            faultSnapMapper.batchUpdate(updateSnaps);

        if (faultHistoryList.size() > 0)
            faultHisotryMapper.batchInsert(faultHistoryList);

    }


    public FaultHistory createFaultHistory(FaultSnap snap) {
        FaultHistory result = new FaultHistory();
        result.setId(SnowflakeGenerator.generateId());
        result.setSnapId(snap.getId());
        result.setFaultTime(snap.getLastUpdateTime());
        result.setConfirmType(0);
        result.setAlertSnapId(snap.getAlarmSnapId());

        if (snap.getIsOpened() != 0)
            result.setMessageType(1);
        else
            result.setMessageType(3);

        return result;
    }

    /**
     * 根据Id获取报警信息
     */
    public List<FaultInfo> getFaultInfoById(String[] ids) {
        return faultInfoMapper.getFaultInfoByIds(ids);
    }
}