package com.jeequan.jeepay.mch.mq;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.components.mq.model.AppPushMQ;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.interfaces.push.IAppPushService;
import com.jeequan.jeepay.core.model.DBAppPushConfig;
import com.jeequan.jeepay.core.model.device.PayOrderInfo4Device;
import com.jeequan.jeepay.core.service.ISysConfigService;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchAppPushInfo;
import com.jeequan.jeepay.db.entity.MchConfig;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.service.impl.MchAppPushInfoService;
import com.jeequan.jeepay.service.impl.MchConfigService;
import com.jeequan.jeepay.service.impl.PayOrderService;
import com.jeequan.jeepay.service.impl.SysUserMchStoreRelaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 接收MQ消息
 * 业务： 新订单提醒 通知
 * @author zx
 * @date 2021/01/04 15:25
 */
@Slf4j
@Component
public class AppPushMQReceiver implements AppPushMQ.IMQReceiver {

    private static final int QUERY_PAGE_SIZE = 1000; //每次查询数量

    @Autowired private PayOrderService payOrderService;
    @Autowired private MchAppPushInfoService mchAppPushInfoService;
    @Autowired private ISysConfigService sysConfigService;
    @Autowired private MchConfigService mchConfigService;
    @Autowired private SysUserMchStoreRelaService sysUserMchStoreRelaService;

    @Override
    public void receive(AppPushMQ.MsgPayload payload) {

        log.info("接收支付成功app推送MQ, msg={}", payload.toString());

        String payOrderId = payload.getPayOrderId();

        // 查询订单、订单状态
        PayOrder payOrder = payOrderService.getById(payOrderId);
        if (payOrder == null || payOrder.getState() != PayOrder.STATE_SUCCESS) {
            return;
        }

        // 查询推送配置
        DBAppPushConfig appPushConfig = sysConfigService.getDBAppPushConfig();
        if (appPushConfig == null || appPushConfig.getUniPushVersion() == null) {
            log.info("系统未配置app推送");
            return;
        }

        // app推送开关
        boolean appPushFlag = mchConfigService.count(MchConfig.gw()
                .eq(MchConfig::getMchNo, payOrder.getMchNo())
                .eq(MchConfig::getConfigKey, "appVoice")
                .eq(MchConfig::getConfigVal, CS.YES))
                > 0;

        // 小程序推送开关
        boolean wxLitePushFlag = mchConfigService.count(MchConfig.gw()
                .eq(MchConfig::getMchNo, payOrder.getMchNo())
                .eq(MchConfig::getConfigKey, "weChatVoice")
                .eq(MchConfig::getConfigVal, CS.YES))
                > 0;

        if (appPushConfig.getUniPushVersion() == MchAppPushInfo.UNI_PUSH_VERSION_1) {
            if (!appPushFlag) {
                log.info("商户未开通app和小程序推送");
                return;
            }
        }else if(!appPushFlag && !wxLitePushFlag){
            log.info("商户未开通app和小程序推送");
            return;
        }

        // 推送消息内容
        JSONObject msgJSON = new JSONObject();
        msgJSON.put("type", "paySuccess");
        msgJSON.put("msg", getPushMsg(payOrder.getWayCodeType(), payOrder.getAmount()));
        msgJSON.put("expiredTime", DateUtil.formatDateTime(DateUtil.offsetMinute(payOrder.getSuccessTime(), PayOrderInfo4Device.EXPIRED_TIME)));

        // 查询订单  商户超管、普通操作员和门店下的店长、收银员  sysUserId
        Set<Long> sysUserIdSet = sysUserMchStoreRelaService.selectSysUserIdsByStoreId(payOrder.getMchNo(), payOrder.getStoreId());

        // 查询设备，单次最多1000条，需循环调用
        LambdaQueryWrapper<MchAppPushInfo> queryWrapper = MchAppPushInfo.gw()
                .eq(MchAppPushInfo::getMchNo, payOrder.getMchNo())
                .eq(MchAppPushInfo::getUniPushVersion, appPushConfig.getUniPushVersion())
                .in(MchAppPushInfo::getSysUserId, sysUserIdSet);

        List<String> cidTypes = new ArrayList<>();
        if (appPushFlag) {
            cidTypes.add(MchAppPushInfo.PUSH_CID_TYPE_APP);
        }
        if (wxLitePushFlag) {
            cidTypes.add(MchAppPushInfo.PUSH_CID_TYPE_WX);
        }
        queryWrapper.in(MchAppPushInfo::getCidType, cidTypes);

        int pageNum = 1;
        while (true) {
            try {
                // 查询app端推送设备cid
                IPage<MchAppPushInfo> pushInfoPage = mchAppPushInfoService.page(new Page<>(pageNum, QUERY_PAGE_SIZE), queryWrapper);
                if (CollUtil.isEmpty(pushInfoPage.getRecords())) {
                    break;
                }

                Set<String> cidList = pushInfoPage.getRecords().stream().map(MchAppPushInfo::getCid).collect(Collectors.toSet());

                // 调用推送
                if (appPushConfig.getUniPushVersion() == MchAppPushInfo.UNI_PUSH_VERSION_1) {

                    SpringBeansUtil.getBean("appPushService", IAppPushService.class).pushMessageToList(msgJSON.toJSONString(), cidList, appPushConfig);
                    log.info("uniPush1.0推送成功，payOderId={}, cldList={}", payOrder.getPayOrderId(), cidList);

                }else if (appPushConfig.getUniPushVersion() == MchAppPushInfo.UNI_PUSH_VERSION_2) {

                    JSONObject pushInfo = new JSONObject();
                    pushInfo.put("cids", cidList);
                    // pushInfo.put("getui_alias", "unipush2_" + payOrder.getStoreId());
                    pushInfo.put("title", "收款通知");
                    pushInfo.put("content", msgJSON.toJSONString());
                    pushInfo.put("data", new JSONObject());

                    HttpResponse response = HttpUtil.createPost(appPushConfig.getUniPushCloudUrl()).body(pushInfo.toJSONString()).execute();
                    if (!response.isOk()) {
                        log.info("uniPush2.0推送失败，payOderId={}, 云函数url={}, cldList={}，响应：{}", payOrder.getPayOrderId(), appPushConfig.getUniPushCloudUrl(), cidList, JSONObject.toJSONString(response));
                    }else {
                        log.info("uniPush2.0推送成功，payOderId={}, 云函数url={}, cldList={}，响应：{}", payOrder.getPayOrderId(), appPushConfig.getUniPushCloudUrl(), cidList, JSONObject.toJSONString(response));
                    }

                }

                //已经到达页码最大量，无需再次查询
                if(pushInfoPage.getPages() <= pageNum){
                    break;
                }
                pageNum++;

            }catch (Exception e) {
                log.error("app推送异常：", e);
                break;
            }
        }
    }

    // 播报语音
    private String getPushMsg(String wayCodeType, Long amount) {

        String wayTypeName = "";

        switch (wayCodeType) {
            case "WECHAT":
                wayTypeName = "微信";
                break;
            case "ALIPAY":
                wayTypeName = "支付宝";
                break;
            case "YSFPAY":
                wayTypeName = "云闪付";
                break;
            case "UNIONPAY":
                wayTypeName = "银联";
                break;
        }

        return wayTypeName + "收款" + AmountUtil.convertCent2Dollar(amount) + "元";
    }


}
