package com.mvc.service.copy;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.dao.TPackLogMapper;
import com.mvc.entity.TPackLog;
import com.mvc.entity.TPackLogExample;
import com.mvc.model.TPackLogModel;
import com.mvc.netty.dealconstant.HandleMsgCode;
import com.mvc.service.PackLogMana;
import com.mvc.utils.DateUtil;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Service
@Transactional
public class TPackLogService {

    @Resource
    private TPackLogMapper tPackLogMapper;

    //查找未处理的的原始报文
    public List<TPackLog> selectUnParse() {
        TPackLogExample example = new TPackLogExample();
        TPackLogExample.Criteria criteria = example.createCriteria();
        criteria.andFlagEqualTo("0");
        List<TPackLog> list = tPackLogMapper.selectByExample(example);
        return list;
    }

    public TPackLog updateTPackLog(TPackLog tpacklog) {
        tPackLogMapper.updateByPrimaryKey(tpacklog);
        return tpacklog;
    }

    //查找未处理大图集合String
    public List<String> selectDistinctUnParsecode_DT(String flag) {
        List<String> strings = tPackLogMapper.selectDistinctUnParsecode_DT(flag);
        return strings;
    }

    public List<TPackLog> selectUnParse_DT(String stationcode) {
        TPackLogExample example = new TPackLogExample();
        TPackLogExample.Criteria criteria = example.createCriteria();
        criteria.andStationCodeEqualTo(stationcode);
        criteria.andFlagEqualTo("10");
        example.setOrderByClause("PACK_INDEX");
        List<TPackLog> tPackLogs = tPackLogMapper.selectByExample(example);
        return tPackLogs;
    }

    public List<TPackLog> selectUnParse_duobao(String stationcode) {
        TPackLogExample example = new TPackLogExample();
        TPackLogExample.Criteria criteria = example.createCriteria();
        criteria.andStationCodeEqualTo(stationcode);
        criteria.andFlagEqualTo("20");
        example.setOrderByClause("PACK_INDEX");
        List<TPackLog> tPackLogs = tPackLogMapper.selectByExample(example);
        return tPackLogs;
    }

    //根据条件查询原始报文
    public Map<String, Object> findAllTPackLog(TPackLogModel model) {
        Map<String, Object> resMap = new HashMap<>();
        List<TPackLogModel> resList = new ArrayList<>();
        Page<Object> pageObject = PageHelper.startPage(model.getPage(), model.getRows());
        TPackLogExample example = new TPackLogExample();
        TPackLogExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(model.getStationCode())) {
            criteria.andStationCodeEqualTo(model.getStationCode());
        }
        if (model.getRevTime() != null) {
            criteria.andRevTimeLessThan(model.getRevTime());
        }

        List<TPackLog> tPackLogs = tPackLogMapper.selectByExample(example);
        for (int i = 0; i < tPackLogs.size(); i++) {
            TPackLogModel tmodel = new TPackLogModel();
            BeanUtils.copyProperties(tPackLogs.get(i), tmodel);
            resList.add(tmodel);
        }
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

    /**
     * 查询未解析的组ID列表
     *
     * @param flag
     * @return
     */
    public List<String> selectDistinctUnParsecode_PackGid_DT(String flag) {
        List<String> strings = tPackLogMapper.selectDistinctUnParsecode_PackGid_DT(flag);
        return strings;
    }

    /**
     * 根据组ID查询未解析的数据
     *
     * @param packGid
     * @param flag
     * @return
     */
    public List<TPackLog> selectUnParse_ByGid(String packGid, String flag) {
        TPackLogExample example = new TPackLogExample();
        TPackLogExample.Criteria criteria = example.createCriteria();
        criteria.andPackGidEqualTo(packGid);
        criteria.andFlagEqualTo(flag);
        example.setOrderByClause("PACK_INDEX");
        List<TPackLog> tPackLogs = tPackLogMapper.selectByExample(example);
        return tPackLogs;
    }

    /**
     * 根据查询对象分页查询列表
     *
     * @param queryModel
     * @return
     */
    public Map<String, Object> findAllTPackLogByQueryModel(TPackLogModel queryModel) {
        Map<String, Object> resMap = new HashMap<>();
        List<TPackLogModel> resList = new ArrayList<>();

        TPackLogExample example = new TPackLogExample();
        TPackLogExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(queryModel.getStationCode())) {
            criteria.andStationCodeEqualTo(queryModel.getStationCode());
        }

        if (StringUtils.isNotEmpty(queryModel.getUpordown())) {
            criteria.andUpordownEqualTo(queryModel.getUpordown());
        }

