package com.starry.admin.modules.weichat.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.common.play.wx.WeChatConstants;
import com.starry.admin.modules.clerk.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.clerk.module.entity.PlayClerkUserReviewInfoEntity;
import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
import com.starry.admin.modules.custom.service.IPlayCustomUserInfoService;
import com.starry.admin.modules.order.module.entity.PlayOrderInfoEntity;
import com.starry.admin.modules.platform.entity.SysTenantEntity;
import com.starry.admin.modules.platform.service.impl.SysTenantServiceImpl;
import com.starry.admin.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.impl.WxMpMapConfigImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author admin
 */
@Slf4j
@Service
public class WxCustomMpService {

    @Resource
    private WxMpService wxMpService;

    @Resource
    private SysTenantServiceImpl tenantService;
    @Resource
    private IPlayCustomUserInfoService customUserInfoService;


    public WxMpService proxyWxMpService() {
        String tenantId = SecurityUtils.getTenantId();
        if (StrUtil.isBlankIfStr(tenantId)) {
            throw new CustomException("系统错误,租户ID不能为空");
        }
        SysTenantEntity entity = tenantService.selectSysTenantByTenantId(tenantId);
        if (entity == null) {
            throw new CustomException("系统错误,租户ID不能为空");
        }
        WxMpMapConfigImpl config = new WxMpMapConfigImpl();
        config.setAppId(entity.getAppId());
        config.setSecret(entity.getSecret());
        wxMpService.addConfigStorage(entity.getAppId(), config);
        return wxMpService.switchoverTo(entity.getAppId());
    }

    public WxPayService getWxPay() {
        String tenantId = SecurityUtils.getTenantId();
        if (StrUtil.isBlankIfStr(tenantId)) {
            throw new CustomException("系统错误,租户ID不能为空");
        }
        SysTenantEntity entity = tenantService.selectSysTenantByTenantId(tenantId);
        if (entity == null) {
            throw new CustomException("系统错误,租户ID不能为空");
        }
        if (StringUtils.isEmpty(entity.getMchId())) {
            throw new CustomException("商户号不能为空，请联系平台方进行配置");
        }
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(StringUtils.trimToNull(entity.getAppId()));
        payConfig.setMchId(StringUtils.trimToNull(entity.getMchId()));
        payConfig.setMchKey(StringUtils.trimToNull(entity.getMchKey()));

        payConfig.setNotifyUrl(StringUtils.trimToNull(WeChatConstants.NOTIFY_URL));
        payConfig.setTradeType("JSAPI");
        payConfig.setSignType("MD5");
        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }


    public void sendBalanceMessage(PlayOrderInfoEntity order) {
        PlayCustomUserInfoEntity customUserInfo = customUserInfoService.selectById(order.getPurchaserBy());
        String touser = customUserInfo.getOpenid();
        SysTenantEntity tenant = tenantService.selectSysTenantByTenantId(order.getTenantId());
        String tenantKey = tenant.getTenantKey();
        String url = "http://" + tenantKey + ".july.hucs.top/user/";
        String template_id = tenant.getCzcgtzTemplateId();

        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        templateMessage.setTemplateId(template_id);
        templateMessage.setToUser(touser);
        templateMessage.setUrl(url);
        List<WxMpTemplateData> data = new ArrayList<>();
        data.add(new WxMpTemplateData("thing18", "陪陪船票"));
        data.add(new WxMpTemplateData("amount4", order.getOrderMoney().toString()));
        data.add(new WxMpTemplateData("phrase5", "船票充值"));
        data.add(new WxMpTemplateData("amount10", customUserInfo.getAccountBalance().toString()));
        templateMessage.setData(data);
        try {
            proxyWxMpService().getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);

        }
    }

    /**
     * 通过微信公众号发送消息
     *
     * @param tenantId    租户ID
     * @param openId      消息接收人openID
     * @param userType    用户类型，0:顾客，1:店员
     * @param nickName    消息内容-消息接收人昵称
     * @param orderNo     消息内容-订单编号
     * @param orderId     消息内容-订单ID
     * @param orderAmount 消息内容-订单金额
     * @author 杭州世平信息科技有限公司-xuhq
     * @since 2024/7/31 10:51
     **/
    public void sendOrderMessage(String tenantId, String openId, String userType, String nickName, String orderNo, String orderId, String orderAmount) {
        SysTenantEntity tenant = tenantService.selectSysTenantByTenantId(tenantId);
        String template_id = tenant.getSdxddtzTemplateId();
        String tenantKey = tenant.getTenantKey();
        String url = "http://" + tenantKey + ".july.hucs.top/" + ("0".equals(userType) ? "user/#/orderDetail/" : "clerk/#/orderDetail/") + orderId;
        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        templateMessage.setTemplateId(template_id);
        templateMessage.setToUser(openId);
        templateMessage.setUrl(url);
        List<WxMpTemplateData> data = new ArrayList<>();
        data.add(new WxMpTemplateData("amount2", orderAmount));
        data.add(new WxMpTemplateData("thing12", nickName));
        data.add(new WxMpTemplateData("character_string5", orderNo));
        data.add(new WxMpTemplateData("time4", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")));
        templateMessage.setData(data);
        try {
            proxyWxMpService().getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);

        }

    }

    public void sendCheckMessage(PlayClerkUserReviewInfoEntity entity, PlayClerkUserInfoEntity userInfo, String reviewState) {
        String touser = userInfo.getOpenid();

        SysTenantEntity tenant = tenantService.selectSysTenantByTenantId(userInfo.getTenantId());
        String template_id = tenant.getRzsqshtxTemplateId();
        String tenantKey = tenant.getTenantKey();
        String url = "http://" + tenantKey + ".july.hucs.top/clerk/";

        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        templateMessage.setTemplateId(template_id);
        templateMessage.setToUser(touser);
        templateMessage.setUrl(url);
        List<WxMpTemplateData> data = new ArrayList<>();
        data.add(new WxMpTemplateData("short_thing7", reviewState.equals("1") ? "通过" : "拒绝"));
        data.add(new WxMpTemplateData("thing2", entity.getNickname()));
        data.add(new WxMpTemplateData("thing11", entity.getWeiChatCode()));
        data.add(new WxMpTemplateData("time8", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")));
        templateMessage.setData(data);
        try {
            proxyWxMpService().getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);

        }

    }
}
