package com.bohuikeji.delivery.backstage.listener.order;

import com.bohuikeji.delivery.backstage.constants.KeyConst;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.socket.CourierNotice;
import com.bohuikeji.delivery.backstage.entity.vo.CourierAddressVo;
import com.bohuikeji.delivery.backstage.service.ISocketService;
import com.bohuikeji.delivery.backstage.service.ITCourierService;
import com.bohuikeji.delivery.backstage.service.ITNewsService;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
import com.bohuikeji.delivery.backstage.util.AppPush;
import com.bohuikeji.frame.module.admin.base.MqListener;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.utils.DistanceUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单指派完成监听处理
 * @author Admin
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderAssignListener extends MqListener<String> {

    final ITOrderService orderService;
    final ISocketService socketService;
    final ITNewsService newsService;
    final MqTool mqTool;
    final RedisUtil redisUtil;
    final ITFranchiseeInformationService franService;
    /**
     * 参数KEY：订单号
     */
    public static final String KEY_ORDER_ID="orderId";
    /**
     *
     */
    final ITCourierService courierService;
    /**
     * 参数Key:推送次号
     */
    public static final String KEY_TIMES="times";
    /**
     * 推送次数
     */
    private static final int SEND_TIMES=3;

    /**
     * 获取当前配置环境
     */
    @Value("${spring.profiles.active}")
    private String active;

    @Override
    public boolean onReceive(String orderNum) {
        TOrder order = orderService.getByNum(orderNum);
        if (order == null) {
            log.error("【消息队列监听错误】订单完创建发送通知消息失败，无法找到订单：[{}]", orderNum);
            return true;
        }
        //骑手id
        List<Integer> ids = new ArrayList<>(200);
        //推送ID
        List<String> finalcids = new ArrayList<>(200);
        //从Redis获取所以在线的骑手
        List<CourierAddressVo> courierAddressVos=redisUtil.getListByPattern(KeyConst.REDIS_COURIER_ADDRESS+"*",CourierAddressVo.class);
        //List<CourierAddressVo> courierAddressVos = redisUtil.getPatternKeys(KeyConst.REDIS_COURIER_LAST_ADDRESS+"*");
        courierAddressVos.forEach(cuv->{
            if(cuv.getCourier().getJobStatus().equals("停止")){
                return;
            }
            double dist = DistanceUtils.getDistance(order.getMailingAddress().getLng(), order.getMailingAddress().getLat(), cuv.getAddress().getLng(), cuv.getAddress().getLat());
            if(dist<50){
                ids.add(cuv.getCourier().getCourierId());
                String cid=cuv.getCourier().getCid();
                log.info("##################################1:{}",ids);
                if (StringUtils.isNotBlank(cid)){
                    finalcids.add(cid);
                }

            }
        });
        //推送语音消息
        CourierNotice notice = new CourierNotice("同城急送，订单来袭!", org.apache.commons.lang.StringUtils.join(ids, ","));
        notice.setMp3("https://oss.bhynm.com/delivery/upload/2022/3/23/164802791720412.mp3");
        socketService.sendCourierMsg(notice,false);
        courierService.sendOffLineMgs(order);
        //推送通知栏
        try {
            //限制条数,【修改这里】
            int limitTimes = 4000;
            //分批处理
            for (int from = 0, to = 0, size = finalcids.size(); from < size; from = to) {
                to = Math.min(from + limitTimes, size);
                log.info("执行处理1:{}条", finalcids.subList(from, to).size());
                AppPush.pusBatch("新订单提醒", order.getMailingAddress().getArea() + "有新的订单，猛戳抢单~~", finalcids.subList(from, to));
            }
        } catch (Exception e) {
            log.error("【通知栏消息推送失败】批量推送异常：", e);
        }
        return true;
    }

    @Override
    public void onError(String msg, Exception e) {

    }
}
