package com.jeequan.jeepay.pay.service.payorderpush.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeequan.jeepay.components.mq.model.PushWxMpMsgMQ;
import com.jeequan.jeepay.core.entity.MchWxmpUser;
import com.jeequan.jeepay.core.interfaces.wxmp.IWxMpTemplateMsgService;
import com.jeequan.jeepay.core.model.DBWxMpConfig;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.db.entity.PayWay;
import com.jeequan.jeepay.pay.service.payorderpush.AbstractPushService;
import com.jeequan.jeepay.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/*
* 支付成功 发送微信公众号消息 service
*
* @author zx
*
* @date 2021/6/8 17:43
*/
@Slf4j
@Service
public class PushWxMpTemplateMsgService extends AbstractPushService {

    @Autowired private SysConfigService sysConfigService;
    @Autowired private MchWxmpUserService mchWxmpUserService;
    @Autowired private PayWayService payWayService;
    @Autowired private IWxMpTemplateMsgService wxMpMessageService;
    @Autowired private PayOrderService payOrderService;
    @Autowired private SysUserMchStoreRelaService sysUserMchStoreRelaService;

    public void send(String payOrderId,Byte noticeType){
        // 查询订单、订单状态
        PayOrder payOrder = payOrderService.getById(payOrderId);
        if (!preCheck(payOrder)) {
            return;
        }
        try {
            // 查询微信公众号配置
            DBWxMpConfig wxMpConfig = sysConfigService.getDBWxMpConfig();
            if (wxMpConfig == null) {
                log.warn("公众号未配置，请前往运营平台 -> 系统管理 进行配置");
                return;
            }
            // 查询订单  商户超过和门店下的店长、店员  sysUserId
            Set<Long> sysUserIdSet = sysUserMchStoreRelaService.selectSysUserIdsByStoreId(payOrder.getMchNo(), payOrder.getStoreId());
            // 查询用于接收的用户列表
            List<MchWxmpUser> userList = new ArrayList<>();
            LambdaQueryWrapper<com.jeequan.jeepay.db.entity.MchWxmpUser> queryWrapper = com.jeequan.jeepay.db.entity.MchWxmpUser.gw();
            queryWrapper.eq(com.jeequan.jeepay.db.entity.MchWxmpUser::getMchNo, payOrder.getMchNo());
            queryWrapper.eq(com.jeequan.jeepay.db.entity.MchWxmpUser::getWxAppId, wxMpConfig.getWxAppId());
            queryWrapper.eq(com.jeequan.jeepay.db.entity.MchWxmpUser::getSendStatus, com.jeequan.jeepay.db.entity.MchWxmpUser.SEND_STATE_OPEN);
            queryWrapper.in(com.jeequan.jeepay.db.entity.MchWxmpUser::getSysUserId, sysUserIdSet);
            List<com.jeequan.jeepay.db.entity.MchWxmpUser> list = mchWxmpUserService.list(queryWrapper);
            userList.addAll(list);
            if(userList.isEmpty()){
                log.warn("无可推送用户，请先授权接收人");
                return;
            }
            String templateMessage = null;
            String templateId = wxMpConfig.getPaySuccMsgTemplateId();
            if(noticeType == PushWxMpMsgMQ.ORDER_NOTICE){
                PayWay payWay = payWayService.getById(payOrder.getWayCode());
                String wayName = payWay == null ? " " : payWay.getWayName();
//                String remark = StringUtils.defaultIfEmpty(wxMpConfig.getPaySuccMsgTemplateContentRemark(), StringUtils.defaultIfEmpty(payOrder.getSubject(), " "));
//                remark = StringUtils.substring(remark, 0, 20); // 最大20个字符
                templateMessage = wxMpConfig.getPaySuccMsgTemplateContent()
                        .replace("{{orderAmount}}", ("￥" + AmountUtil.convertCent2Dollar(payOrder.getAmount())))
                        .replace("{{payOrderId}}", payOrder.getPayOrderId())
                        .replace("{{payProductName}}", wayName)
                        .replace("{{paySuccTime}}", DateUtil.formatDateTime(payOrder.getSuccessTime()))
                        .replace("{{mercName}}", payOrder.getStoreName());
            }else if(noticeType == PushWxMpMsgMQ.ROUTE_NOTICE){
                //模板消息
                templateId = wxMpConfig.getNoticeMsgTemplateId();
            }else{
                return;
            }
            // 发送模板消息
            wxMpMessageService.sendTemplateMessage(userList, templateMessage, wxMpConfig,templateId);
//            wxMpMessageService.sendTemplateMessageExtend(userList, templateMessage, wxMpConfig);
        } catch (Exception e) {
            log.error("error", e);
        }
    }

}
