package com.czg.service.product.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.czg.exception.CzgException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信公众号消息推送
 *
 * @author tankaikai
 * @since 2025-03-14 14:56
 */
@Data
@Slf4j
@Component
public class WxAccountUtil {

    //银收客公众号推送
    @Value("${wx.ysk.appId}")
    private String appId = "wx212769170d2c6b2a";
    @Value("${wx.ysk.secrete}")
    private String secrete = "8492a7e8d55bbb1b57f5c8276ea1add0";
    @Value("${wx.ysk.operationMsgTmpId}")
    private String operationMsgTmpId;
    @Value("${wx.ysk.warnMsgTmpId}")
    private String warnMsgTmpId;


    static LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();

    static {
        linkedHashMap.put("40001", "获取 access_token 时 AppSecret 错误，或者 access_token 无效。请开发者认真比对 AppSecret 的正确性，或查看是否正在为恰当的公众号调用接口");
        linkedHashMap.put("40003", "不合法的 OpenID ，请开发者确认 OpenID （该用户）是否已关注公众号，或是否是其他公众号的 OpenID");
        linkedHashMap.put("40014", "不合法的 access_token ，请开发者认真比对 access_token 的有效性（如是否过期），或查看是否正在为恰当的公众号调用接口");
        linkedHashMap.put("40037", "不合法的 template_id");
        linkedHashMap.put("43101", "用户未订阅消息");
        linkedHashMap.put("43107", "订阅消息能力封禁");
        linkedHashMap.put("43108", "并发下发消息给同一个粉丝");
        linkedHashMap.put("45168", "命中敏感词");
        linkedHashMap.put("47003", "参数错误");
    }

    public void sendOperationMsg(List<String> openIdList, String userName, String operationDesc) {
        openIdList.forEach(openId -> {
            Map<String, Object> data = Map.of(
                    "thing19", Map.of("value", userName),
                    "thing8", Map.of("value", StrUtil.sub(operationDesc, 0, 20)),
                    "time21", Map.of("value", DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"))
            );
            try {
                sendTemplateMsg("敏感操作", operationMsgTmpId, openId, data);
            } catch (Exception e) {
                log.error("发送失败, openId: {}, 响应: {}", openId, e.getMessage());
            }
        });
    }

    public void sendStockMsg(String typeName, String shopName, String productName, BigDecimal stockNum, String openId) {
        if (stockNum.compareTo(BigDecimal.ZERO) <= 0) {
            stockNum = BigDecimal.ZERO;
        }
        String stockNumStr = stockNum.toPlainString();
        Map<String, Object> data = Map.of(
                //品名
                "thing34", Map.of("value", typeName),
                //商品名称
                "thing4", Map.of("value", productName),
                //商品数量
                "number5", Map.of("value", stockNumStr),
                //商家名称
                "thing22", Map.of("value", shopName)
        );
        try {
            sendTemplateMsg("库存预警", warnMsgTmpId, openId, data);
        } catch (Exception e) {
            log.error("发送失败, openId:{}, msg: {}", openId, e.getMessage());
        }
    }

    public String getAccessToken() {
        String resp = HttpUtil.get(StrUtil.format("https://access-token.sxczgkj.com/accessToken?appId={}&appSecret={}", appId, secrete));
//       响应 {"accessToken":"100_6C_jltHANT1y2Fot5PXKFDzPXTyWumCsao0oMoNRvJUTuxS0IOVO4nBmjdmx5dZfYItShFVSAKYzNDf7ZGLPlx52ii1Y1qerrbbSmIiLWCrec5qjBY4gV5Tfv8YKKTdABAEEN","appId":"wx212769170d2c6b2a"}
        if(StrUtil.isNotBlank(resp)){
            JSONObject respInfo = JSONObject.parseObject(resp);
            return respInfo.getString("accessToken");
        }else {
            String resp1 = HttpUtil.get(StrUtil.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}", appId, secrete));
            JSONObject respInfo = JSONObject.parseObject(resp1);
            if (!respInfo.containsKey("access_token")) {
                log.warn("银收客 公众号获取token失败, 响应内容: {}", resp1);
                throw new CzgException(resp);
            }
            return respInfo.getString("access_token");
        }
    }

    public JSONObject sendTemplateMsg(String detail, String templateId, String toUserOpenId, Map<String, Object> data) {
        log.info("银收客公众号消息推送，消息类型：{} 接收用户openId: {}, 消息数据: {}", detail, toUserOpenId, data);
        String accessToken = getAccessToken();
        JSONObject object1 = new JSONObject();
        object1.put("template_id", templateId);
        object1.put("touser", toUserOpenId);
        object1.put("data", data);

        String response = HttpRequest.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".concat(accessToken)).body(object1.toString()).execute().body();
        log.info("银收客公众号消息推送，响应内容:{}", response);
        JSONObject resObj = JSONObject.parseObject(response);
        if (ObjectUtil.isNotEmpty(resObj) && ObjectUtil.isNotNull(resObj) && "0".equals(resObj.get("errcode") + "")) {
            return resObj;
        }
        throw new CzgException(linkedHashMap.getOrDefault(resObj.get("errcode") + "", "未知错误"));
    }
//
//    public static void main(String[] args) {
////        String appId = "wx212769170d2c6b2a";
////        String secrete = "8492a7e8d55bbb1b57f5c8276ea1add0";
////        String resp = HttpUtil.get(StrUtil.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}", appId, secrete));
////        System.out.println(resp);
//
//        String accessToken = "100_ZGAKcjfJBViY-W_4TPDRnZJvnveRsVFAQzUY0SeosUMfVId4LN-TLD1Ajp-7t7aZL4yiBIjbAaTiK-FQ4S1KnbaDDobfYjD2jqMvbgXHFxiActwaDmdJfYpt6QcWNKcAHAQHE";
//        JSONObject object1 = new JSONObject();
//        object1.put("template_id", "C08OUr80x6wGmUN1zpFhSZyFA2G6b9_jiZgEppzLB70");
//        object1.put("touser", "ojC-S6r36TauETXV8G4e6J-U8Qa0");
//        object1.put("data", Map.of(
//                //品名
//                "thing34", Map.of("value", "耗材"),
//                //商品名称
//                "thing4", Map.of("value", "名称"),
//                //商品数量
//                "number5", Map.of("value", 1),
//                //商家名称
//                "thing22", Map.of("value", "412341324")
//        ));
//
//        String response = HttpRequest.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".concat(accessToken)).body(object1.toString()).execute().body();
//        log.info("银收客公众号消息推送，响应内容:{}", response);
//        JSONObject resObj = JSONObject.parseObject(response);
//    }
}
