package com.bohuikeji.delivery.backstage.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
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.TCustomer;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.socket.AdminNotice;
import com.bohuikeji.delivery.backstage.entity.socket.CourierNotice;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.util.WxUtils;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.socket.Smsg;
import com.bohuikeji.frame.module.admin.service.IRanchSocketService;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.utils.BaiDuAiUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * socket消息业务封装
 * @author 孙劲辉
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SocketServiceImpl implements ISocketService {
    final IRanchSocketService ranchSocket;
    final ITFranchiseeInformationService franchiseeInformationService;
    final RedisUtil redisUtil;
    final IWxUserService wxUserService;
    final ITOrderService itOrderService;
    final ITCourierService courierService;
    final ITCustomerService customerService;

    /**
     * 发送通用后台消息
     * 使用该方法发送给加盟商的消息，平台也会同步收到
     *
     * @param notice
     */
    @Override
    public void sendAdminMsg(AdminNotice notice) {
        //如果的给平台的消息直接推送
        if(notice.getFranId().equals(1)){
            ranchSocket.sendMsg(new Smsg(notice.getUrl(),notice));
            return;
        }
        //加盟商的消息推送给自己和上级
        for (Object id:franchiseeInformationService.querySuper(notice.getFranId())) {
            ranchSocket.sendMsg(new Smsg(notice.setFranId(Integer.parseInt(id.toString())).getUrl(),notice));
        }
        //最后消息在推送给后台
        ranchSocket.sendMsg(new Smsg(notice.setFranId(1).getUrl(),notice));


    }

    /**
     * 发送加盟商后台消息
     * 使用此方法发送给加盟商的消息，平台不会接受
     *
     * @param notice
     */
    @Override
    public void senFranMsg(AdminNotice notice) {
        ranchSocket.sendMsg(new Smsg(notice.getUrl(),notice));
    }

    /**
     * 发送信息给骑手
     * 公众号模板消息
     * @param notice 消息主体
     * @param tts 是否自动转为语音
     */
    @Override
    public CourierNotice sendCourierMsg(CourierNotice notice,boolean tts) {
        if(tts){
            notice.setMp3(BaiDuAiUtils.tts(notice.getText()));
        }
        for (String courierId : notice.getCourierIds().split(",")) {
            //如果骑手在线则进行推送
            ranchSocket.sendMsg(new Smsg(CourierNotice.URL+courierId,notice));
            log.info("消息推送的详细信息：{}",notice);
        }
        if (notice.getParams()==null||notice.getParams().size()<1){
            return notice;
        }
        //发送公众号模板消息
        List<TWxUser> wxUserList=wxUserService.list(new QueryWrapper<TWxUser>().in("user_id", (Object) notice.getCourierIds().split(",")).eq("user_type","COURIER").eq("wx_app_type","GZH"));
        log.info("##################################2:{}",wxUserList);
        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");
        wxUserList.forEach(u->{
            WxUtils.sendTmplMsg(WxAppEm.GZH_TCJS,courierTlmp,u.getWxUserOpenid(),notice.getParams());
        });
        return notice;
    }

    /**
     * 小程序模板消息
     * @param tOrderid
     * @param dsc
     * @return
     */
    @Override
    public void sendOutNews(Integer tOrderid,List<Integer> ids,String dsc) {
        log.info("********************骑手小程序订阅消息推送*********************：{}",tOrderid);
        LocalDate now = LocalDate.now();
        TOrder tOrder = itOrderService.getById(tOrderid);
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@:{}",ids);
        for (Integer courierId : ids) {
            log.info("@@@@@@@@@@@@@@@@@@@@在线骑手的id:{}",courierId);
            WxAppEm app= WxAppEm.MP_COURIER;
            TWxUser wxUser=wxUserService.getUserByType(courierId,WxAppEm.WX_USER_TYPE_COURIER,app);
            //String jsonStr = JSONObject.toJSONString(tOrder);
            //JSONObject js = JSONObject.parseObject(jsonStr);
            TCustomer customer = customerService.getById(tOrder.getPlayerId());
            String time8 = now.getYear()+"年"+now.getMonthValue()+"月"+ LocalDateTime.now().getDayOfMonth()+"日"+" "+LocalDateTime.now().getHour()+":"+LocalDateTime.now().getMinute();

            JSONObject body=new JSONObject();
            body.put("touser",wxUser.getWxUserOpenid());
            body.put("template_id","7yznkgJIYV3tEODP765RmDOB-t0o0OXUYk6Q9q8K4Ec");
            body.put("page","pages/order/orderDetail?orderId="+tOrder.getOrderId());
            JSONObject json=new JSONObject();

            JSONObject object=new JSONObject();
            object.put("value",customer.getCustomerName());
            JSONObject object1=new JSONObject();
            object1.put("value",tOrder.getMailingAddress().getArea());
            JSONObject object2=new JSONObject();
            object2.put("value",tOrder.getOrderNum());
            JSONObject object3=new JSONObject();
            object3.put("value",time8);
            JSONObject object4=new JSONObject();
            object4.put("value",tOrder.getContactPhone());
            json.put("character_string1",object2);
            json.put("thing6",object);
            json.put("phone_number7",object4);
            json.put("time3",object3);
            json.put("thing4",object1);
            body.put("data",json);
            //发送
            log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@请求参数：{}",body);
            String accessToken= WxUtils.getAccessToken(WxAppEm.MP_COURIER);
            String post  =  HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body.toString());
            log.info("********************骑手小程序订阅消息推送成功*********************：[{}]",post);
            //如果骑手在线则进行推送
        }
    }
}
