package com.zt.plat.module.qms.resource.device.common;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.ObjectUtils;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

public class DeviceUtil {


    /***
     * 根据频率类型，获取当前频率周期的开始时间和结束时间
     * @param date  上次执行日期
     * @param frequencyType 频率类型
     * @param frequency 频率
     * @return
     */
    public static LocalDateTime[] getDateRangeByFrequency(LocalDateTime date, boolean nextFlag, String frequencyType, String frequency) {
        LocalDateTime referenceDate = (date != null) ? date : LocalDateTime.now();
        LocalDateTime startDate = null;
        LocalDateTime endDate = null;
        int frequencyInt = Integer.parseInt(frequency);
        if(!nextFlag)
            frequencyInt --;
        switch (frequencyType.toLowerCase()) {
            case "day":
                startDate = referenceDate.plusDays(frequencyInt);
                endDate = startDate.plusDays(frequencyInt + 1);
                break;
//            case "day_before_use":  //每天第一次使用前，与按天相同。 截止2025-4-19，未启用此项
//                startDate = referenceDate.plusDays(frequencyInt);
//                endDate = startDate.plusDays(frequencyInt + 1);
//                break;
            case "week":
                startDate = referenceDate.plusWeeks(frequencyInt);
                startDate = startDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
                endDate = startDate.plusWeeks(1).minusDays(1);
                break;
            case "month":
                startDate = referenceDate.plusMonths(frequencyInt).withDayOfMonth(1);
                endDate = startDate.plusMonths(1).minusDays(1);
                break;
            case "year":
                startDate = referenceDate.plusYears(frequencyInt);
                endDate = startDate.plusYears(1).minusDays(1);
                break;
            default:
                return null;
        }

        return new LocalDateTime[]{
                LocalDateTime.of(startDate.toLocalDate(), LocalTime.of(0, 0, 0)),
                LocalDateTime.of(endDate.toLocalDate(), LocalTime.of(23, 59, 59))
        };
    }


    public static String assembleCommentJson(JSONArray flow){
        if(flow == null)
            return "";
        JSONArray entity = new JSONArray();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(int i = flow.size() - 1; i >= 0; i--){
            JSONObject flowItem = flow.getJSONObject(i);
            String historyActivityId = flowItem.getString("historyActivityId");
            String historyActivityName = flowItem.getString("historyActivityName");
            if(checkContains(entity, historyActivityId))
                continue;
            String assigneeName = flowItem.getString("assigneeName");
            String assignee = flowItem.getString("assignee");
            String endTime = flowItem.getString("endTime");
            JSONArray comments = flowItem.getJSONArray("comments");
            String comment = "";
            if(comments != null && comments.size() > 0){
                comment = comments.getJSONObject(0).getString("message");
            }
            if(!historyActivityId.toLowerCase().startsWith("activity_"))
                continue;
            if(!ObjectUtils.isEmpty(endTime)){
                JSONObject commentObj = new JSONObject();
                commentObj.put("nodeId", historyActivityId);
                commentObj.put("nodeName", historyActivityName);
                commentObj.put("comment", comment);
                commentObj.put("userName", assigneeName);
                commentObj.put("userId", assignee);
                commentObj.put("time", endTime);
                entity.add(commentObj);
            }
        }
        return entity.toJSONString();
    }

    public static void transCommentToValue(JSONObject voJson, String commentJsonStr){
        List<String> hasActivityList = new ArrayList<>();
        if(!ObjectUtils.isEmpty(commentJsonStr)){
            JSONArray arr = JSONArray.parseArray(commentJsonStr);
            for(int i=0;i<arr.size();i++){
                JSONObject obj = arr.getJSONObject(i);
                String nodeId = obj.getString("nodeId");
                String time = obj.getString("time");
                String comment = obj.getString("comment");
                String userName = obj.getString("userName");
                if(hasActivityList.contains(nodeId))
                    continue;
                voJson.put(nodeId + "-Comment",comment);
                voJson.put(nodeId + "-Time",time);
                voJson.put(nodeId + "-UserName",userName);
                hasActivityList.add(nodeId);
            }
        }
    }

    private static boolean checkContains(JSONArray entity, String nodeId){
        for(int i = 0; i < entity.size(); i++){
            JSONObject item2 = entity.getJSONObject(i);
            if(item2.getString("nodeId").equals(nodeId)){
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        LocalDateTime lastDate = LocalDateTime.of(2025, 3 , 25, 0, 0);
        String frequencyType = "month";
        String frequency = "3";

        LocalDateTime[] result = getDateRangeByFrequency(lastDate, false, frequencyType, frequency);
        System.out.println("Start Date: " + result[0]);
        System.out.println("End Date: " + result[1]);
    }

}
