package com.bohuikeji.delivery.backstage.task;

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.ITOrderService;
import com.bohuikeji.delivery.backstage.service.IWxUserService;
import com.bohuikeji.delivery.backstage.util.AppPush;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.task.Task;
import com.bohuikeji.frame.module.admin.utils.DistanceUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.bohuikeji.frame.module.admin.utils.TaskUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 骑手订单通知任务
 *
 * @author 孙劲辉
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class CourierNoticeTask implements Task {

    /**
     * 参数KEY：订单号
     */
    public static final String KEY_ORDER_ID="orderId";
    /**
     * 参数Key:推送次号
     */
    public static final String KEY_TIMES="times";

    /**
     * 推送次数
     */
    private static final int SEND_TIMES=3;
    /**
     *
     */
    final ITCourierService courierService;
    /**
     * 提现处理业务类
     */
    final IWxUserService wxUserService;
    final RedisUtil redisUtil;
    final ITOrderService orderService;
    final ISocketService socketService;


    @Override
    public long delayTime() {
        return 1000*60*3;
    }

    @Override
    public void runTask(HashMap<String,Object> params) {
        TOrder order = orderService.getById((Integer)params.get(KEY_ORDER_ID));
        log.info("骑手小程序订单消息推送：{}",order.getOrderNum());
        if (order == null) {
            log.error("【骑手订单通知任务】运行错误我，参数[order]为null");
            throw new RuntimeException("【骑手订单通知任务】运行错误，参数[order]为null");
        }
        //测试订单不推送
        if (order.getTest()){
            return;
        }
        if (!"待接单".equals(order.getOrderStatus())) {
            log.error("【新订单提醒推送取消】订单{},状态已变为：{}",order.getOrderNum(),order.getOrderStatus());
            return;
        }
        //骑手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);
        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);
                }

            }
        });
        if (!ids.isEmpty()) {
            //推送语音消息
            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);
            //推送通知栏
            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);
            }
        }
        Integer times=(Integer) params.get(KEY_TIMES);
        /**
         * 只有第一次推送离线消息
         */
        if (times==null||times==1) {
            times = 1;
            //推送离线消息
            courierService.sendOffLineMgs(order);
        }
        //处理完成再扔回队列
        if(times<SEND_TIMES){
            TaskUtils.add(this,delayTime()*times).addParam(KEY_ORDER_ID,order.getOrderId()).addParam(KEY_TIMES,times+1);
        }
        //socketService.sendOutNews(order.getOrderId(),ids,null);
    }
}
