package com.liquidnet.service.kylin.utils;

import com.liquidnet.service.kylin.constant.GroupBuyStatusConst;
import com.liquidnet.service.kylin.dto.vo.groupbuy.KylinGroupBuyMemberVo;
import com.liquidnet.service.kylin.dto.vo.groupbuy.KylinGroupBuyOrderVo;
import com.liquidnet.service.kylin.dto.vo.groupbuy.KylinGroupBuyRobotTaskVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

/**
 * 拼团机器人通用判定与预约清理（order / kylin / platform 共用）。
 */
public final class GroupBuyRobotUtil {

    public static final String USER_ID_PREFIX = "robot_";
    public static final String ORDER_TICKETS_ID_PREFIX = "ROBOT_";

    private GroupBuyRobotUtil() {
    }

    public static boolean isRobot(KylinGroupBuyMemberVo member) {
        if (member == null) {
            return false;
        }
        if (Integer.valueOf(1).equals(member.getIsRobot())) {
            return true;
        }
        if (StringUtils.startsWith(member.getOrderTicketsId(), ORDER_TICKETS_ID_PREFIX)) {
            return true;
        }
        return StringUtils.startsWith(member.getUserId(), USER_ID_PREFIX);
    }

    public static boolean isRobotPlanPending(KylinGroupBuyOrderVo group) {
        if (group == null) {
            return false;
        }
        Integer status = group.getRobotPlanStatus();
        return status == null || GroupBuyStatusConst.RobotPlanStatus.NONE.equals(status);
    }

    /** 仅取消未执行任务，不改 robotPlanStatus。 */
    public static void cancelPendingTasks(KylinGroupBuyOrderVo group) {
        if (group == null || CollectionUtils.isEmpty(group.getRobotTasks())) {
            return;
        }
        for (KylinGroupBuyRobotTaskVo task : group.getRobotTasks()) {
            if (task == null) {
                continue;
            }
            if (task.getStatus() == null
                    || GroupBuyStatusConst.RobotTaskStatus.PENDING.equals(task.getStatus())) {
                task.setStatus(GroupBuyStatusConst.RobotTaskStatus.CANCELLED);
            }
        }
    }

    /**
     * 取消未执行任务；计划若非已完成则置为已取消。
     */
    public static void cancelPendingPlan(KylinGroupBuyOrderVo group) {
        if (group == null) {
            return;
        }
        cancelPendingTasks(group);
        if (!GroupBuyStatusConst.RobotPlanStatus.DONE.equals(group.getRobotPlanStatus())) {
            group.setRobotPlanStatus(GroupBuyStatusConst.RobotPlanStatus.CANCELLED);
        }
    }
}
