package com.sifang.modules.taskdispatch.util;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.utils.DateUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 派工 tools
 */
@SuppressWarnings("ALL")
public class ItemDispatchUtil {

    /**
     * timeSpans must be sorted, and must not intersect with each other
     */
    public static TimeDurationInfo duration(Date startTime, Date endTime, List<String> timeSpans) {
        if (startTime.after(endTime)) {
            return new TimeDurationInfo(0, 0, 0);
        }

        List<TimeSpan> spans = new ArrayList<>();
        if (DateUtils.isSameDay(startTime, endTime)) {
            spans.add(new TimeSpan(startTime, endTime));
        } else {
            spans.add(new TimeSpan(startTime, DateUtils.truncate(DateUtils.addDays(startTime, 1), Calendar.DATE)));
            Date st = DateUtils.addDays(new Date(startTime.getTime()), 1);
            while (!DateUtils.isSameDay(st, endTime)) {
                Date begin = DateUtils.truncate(st, Calendar.DATE);
                spans.add(new TimeSpan(begin, DateUtils.addDays(begin, 1)));
                st = DateUtils.addDays(st, 1);
            }
            spans.add(new TimeSpan(DateUtils.truncate(endTime, Calendar.DATE), endTime));
        }

        long all = 0L;
        for (TimeSpan span : spans) {
            for (String timeSpan : timeSpans) {
                long overlapDuration = span.getOverlapDuration(new TimeSpan(DateUtils.truncate(span.getStart(), Calendar.DATE), timeSpan));
                all += overlapDuration;
            }
        }
        return TimeSpan.getOverlapDurationInfo(all);
    }

    public static void setReviewFlag(List<Record> records) {
        setReviewFlag(records, false);
    }

    public static void setReviewFlag(List<Record> records, boolean withArchive) {
        User user = UserUtils.getUser();
        if (user == null) {
            return;
        }
        if (CollectionUtils.isEmpty(records)) {
            return;
        }
        for (Record record : records) {
            record.set("review_flag", false);
            if (Objects.equals(record.getStr("assign_audit_user_id"), user.getId())) {
                record.set("review_flag", true);
            }
            if (withArchive) {
                if (Objects.equals(record.getStr("archive_audit_user_id"), user.getId())) {
                    record.set("archive_review_flag", true);
                }
            }
        }
    }


}
