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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gyee.wisdom.alarm.sharding.config.ConfigProperties;
import com.gyee.wisdom.alarm.sharding.entity.AlarmHistory;
import com.gyee.wisdom.alarm.sharding.entity.AlarmSnap;
import com.gyee.wisdom.alarm.sharding.entity.Windturbine;
import com.gyee.wisdom.alarm.sharding.mapper.AlarmHisotryMapper;
import com.gyee.wisdom.alarm.sharding.mapper.MainBrownoutsMapper;
import com.gyee.wisdom.alarm.sharding.mapper.ShutdownEventMapper;
import com.gyee.wisdom.alarm.sharding.mapper.WindturbineMapper;
import com.gyee.wisdom.alarm.sharding.model.AlarmHistoryInfo;
import com.gyee.wisdom.common.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class AlarmHistoryService extends ServiceImpl<AlarmHisotryMapper, AlarmHistory>  {

    @Autowired
    private AlarmHisotryMapper alarmHisotryMapper;

    @Autowired
    private TableNameService tableNameService;

    @Autowired
    private ConfigProperties configProperties;

    @Autowired
    private ShutdownEventMapper shutdownEventMapper;
    @Autowired
    private MainBrownoutsMapper mainBrownoutsMapper;
    @Autowired
    private WindturbineMapper windturbineMapper;

    public Map<String, String> getListmap() {
        return listmap;
    }

    Map<String, String> listmap = null;


    public AlarmHistory queryById(long hisId) {
        return  alarmHisotryMapper.selectById(hisId);
    }

    //todo: 跨表分页bug
    public IPage<AlarmHistoryInfo> pageQueryAll(Page page,
                                                String stationId,
                                                String windturbineId,
                                                String category1,
                                                String category2,
                                                String rank,
                                                String modelid,
                                                Long snapId,
                                                Integer messageType,
                                                String keyword,
                                                String startTime,
                                                String endTime){
        try {

            if (keyword != null && ("").equals(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(StringUtils.isNotBlank(windturbineId)&&StringUtils.isBlank(stationId)){
                Windturbine windturbine = windturbineMapper.selectByPrimaryKey(windturbineId);
                if(windturbine!=null)
                    stationId=windturbine.getWindpowerstationid();
            }

            if (stationId == null || ("").equals(stationId.trim())) {
                String[] stationIds = tableNameService.getStationIds();
                List<String> simpleStationIdList = Arrays.asList(stationIds).stream().map(s -> StringUtils.split(s,"_")[0]).collect(Collectors.toList());
                //多场站查询，由近到远
                List<String> yearMonthList = tableNameService.getYearAndMonthList(dtStart, dtEnd);
                if (yearMonthList != null && yearMonthList.size() > 0) {
                    if (yearMonthList.size() == 1)
                        return alarmHisotryMapper.pageQueryAll2(page, simpleStationIdList,yearMonthList.get(0), stationId, windturbineId, category1, category2,
                                rank, modelid, snapId, messageType, keyword, dtStart, dtEnd);

                    long pageNum = 1;
                    IPage<AlarmHistoryInfo> result = new Page<>(page.getCurrent(), page.getSize());
                    for (String yearMonth : yearMonthList) {
                        IPage<AlarmHistoryInfo> iPage = alarmHisotryMapper.pageQueryAll2(page, simpleStationIdList,yearMonth, stationId, windturbineId, category1, category2,
                                rank, modelid, snapId, messageType, keyword, dtStart, dtEnd);
                        pageNum = page.getCurrent() - page.getPages();
                        result.setTotal(result.getTotal() + iPage.getTotal());
                        if (result.getRecords() == null || result.getRecords().size() == 0)
                            result.setRecords(iPage.getRecords());
                        else if (result.getRecords().size() < page.getSize() && iPage.getRecords() != null && iPage.getRecords().size() > 0) {
                            //合并记录
                            for (int i = 0; i < iPage.getRecords().size(); i++) {
                                result.getRecords().add(iPage.getRecords().get(i));
                                if (result.getRecords().size() == page.getSize())
                                    break;
                            }
                        }

                        //page从头开始
                        page.setCurrent(pageNum);
                        page.setTotal(0L);
                    }

                    return result;
                }
            } else {
                //表序： 由近到远
                long pageNum = 1;
                List<String> tbNames = tableNameService.getAlarmHistoryTableNames(stationId, dtStart, dtEnd);
                if (tbNames != null && tbNames.size() > 0) {
                    if (tbNames.size() == 1)
                        return alarmHisotryMapper.pageQueryAll(page, tbNames.get(0), stationId, windturbineId, category1, category2,
                                rank, modelid, snapId, messageType, keyword, dtStart, dtEnd);
                    //HashMap<String, IPage<AlarmHistoryInfo>> resultMap = new HashMap<>();
                    IPage<AlarmHistoryInfo> result = new Page<>(page.getCurrent(), page.getSize());
                    for (String tbName : tbNames) {
                        IPage<AlarmHistoryInfo> iPage = alarmHisotryMapper.pageQueryAll(page, tbName, stationId, windturbineId, category1, category2,
                                rank, modelid, snapId, messageType, keyword, dtStart, dtEnd);
                        pageNum = page.getCurrent() - page.getPages();
                        result.setTotal(result.getTotal() + iPage.getTotal());
                        if (result.getRecords() == null || result.getRecords().size() == 0)
                            result.setRecords(iPage.getRecords());
                        else if (result.getRecords().size() < page.getSize() && iPage.getRecords() != null && iPage.getRecords().size() > 0) {
                            //合并记录
                            for (int i = 0; i < iPage.getRecords().size(); i++) {
                                result.getRecords().add(iPage.getRecords().get(i));
                                if (result.getRecords().size() == page.getSize())
                                    break;
                            }
                        }
                        //page从头开始
                        page.setCurrent(pageNum);
                        page.setTotal(0L);
                    }

                    return result;
                }
            }
        }catch (Exception ex) {
            log.error(ex.getMessage());
            log.error(ex.getStackTrace().toString());
        }

        return null;
    }

    public int selectSnapCount(String tableName, long snapid, Date startDate, Date endDate) {
        return  alarmHisotryMapper.selectSnapCount(tableName, snapid, startDate, endDate);
    }

    //宁夏定制化功能 暂时干掉
//    @Scheduled(cron = "0 */2 * * * ?")
//   public Map<String, String> getTodayCount() throws Exception{
//       listmap= new HashMap<>();
//       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//       Calendar calendar = Calendar.getInstance();
//       // 时
//       calendar.set(Calendar.HOUR_OF_DAY, 0);
//       // 分
//       calendar.set(Calendar.MINUTE, 0);
//       // 秒
//       calendar.set(Calendar.SECOND, 0);
//       // 毫秒
//       calendar.set(Calendar.MILLISECOND, 0);
//
//       String strDate =  sdf.format(calendar.getTime());
//       calendar.add(Calendar.DATE,1);
//       String strEnd = sdf.format(calendar.getTime());
//       List<Map<String, String>> list  = new ArrayList<>();
//       Page<AlarmSnap> page =new Page(1,10);
//
//       IPage<AlarmHistoryInfo> syz = pageQueryAll(page,"","","SYZ","","","",null,null,"",strDate,strEnd);
//        if(syz!=null){
//            listmap.put("syzgj",syz.getTotal()+"");
//        }
//       IPage<AlarmHistoryInfo> windturbine = pageQueryAll(page,"","","windturbine","","","",null,null,"",strDate,strEnd);
//        if(windturbine!=null){
//            listmap.put("fjgj",windturbine.getTotal()+"");
//        }
//       IPage<AlarmHistoryInfo> custom = pageQueryAll(page,"","","custom","","","",null,null,"",strDate,strEnd);
//        if(custom!=null){
//            listmap.put("fjyj",custom.getTotal()+"");
//        }
//       Date currentDate = sdf.parse(strDate);
//       Map<String, String> shutdown = shutdownEventMapper.queryTodayCount(currentDate);
//        if(shutdown!=null){
//            listmap.put("tj",shutdown.get("count"));
//        }
//       Map<String, String> Brownouts2  = mainBrownoutsMapper.queryMainBrownouts2Count(currentDate);
//        if(Brownouts2!=null){
//            listmap.put("xd",Brownouts2.get("count"));
//        }
//       return listmap;
//    }


}
