package com.mvc.forwarmana;

import com.mvc.constant.DeviceType;
import com.mvc.constant.ReviewResultType;
import com.mvc.entity.StationAcc;
import com.mvc.entity.TaskReview;
import com.mvc.model.TAireadModel;
import com.mvc.model.TServerReadModel;
import com.mvc.service.aiiden.TaskReviewService;
import com.mvc.service.copy.TAireadService;
import com.mvc.service.copy.TServerReadService;
import com.mvc.service.taizhang.StationAccService;
import com.mvc.utils.DateUtil;
import com.mvc.utils.StoreBlockingQueue;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 智慧院数据转发
 */
@Component
public class ZHYForwarder {
    /* 水利所数据转发较为特殊,由于是审核后的数据全部转发,因此站点并未在转发字典进行记录 */

    private static Logger log = LoggerFactory.getLogger(ZHYForwarder.class);

    @Resource
    private StationAccService stationAccService;

    @Resource
    private TaskReviewService taskReviewService;

    @Resource
    private TAireadService aireadService;

    @Resource
    private TServerReadService serverReadService;

    //需要直发的单位(万邦安装的子单位,表脏但要数) 2024-09-19 guozhao
    private static final String DIRECT_UNIT_CODE = "ca2271426b1343faa457f28e17902102";

