package cn.iocoder.yudao.module.order.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.apollo.core.event.AutoProcessNotCustomerServiceExceptionEvent;
import cn.iocoder.yudao.framework.common.constant.Constant;
import cn.iocoder.yudao.module.order.dal.dataobject.orderException.OrderExceptionDO;
import cn.iocoder.yudao.module.order.enums.OrderExceptionEnum;
import cn.iocoder.yudao.module.order.enums.OrderExceptionResult;
import cn.iocoder.yudao.module.order.service.orderException.OrderExceptionService;
import cn.iocoder.yudao.module.order.vo.orderException.OrderExceptionResultHandlerVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 订单相关操作日志监听
 *
 * @author zhengYi
 */
@Component("AutoProcessNotCustomerServiceExceptionListener")
@AllArgsConstructor
public class AutoProcessNotCustomerServiceExceptionListener {

    private final OrderExceptionService orderExceptionService;

    /**
     * 添加客户分配确认监听
     *
     * @param event 客户id
     */
    @EventListener(AutoProcessNotCustomerServiceExceptionEvent.class)
    public void assignedCustomerCallback(AutoProcessNotCustomerServiceExceptionEvent event) {
        //找到所有未处理的
        List<OrderExceptionDO> pendHeavyExceptionList = orderExceptionService.selectList(new LambdaQueryWrapper<OrderExceptionDO>()
                .in(OrderExceptionDO::getOrderExceptionStatus, 0, 1)
                .eq(OrderExceptionDO::getOrderExceptionType, OrderExceptionEnum.NOT_CUSTOMER_SERVICE_EXCEPTION.getKey())
                .apply("order_exception_remark ->> '$.descZh' like '%" + event.getCustomerNumber() + "'")
        );
        if (CollectionUtil.isNotEmpty(pendHeavyExceptionList)) {
            for (OrderExceptionDO orderExceptionDO : pendHeavyExceptionList) {
                OrderExceptionResultHandlerVo orderExceptionResultHandlerVo = new OrderExceptionResultHandlerVo();
                orderExceptionResultHandlerVo.setSource("pc");
                orderExceptionResultHandlerVo.setOrderExceptionId(orderExceptionDO.getId());
                orderExceptionResultHandlerVo.setOrderExceptionHandlerResult(OrderExceptionResult.NOT_CUSTOMER_SERVICE_EXCEPTION_RESULT.NOT);
                orderExceptionResultHandlerVo.setOrderExceptionHandlerRemark("客户已被他人捞取");
                orderExceptionResultHandlerVo.setHandlerId(Constant.SYSTEM_USER_ADMIN_ID); //admin

                //工作流处理
                orderExceptionService.handlerExceptionByExceptionId(orderExceptionResultHandlerVo);
            }
        }
    }
}
