package com.tzld.piaoquan.recommend.server.service.score4recall.strategy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tzld.piaoquan.recommend.server.service.score.ScorerConfigInfo;
import com.tzld.piaoquan.recommend.server.service.score4recall.AbstractScorer4Recall;
import com.tzld.piaoquan.recommend.server.service.score4recall.model4recall.Model4RecallKeyValue;
import com.tzld.piaoquan.recommend.server.util.ListMerger;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public class BlessRecallScore extends AbstractScorer4Recall {

    public BlessRecallScore(ScorerConfigInfo configInfo) {
        super(configInfo);
    }

    @Override
    public void loadModel() {
        doLoadModel(Model4RecallKeyValue.class);
    }

    @Override
    public List<Pair<Long, Double>> recall(Map<String, String> params) {
        // 节假日、时效性，判断
        Model4RecallKeyValue model = (Model4RecallKeyValue) this.getModel();
        if (model == null || model.kv == null) {
            return new ArrayList<>();
        }
        LocalDateTime now = LocalDateTime.now();
        // 节日祝福-每年
        List<Pair<Long, Double>> yearResult = new ArrayList<>();
        String yearlyFestivalTimeRange = params.get("yearly_festival_time_range");
        if (StringUtils.isBlank(yearlyFestivalTimeRange)) {
            return new ArrayList<>();
        }
        JSONObject jsonObject = JSONObject.parseObject(yearlyFestivalTimeRange);
        for (String festival : jsonObject.keySet()) {
            try {
                JSONArray jsonArray = jsonObject.getJSONArray(festival);
                if (jsonArray == null) {
                    continue;
                }
                List<String> timeRangeList = jsonArray.toJavaList(String.class);
                if (isFestivalTime(now, timeRangeList)) {
//                    Pair<LocalDateTime, LocalDateTime> startTimeAndEndTime = getStartTimeAndEndTime(timeRangeList.get(0));
//                    if (startTimeAndEndTime == null) {
//                        continue;
//                    }
                    List<Pair<Long, Double>> festivalLists = model.kv.getOrDefault(festival, new ArrayList<>());
                    if (festivalLists.isEmpty()) {
                        continue;
                    }
                    festivalLists = festivalLists.stream().map(pair -> Pair.of(pair.getLeft(), 0.0))
                            .limit(Math.min(200, festivalLists.size()))
                            .collect(Collectors.toList());
                    yearResult.addAll(festivalLists);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<Pair<Long, Double>> dayResult = new ArrayList<>();
        // 每日祝福-每天固定时间段
        String dailyFestivalTimeRange = params.get("daily_bless_time_range");
        if (StringUtils.isBlank(dailyFestivalTimeRange)) {
            return new ArrayList<>();
        }
        JSONObject dailyFestivalTimeRangeJson = JSONObject.parseObject(dailyFestivalTimeRange);
        for (String bless : dailyFestivalTimeRangeJson.keySet()) {
            try {
                String timeRange = dailyFestivalTimeRangeJson.getString(bless);
                if (isFestivalTime(now, Collections.singletonList(timeRange))) {
                    List<Pair<Long, Double>> festivalLists = model.kv.getOrDefault(bless, new ArrayList<>());
                    if (festivalLists.isEmpty()) {
                        continue;
                    }
                    festivalLists = festivalLists.stream().map(pair -> Pair.of(pair.getLeft(), 0.0))
                            .limit(Math.min(200, festivalLists.size()))
                            .collect(Collectors.toList());
                    dayResult.addAll(festivalLists);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 常规祝福类的小程序-任意时间
        List<Pair<Long, Double>> anyResult = new ArrayList<>();
        List<Pair<Long, Double>> festivalLists = model.kv.getOrDefault("祝福", new ArrayList<>());
        if (!festivalLists.isEmpty()) {
            festivalLists = festivalLists.stream().map(pair -> Pair.of(pair.getLeft(), 0.2))
                    .limit(Math.min(200, festivalLists.size()))
                    .collect(Collectors.toList());
            anyResult.addAll(festivalLists);
        }
        return ListMerger.mergeLists(yearResult, dayResult, anyResult);
    }

    public boolean isFestivalTime(LocalDateTime now, List<String> timeRangeList) {
        if (timeRangeList == null || timeRangeList.isEmpty()) {
            return false;
        }
        for (String timeRange : timeRangeList) {
            // 判断是否是 daily 开头
            if (StringUtils.startsWith(timeRange, "daily")) {
                // 判断是否是 daily 开头
                String dailyTimeRange = StringUtils.substring(timeRange, 6);
                String[] split = StringUtils.split(dailyTimeRange, "-");
                if (split.length != 2) {
                    continue;
                }
                String startTime = split[0];
                String endTime = split[1];
                // 获取当前时间的小时和分钟
                int hour = now.getHour();
                int minute = now.getMinute();
                // startTime: 21:00 endTime: 23:00
                String[] startSplit = StringUtils.split(startTime, ":");
                String[] endSplit = StringUtils.split(endTime, ":");
                if (startSplit.length != 2 || endSplit.length != 2) {
                    continue;
                }
                int startHour = Integer.parseInt(startSplit[0]);
                int startMinute = Integer.parseInt(startSplit[1]);
                int endHour = Integer.parseInt(endSplit[0]);
                int endMinute = Integer.parseInt(endSplit[1]);
                if (hour > startHour && hour < endHour) {
                    return true;
                } else if (hour == startHour && hour == endHour) {
                    if (minute >= startMinute && minute <= endMinute) {
                        return true;
                    }
                } else if (hour == startHour) {
                    if (minute >= startMinute) {
                        return true;
                    }
                } else if (hour == endHour) {
                    if (minute <= endMinute) {
                        return true;
                    }
                }
                continue;
            }
            // 时间格式 2024-12-20 00:00~2024-12-25 08:00
            String[] split = StringUtils.split(timeRange, "~");
            if (split.length != 2) {
                continue;
            }
            String startTime = split[0];
            String endTime = split[1];
            // 解析 startTime endTime
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            LocalDateTime startLocalDateTime = LocalDateTime.parse(startTime, dateTimeFormatter);
            LocalDateTime endLocalDateTime = LocalDateTime.parse(endTime, dateTimeFormatter);
            if (now.isAfter(startLocalDateTime) && now.isBefore(endLocalDateTime)) {
                return true;
            }
        }
        return false;
    }


}