    /**
     * 生成水利所数据队列
     */
    public void generateSlsDataQueue() {
        Date nowDate = new Date();
        List<StationAcc> stationAccList = stationAccService.findAllStationAcc();
        Date yesterday = DateUtil.getOtherDateByCurrentDate(nowDate, -1);
        Map<String, TaskReview> reviewMap = taskReviewService.findTaskReviewMapByDate(yesterday);
        if (stationAccList == null || reviewMap == null || reviewMap.isEmpty()) {
            return;
        }

        /*Date testDate = DateUtil.parseTimeStr("20240921235900", DateUtil.PATTERN_DATA_UNSIGNED);//测试时间
        boolean isTest = nowDate.before(testDate);*/

        //采样时间是昨日16点(丰台区获取的是16点数据,其它单位也有可能是此情况) 2024-08-15 guozhao
        //Date sampleTime = DateUtil.getOtherDateByHour(DateUtil.getZeroTimeOfDay(nowDate), -8);
        //**注意:发昨天16点的数据,会导致及时率下降,将昨日审核数据作为当日0点数据来发 2025-06-28 guozhao
        Date sampleTime = DateUtil.getZeroTimeOfDay(nowDate);
        Date rptTime = nowDate;//为了与接收时间对应,改为当前时间
        //Date rptTime = DateUtil.getOtherDateByMinute(sampleTime, 1);//发报时间推后1分钟
        int num = 0;
        for (StationAcc acc : stationAccList) {
            if (!acc.getDeviceType().equals(DeviceType.WATER_METER.getCode())) {//非水表
                log.info("{}:非水表不推送", acc.getStationCode());
                continue;
            }

            if (!reviewMap.containsKey(acc.getStationCode())) {//审核记录中没有
                log.info("{}:无审核记录不推送", acc.getStationCode());
                continue;
            }

            TaskReview taskReview = reviewMap.get(acc.getStationCode());
            TAireadModel aireadModel = null;

            //未审核或无法辨别(处理需要直发和过滤的)
            if (!taskReview.getFinishedFlag().equals(ReviewResultType.IDENT_TRUE.getCode()) && !taskReview.getFinishedFlag().equals(ReviewResultType.REVIEW_REVISE.getCode())) {
                if (acc.getUnitCode() != null && DIRECT_UNIT_CODE.contains(acc.getUnitCode())) {//虽然无法辨别,但也要推送的 2024-09-20 guozhao
                    aireadModel = getValidAireadModel(acc.getStationCode(), rptTime);
                    if (aireadModel == null) {//如果没有可靠的记录,也要保障有
                        aireadModel = aireadService.getTaireadByAireadId(taskReview.getAireadId());
                    }
                    if (aireadModel != null) {
                        aireadModel.setSampleTime(sampleTime);//为了跳过时间卡控 2024-09-21 guozhao
                        //注意:无法辨别,又是万邦的表,也要推送,把值给0,防止生成数据时出错 2025-05-08 guozhao
                        //下面注释掉了,用设备值、前值都可以,但用0有可能会导致跳数
                        //aireadModel.setResultValue(BigDecimal.ZERO);
                        //aireadModel.setIdentValue(BigDecimal.ZERO);
                        //aireadModel.setRawValue(BigDecimal.ZERO);
                    }
                } else {
                    log.info("{}:未审核或无法辨别不推送-{}", acc.getStationCode(), taskReview.getFinishedFlag());
                    continue;
                }
            } else {
                aireadModel = aireadService.getTaireadByAireadId(taskReview.getAireadId());
            }

            if (aireadModel == null) {
                log.info("{}:AireadId未匹配到读数记录,不推送-{}", acc.getStationCode(), taskReview.getAireadId());
                continue;
            }

            if (DateUtil.daysBetween(aireadModel.getSampleTime(), yesterday) > 30) {
                log.info("{}:超过30天无数据不推送", acc.getStationCode());
                continue;
            }

            aireadModel = modifyAireadModel(aireadModel, taskReview);
            //将采样时间修改为今日
            aireadModel.setSampleTime(sampleTime);
            aireadModel.setRptTime(rptTime);
            num++;
            try {
                StoreBlockingQueue.sysReviewQueue.put(aireadModel);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.info("生成水利所推送数据队列:{} 条", num);
    }

    /**
     * 修改读数对象(根据审核对象)
     *
     * @param tAireadModel
     * @param taskReview
     * @return
     */
    private TAireadModel modifyAireadModel(TAireadModel tAireadModel, TaskReview taskReview) {
        try {
            if(taskReview.getReviewValue() != null){
                tAireadModel.setRawValue(taskReview.getReviewValue());
                tAireadModel.setIdentValue(taskReview.getReviewValue());
            }

            boolean isExistJpg = false;
            String smallUrl = "";
            if (StringUtils.isNotEmpty(taskReview.getServerReadId())) {
                TServerReadModel tServerReadModel = serverReadService.findTServerReadByAiServerReadid(taskReview.getServerReadId());

                if (tServerReadModel != null && StringUtils.isNotEmpty(tServerReadModel.getSmallJpgUrl())) {
                    smallUrl = tServerReadModel.getSmallJpgUrl();
                    tAireadModel.setSmallPicType(tServerReadModel.getSmallJpgType());
                    tAireadModel.setPicHeigth(tServerReadModel.getSmallJpgHeight());
                    tAireadModel.setPicWidth(tServerReadModel.getSmallJpgWidth());
                    smallUrl = taskReviewService.convertSmallUrl(smallUrl);         //改https后访问不到本机图片,转为本地路径
                    isExistJpg = true;
                }
            }

            if (!isExistJpg) {
                //没有图发空图,尺寸用假数据
                tAireadModel.setSmallPicType("2");
                tAireadModel.setPicHeigth(44);
                tAireadModel.setPicWidth(148);
            }

            tAireadModel.setSmallRawData(taskReviewService.getPicRawData(smallUrl));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return tAireadModel;
    }

    /**
     * 获取有效的读数记录
     *
     * @param stationCode
     * @param rptTime
     * @return
     */
    private TAireadModel getValidAireadModel(String stationCode, Date rptTime) {
        Date startTime = DateUtil.getOtherDateByMonth(rptTime, -6);
        List<TaskReview> taskReviews = taskReviewService.findValidReviewsByStationCodeAndDate(stationCode, startTime, rptTime);
        if (taskReviews == null || taskReviews.isEmpty()) {//没有有效的审核记录,找1278或不为0的
            //找最近的一条可靠记录
            List<TAireadModel> aireadModels = aireadService.findAllTaireadByStationCodeAndStartTime(stationCode, startTime);
            for (int i = aireadModels.size() - 1; i > 0; i--) {
                if (aireadModels.get(i).getGoodFlag() != null && aireadModels.get(i).getGoodFlag().equals("1")) {
                    return aireadModels.get(i);
                }
            }
        } else {
            return aireadService.getTaireadByAireadId(taskReviews.get(taskReviews.size() - 1).getAireadId());
        }

        return null;
    }
}