        if (StringUtils.isNotEmpty(queryModel.getPackGid())) {
            criteria.andPackGidEqualTo(queryModel.getPackGid());
        }

        //FF代表查询全部
        if (StringUtils.isNotEmpty(queryModel.getFunCode()) && !queryModel.getFunCode().equals("FF")) {
            criteria.andFunCodeEqualTo(queryModel.getFunCode());
        }

        if (StringUtils.isNotEmpty(queryModel.getFlag()) && !queryModel.getFlag().equals("FF")) {
            criteria.andFlagEqualTo(queryModel.getFlag());
        }

        if (StringUtils.isNotEmpty(queryModel.getStartTime())) {
            Date date = DateUtil.parseTimeStr(queryModel.getStartTime(), "yyyy-MM-dd HH:mm:ss");
            criteria.andRevTimeGreaterThanOrEqualTo(date);
        }

        if (StringUtils.isNotEmpty(queryModel.getEndTime())) {
            Date date = DateUtil.parseTimeStr(queryModel.getEndTime(), "yyyy-MM-dd HH:mm:ss");
            criteria.andRevTimeLessThanOrEqualTo(date);
        }
        example.setOrderByClause("TIME_STAMP DESC");

        Page<Object> pageObject = PageHelper.startPage(queryModel.getPage(), queryModel.getRows());
        List<TPackLog> tPackLogs = tPackLogMapper.selectByExample(example);
        for (TPackLog tPackLog : tPackLogs) {
            TPackLogModel model = new TPackLogModel();
            BeanUtils.copyProperties(tPackLog, model);
            resList.add(model);
        }
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

    /**
     * 根据ID查询报文(带报文内容)
     *
     * @param id
     * @return
     * @throws IOException
     */
    public TPackLogModel findTPackLogById(Integer id) throws IOException {
        TPackLog tPackLog = tPackLogMapper.selectByPrimaryKey(id);
        TPackLogModel model = null;
        if (tPackLog != null) {
            model = new TPackLogModel();
            BeanUtils.copyProperties(tPackLog, model);
            String content = PackLogMana.getFileContent(model.getFileName(), model.getStationCode(), 1);
            model.setOriginmessage(content);
        }
        return model;
    }

    /**
     * 生成报文日志记录,并保存文件
     *
     * @param logs
     * @param revTime
     * @throws IOException
     */
    public void savePackLog(List<TPackLog> logs, Date revTime) {
        if(logs == null || logs.isEmpty()){
            return;
        }
        String fileName = PackLogMana.savePackLog(logs);
        TPackLog tPackLog = logs.get(0);
        if (StringUtils.isEmpty(tPackLog.getPackId()) || tPackLog.getPackId().length() < 32) {
            tPackLog.setPackId(StringUtil.getUuid());
        }
        if (revTime == null || revTime.getTime() == 0) {
            tPackLog.setRevTime(tPackLog.getRevTime() == null ? new Date() : tPackLog.getRevTime());
        } else {
            tPackLog.setRevTime(revTime);
        }

        tPackLog.setFileName(fileName);
        tPackLog.setOriginmessage("");//不将报文存储到数据库中
        tPackLog.setMessage("");
        tPackLog.setPackGid(logs.get(0).getPackId());
        tPackLog.setPackIndex(logs.size());
        tPackLog.setTimeStamp(tPackLog.getRevTime().getTime());
        //下行加5毫秒,主要为了处理报文排序问题,部分报文会有收发时间一致,导致排序颠倒 2024-09-18 guozhao
        if (tPackLog.getUpordown().equals("8")) {//下行
            tPackLog.setTimeStamp(tPackLog.getTimeStamp() + 5);
        }

        int rptLen = logs.stream().mapToInt(o -> o.getRptLen() == null ? 0 : o.getRptLen()).sum();
        tPackLog.setRptLen(rptLen);
        tPackLogMapper.insert(logs.get(0));
    }

    /**
     * 生成报文日志记录,并保存文件
     *
     * @param log
     * @param revTime
     * @throws IOException
     */
    public void savePackLog(TPackLog log, Date revTime) {
        if (StringUtils.isEmpty(log.getOriginmessage())) {//待优化 2023-01-17 guozhao
            if (log.getFunCode().equalsIgnoreCase(HandleMsgCode.H_ED.getCode())) {

            }
            return;
        }
        List<TPackLog> logs = new ArrayList<>();
        logs.add(log);
        savePackLog(logs, revTime);
    }
}
