package com.bohuikeji.delivery.backstage.thread;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.constants.WxAppEm;
import com.bohuikeji.delivery.backstage.constants.WxTmplEm;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.service.IWxUserService;
import com.bohuikeji.delivery.backstage.util.AppPush;
import com.bohuikeji.delivery.backstage.util.WxUtils;
import lombok.extern.slf4j.Slf4j;

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

/***
 * 离线推送线程
 * @author 孙劲辉
 */
@Slf4j
public class OffLineMsgThread implements Runnable{
    private IWxUserService wxUserService;
    private List<Integer> ids;
    private TOrder order;

    public OffLineMsgThread(IWxUserService wxUserService, List<Integer> ids,TOrder order) {
        this.wxUserService = wxUserService;
        this.ids = ids;
        this.order=order;
    }


    /**
     * pages/start/start
     */
    @Override
    public void run() {
        log.error("【离线推送】等待推送的骑手：{}",ids);
        try {
            //限制条数,【修改这里】
            int limitTimes = 4000;
            //分批处理
            for (int from = 0, to = 0, size = ids.size(); from < size; from = to) {
                to = Math.min(from + limitTimes, size);
                log.info("执行处理1:{}条", ids.subList(from, to).size());
                AppPush.pusBatch("新订单提醒", order.getMailingAddress().getArea() + "有新的订单，猛戳抢单~~", ids.subList(from, to));
            }
        } catch (Exception e) {
            log.error("【通知栏消息推送失败】批量推送异常：", e);
        }
        //获取已绑定微信的
        wxUserService.list(new QueryWrapper<TWxUser>()
                .eq("wx_app_type","GZH")
                .eq("user_type","COURIER")
                .in("user_id",ids)).forEach(tWxUser -> {
            Map<String,Object> params=new HashMap<>();
            params.put("first","在您附近发现新的订单，猛戳抢单！");
            params.put("keyword1",order.getMailingName());
            params.put("keyword2",order.getMailingPhone().replaceAll("(\\d{3})\\d{5}(\\d{3})", "$1*****$2"));
            params.put("keyword3",order.getMailingAddress().getAddress());
            params.put("remark","点击立即抢单！");
            WxTmplEm courierTlmp=WxTmplEm.COURIER_ORDER_NEW;
            courierTlmp.setUrl(WxUtils.getMpShareLink(WxAppEm.MP_COURIER,"pages/index/index", null).getString("url_link"));
            courierTlmp.setMpAppid(WxAppEm.MP_COURIER.getAppId());
            courierTlmp.setMpPagePath("pages/index/index");
            WxUtils.sendTmplMsg(WxAppEm.GZH_TCJS, courierTlmp,tWxUser.getWxUserOpenid(),params);
        });

    }
}
