package com.mvc.service.external;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.dao.StationAccMapper;
import com.mvc.entity.StationAcc;
import com.mvc.entity.StationAccExample;
import com.mvc.interceptor.JwtInterceptor;
import com.mvc.model.*;
import com.mvc.model.external.IdentResultModel;
import com.mvc.service.TAffiliatedunitService;
import com.mvc.service.copy.TAireadService;
import com.mvc.service.taizhang.CustomUserService;
import com.mvc.service.taizhang.StationAccService;
import com.mvc.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ExternalRequestService {
    private static Logger log = LoggerFactory.getLogger(ExternalRequestService.class);

    @Resource
    private TAireadService aireadService;

    @Resource
    private CustomUserService customUserService;

    @Resource
    private StationAccService stationAccService;

    @Resource
    private StationAccMapper stationAccMapper;

    @Resource
    private TAffiliatedunitService affiliatedunitService;

    //private boolean mIsFilterTodayDate = true;//是否过滤当日数据

    /**
     * 根据站码获取最新一条数据
     *
     * @param stationCode
     * @return
     */
    public IdentResultModel getIdentRecord(String stationCode) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userId = JwtInterceptor.getUserIdByRequest(request);
        log.info("接口调用:{}_userId:{}", "getIdentRecord", userId);
        if (!checkStationAcc(userId, stationCode)) return null;

        /*String endTime = "";
        if (mIsFilterTodayDate) {//过滤当日数据
            Date queryTime = DateUtil.getZeroTimeOfDay(new Date());//当日0点
            queryTime = DateUtil.getOtherDateByMinute(queryTime, -1);//昨日23:59(为了让用户取得昨日的数据)
            endTime = DateUtil.formateDate(queryTime, DateUtil.PATTERN_DATA_UNSIGNED);
        }*/
        String endTime = getQueryEndTime();

        Map<String, Object> map = aireadService.findAllTAireadByStationCode(stationCode, "", endTime, 1, 10);
        List<TAireadModel> aireadModelList = (List<TAireadModel>) map.get("list");
        if (aireadModelList == null || aireadModelList.size() == 0) {
            return null;
        }
        for (TAireadModel model : aireadModelList) {
            if (model.getResultValue() == null) {
                continue;
            }
            if (StringUtils.isEmpty(model.getDeviceSn())) {
                Optional<TAireadModel> optional = aireadModelList.stream().filter(s -> StringUtils.isNotEmpty(s.getDeviceSn())).findFirst();
                if (optional.isPresent()) {
                    model.setDeviceSn(optional.get().getDeviceSn());
                }
            }

            return new IdentResultModel(model);
        }
        return null;
    }

    /**
     * 根据站码和时间范围获取记录列表
     *
     * @param stationCode
     * @param startTime
     * @param endTime
     * @return
     */
    public List<IdentResultModel> getIdentRecords(String stationCode, String startTime, String endTime) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userId = JwtInterceptor.getUserIdByRequest(request);
        log.info("接口调用:{}_userId:{}", "getIdentRecords", userId);
        if (!checkStationAcc(userId, stationCode)) return new ArrayList<>();

        /*if (mIsFilterTodayDate) {
            Date queryTime = DateUtil.getZeroTimeOfDay(new Date());//当日0点
            queryTime = DateUtil.getOtherDateByMinute(queryTime, -1);//昨日23:59(为了让用户取得昨日的数据)

            Date dtEndTime = DateUtil.parseTimeStr(endTime, DateUtil.PATTERN_DATA_UNSIGNED);
            if (dtEndTime.after(queryTime)) {//超过昨日,则取昨日
                endTime = DateUtil.formateDate(queryTime, DateUtil.PATTERN_DATA_UNSIGNED);
            }
        }*/
        Date dtEndTime = DateUtil.parseTimeStr(endTime, DateUtil.PATTERN_DATA_UNSIGNED);//参数中的结束时间
        String tempEndTime = getQueryEndTime();
        Date tempDtEndTime = DateUtil.parseTimeStr(tempEndTime, DateUtil.PATTERN_DATA_UNSIGNED);//限制的结束时间
        if (dtEndTime.after(tempDtEndTime)) {//查询时间超过了限制时间
            endTime = tempEndTime;
        }

        Map<String, Object> map = aireadService.findAllTAireadByStationCode(stationCode, startTime, endTime, 1, 100);
        List<TAireadModel> aireadModelList = (List<TAireadModel>) map.get("list");

        //按采样时间去除重复
        aireadModelList = aireadModelList.stream()
                .collect(Collectors.toMap(
                        TAireadModel::getSampleTime,
                        Function.identity(),
                        (existing, replacement) -> existing,
                        LinkedHashMap::new // 这里指定了映射类型
                )).values()
                .stream()
                .collect(Collectors.toList());

        String deviceSn = "";
        List<IdentResultModel> resultModels = new ArrayList<>();
        for (TAireadModel aireadModel : aireadModelList) {
            if (aireadModel.getResultValue() == null) {//去除无效值
                continue;
            }

            if (DateUtil.getMinutes(aireadModel.getSampleTime()) != 0) {//去除非整点
                continue;
            }

            if (StringUtils.isEmpty(aireadModel.getDeviceSn())) {//补上SN(补发报的情况)
                if (StringUtils.isNotEmpty(deviceSn)) {
                    aireadModel.setDeviceSn(deviceSn);
                } else {
                    Optional<TAireadModel> optional = aireadModelList.stream().filter(s -> StringUtils.isNotEmpty(s.getDeviceSn())).findFirst();
                    if (optional.isPresent()) {
                        deviceSn = optional.get().getDeviceSn();
                        aireadModel.setDeviceSn(deviceSn);
                    }
                }
            }
            if (StringUtils.isEmpty(aireadModel.getDeviceSn())) {
                continue;
            }

            IdentResultModel resultModel = new IdentResultModel(aireadModel);
            resultModels.add(resultModel);

            if (StringUtils.isEmpty(deviceSn) && StringUtils.isNotEmpty(aireadModel.getDeviceSn())) {
                deviceSn = aireadModel.getDeviceSn();
            }
        }

        return resultModels;
    }

    /**
     * 获取当前用户的所有站点最新数据列表
     *
     * @return
     */
    public ResPageModel getIdentRecords(int pageNum, int pageSize) {
        pageSize = pageSize > 100 ? 100 : pageSize;//最多100条
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userId = JwtInterceptor.getUserIdByRequest(request);
        log.info("接口调用:{}_userId:{}", "getIdentRecords_page", userId);
        CustomUserModel userModel = customUserService.findCustomUserModelByUserId(userId);

        ResPageModel pageModel = findAllStationAccListByUnitCode(userModel.getUnitCode(), pageNum, pageSize);

        String endTime = "";
        /*if (mIsFilterTodayDate) {
            Date queryTime = DateUtil.getZeroTimeOfDay(new Date());//当日0点
            queryTime = DateUtil.getOtherDateByMinute(queryTime, -1);//昨日23:59(为了让用户取得昨日的数据)
            endTime = DateUtil.formateDate(queryTime, DateUtil.PATTERN_DATA_UNSIGNED);
        }*/
        endTime = getQueryEndTime();
        List<IdentResultModel> identities = new ArrayList<>();

        if (pageModel == null || pageModel.getList() == null) {//无数据
            return new ResPageModel(null, 0, 0, 0);
        } else {
            List<StationAcc> stationAccs = (List<StationAcc>) pageModel.getList();
            for (StationAcc stationAcc : stationAccs) {
                Map<String, Object> map = aireadService.findAllTAireadByStationCode(stationAcc.getStationCode(), "", endTime, 1, 100);
                List<TAireadModel> aireadModelList = (List<TAireadModel>) map.get("list");

                TAireadModel temp = null;

                for (TAireadModel aireadModel : aireadModelList) {//找有效数据
                    if (aireadModel.getResultValue() == null) {//去除无效值
                        continue;
                    }

                    if (DateUtil.getMinutes(aireadModel.getSampleTime()) != 0) {//去除非整点
                        continue;
                    }

                    if (StringUtils.isEmpty(aireadModel.getDeviceSn())) {//补上SN(补发报的情况)
                        Optional<TAireadModel> optional = aireadModelList.stream().filter(s -> StringUtils.isNotEmpty(s.getDeviceSn())).findFirst();
                        if (optional.isPresent()) {
                            aireadModel.setDeviceSn(optional.get().getDeviceSn());
                        }
                    }
                    if (StringUtils.isEmpty(aireadModel.getDeviceSn())) {
                        continue;
                    }

                    temp = aireadModel;
                    break;
                }

                if (temp != null) {
                    IdentResultModel identResultModel = new IdentResultModel(temp);
                    //注意:特殊处理,紫东能源想要原始数据,传内容中带了图片,暂时不给其它用户 2025-02-17 guozhao
                    if (userId.equals("e27b64effc5f479eb41b2157304f8760")) {
                        identResultModel.setImageUrl(temp.getBigJpgUrl());
                    }
                    identities.add(identResultModel);
                } else {//数据必须与站点一对一,没有的补一个空数据
                    identities.add(new IdentResultModel(stationAcc.getStationCode()));
                }
            }
        }

        return new ResPageModel(identities, pageNum, pageSize, pageModel.getTotal());
    }

    /**
     * 根据单位代码分页获取可查看的所有遥测站点
     *
     * @param unitCode
     * @return
     */
    public ResPageModel findAllStationAccListByUnitCode(String unitCode, int pageNum, int pageSize) {
        TAffiliatedunitModel userUnitModel = affiliatedunitService.findTAffiliatedunit(unitCode);

        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();

        if (userUnitModel == null || StringUtils.isEmpty(userUnitModel.getUnitType())) return null;

        if (userUnitModel.getUnitType().equals("4")) {
            criteria.andUnitCodeEqualTo(unitCode);
        } else {
            criteria.andVisUnitCodesLike("%" + unitCode + "%");
        }
        Page<Object> pageObject = PageHelper.startPage(pageNum, pageSize);
        List<StationAcc> list = stationAccMapper.selectByExample(example);
        return new ResPageModel(list, pageObject);
    }

    /**
     * 校验站点台账,当前账户是否有权查看
     *
     * @param userId
     * @param stationCode
     * @return
     */
    private boolean checkStationAcc(String userId, String stationCode) {
        CustomUserModel userModel = customUserService.findCustomUserModelByUserId(userId);
        if (userModel == null) return false;//Token有效,但用户被删除(极端情况)

        StationAccModel accModel = stationAccService.findStationAccByStationCode(stationCode);
        if (accModel == null) return false;//未建台账

        return accModel.getUnitCode().equals(userModel.getUnitCode()) ||
                (accModel.getVisUnitCodes() != null && accModel.getVisUnitCodes().contains(userModel.getUnitCode()));
    }

    /**
     * 获取查询条件的结束时间
     * 以当日12点为分界,过了12点则取当日数据
     *
     * @return
     */
    private String getQueryEndTime() {
        Date now = new Date();
        Date queryTime = DateUtil.getZeroTimeOfDay(now);//当日0点
        if (DateUtil.getMinsbetweenTime(queryTime, now) < 12 * 60) {//当前时间未过12点(理论上未完成审核,使用昨日数据)
            queryTime = DateUtil.getOtherDateByMinute(queryTime, -1);//昨日23:59(为了让用户取得昨日的数据)
        }
        return DateUtil.formateDate(queryTime, DateUtil.PATTERN_DATA_UNSIGNED);
    }
}
