package com.njzscloud.supervisory.wxPay.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.security.util.SecurityUtil;
import com.njzscloud.supervisory.sys.user.pojo.entity.UserEntity;
import com.njzscloud.supervisory.sys.user.service.UserService;
import com.njzscloud.supervisory.wxPay.contant.TempType;
import com.njzscloud.supervisory.wxPay.contant.TemplateID;
import com.njzscloud.supervisory.wxPay.contant.WxApiConfig;
import com.njzscloud.supervisory.wxPay.dto.TemplateData;
import com.njzscloud.supervisory.wxPay.param.TemplateMessageParam;
import com.njzscloud.supervisory.wxPay.service.WechatTemplateMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 微信消息推送服务实现类
 * @author ljw
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WechatTemplateMessageServiceImpl implements WechatTemplateMessageService {

    private final UserService userService;

    /**
     * 处理微信模板消息thing字段的字符长度限制（最多20个字符）
     * @param content 原始内容
     * @return 处理后的内容
     */
    private String truncateForThingField(String content) {
        if (Strings.isNullOrEmpty(content)) {
            return content;
        }
        if (content.length() > 20) {
            return content.substring(0, 17) + "...";
        }
        return content;
    }

    @Override
    public void bind(String code) {
        // 使用Code换取Access Token和OpenID
        String tokenUrl = WxApiConfig.OAUTH_URL + "appid=" + WxApiConfig.APP_ID + "&secret=" + WxApiConfig.APP_SECRET +
                "&code=" + code + "&grant_type=authorization_code";

        // 使用HTTP客户端发起请求
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(tokenUrl, String.class);

        // 解析微信返回的JSON数据
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (null == jsonObject) {
            throw Exceptions.clierr("获取openid失败");
        }
        String openId = jsonObject.getString("openid");
//        String accessToken = jsonObject.getString("access_token");
        // 返回中通常还包含 expires_in, refresh_token等字段[citation:1]

        if (openId == null || openId.isEmpty()) {
            // 错误处理
            String errCode = (String) jsonObject.get("errcode");
            String errMsg = (String) jsonObject.get("errmsg");
            log.info("获取OpenID失败: " + errCode + " - " + errMsg);
            throw Exceptions.clierr("获取openid失败");
        }

        log.info("用户的OpenID是: " + openId);

        // 将openId与你的系统用户关联
        UserEntity userEntity = new UserEntity();
        userEntity.setId(SecurityUtil.currentUserId());
        userEntity.setOpenid(openId);
        userService.updateById(userEntity);

    }

    @Override
    public Map<String, Object> key(String code) {
        RestTemplate restTemplate = new RestTemplate();
        // 1. 获取Access Token
        String accessToken = getAccessToken();
        String response = restTemplate.postForObject(WxApiConfig.TICKET_URL + accessToken + "&type=jsapi", "", String.class);
        // 5. 处理响应
        JSONObject jsonResponse = JSONObject.parseObject(response);
        if (null == jsonResponse) {
            throw Exceptions.clierr("获取ticket失败，jsonResponse为null");
        }
        if (jsonResponse.getIntValue("errcode") != 0) {
            log.error("发送模板消息失败: " + jsonResponse.getString("errmsg"));
        }
        String jsapi_ticket = jsonResponse.getString("ticket");
        String timestamp = Long.toString(System.currentTimeMillis() / 1000); // 必填，生成签名的时间戳
        String nonceStr = UUID.randomUUID().toString().replaceAll("-", ""); // 必填，生成签名的随机串
        // 注意这里参数名必须全部小写，且必须有序
        String url = WxApiConfig.REDIRECT_URI + "?code=" + code + "&state=STATE";
        log.info("url: " + url);
        String signature = getSignature(jsapi_ticket, timestamp, nonceStr, url);
        Map<String, Object> map = new HashMap<>();
        map.put("appId", WxApiConfig.APP_ID);
        map.put("timestamp", timestamp);
        map.put("nonceStr", nonceStr);
        map.put("signature", signature);

        return map;
    }

    @Override
    public void sendTemplateMessage(TemplateMessageParam param) {
        UserEntity userEntity = userService.getById(param.getUserId());
       // UserEntity userEntity = new UserEntity();
       // userEntity.setOpenid("owC-r2Bf1axK1C2MQ6nOaCDbKuHw");
        if (!Strings.isNullOrEmpty(userEntity.getOpenid())) {
            Map<String, TemplateData> data;
            if (TempType.TRANS_COMPANY.getVal().equals(param.getTempType())) {
                // 通知清运公司指派司机
                // 构建模板数据
                data = new HashMap<>();
                data.put("character_string2", new TemplateData(param.getSn()));
                data.put("thing19", new TemplateData(param.getGoodsName()));
                data.put("thing4", new TemplateData(truncateForThingField(param.getStartAddress())));
                sendMessage(userEntity.getOpenid(), TemplateID.TRANS_COMPANY_TEMP_ID, data, null, "pages/basicPage/publicOrder");
            } else if (TempType.DRIVER.getVal().equals(param.getTempType())) {
                // 通知司机
                // 构建模板数据
                data = new HashMap<>();
                data.put("character_string5", new TemplateData(param.getSn()));
                data.put("thing7", new TemplateData(param.getDriverName()));
                data.put("thing2", new TemplateData(truncateForThingField(param.getStartAddress())));
                data.put("thing3", new TemplateData(param.getEndAddress()));
                sendMessage(userEntity.getOpenid(), TemplateID.DRIVER_TEMP_ID, data, null, "pages/transportPage/jointOrder");
            } else if (TempType.AUDIT_PENDING.getVal().equals(param.getTempType())) {
                // 待审核
                // 构建模板数据
                data = new HashMap<>();
                data.put("character_string2", new TemplateData(param.getSn()));
                data.put("thing3", new TemplateData(truncateForThingField(param.getCfCompanyName())));
                data.put("thing5", new TemplateData(param.getGoodsName()));
                data.put("thing6", new TemplateData(truncateForThingField(param.getCompanyName())));
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm");
                String formattedTime = param.getCreateTime().format(formatter);
                data.put("time1", new TemplateData(formattedTime));
                sendMessage(userEntity.getOpenid(), TemplateID.AUDIT_PENDING, data, null, "pages/adminPage/jianGuan");
            } else if (TempType.AUDIT_OK.getVal().equals(param.getTempType())) {
                // 审核通过
                // 构建模板数据
                data = new HashMap<>();
                data.put("character_string1", new TemplateData(param.getSn()));
                data.put("thing4", new TemplateData(param.getGoodsName()));
                data.put("thing8", new TemplateData(param.getDriverName()));
                data.put("car_number7", new TemplateData(param.getLicensePlate()));
                data.put("thing3", new TemplateData(param.getEndAddress()));
                sendMessage(userEntity.getOpenid(), TemplateID.AUDIT_OK, data, null, "pages/transportPage/jointOrder");
            } else if (TempType.AUDIT_REJECT.getVal().equals(param.getTempType())) {
                // 审核驳回
                // 构建模板数据
                data = new HashMap<>();
                data.put("character_string8", new TemplateData(param.getSn()));
                data.put("thing4", new TemplateData(param.getGoodsName()));
                data.put("thing2", new TemplateData(truncateForThingField(param.getStartAddress())));
                sendMessage(userEntity.getOpenid(), TemplateID.AUDIT_REJECT, data, null, "pages/transportPage/jointOrder");
            }
        } else {
            log.info("未查询到用户信息或不存在openid，无法通知");
        }

    }

    /**
     * 发送模板消息
     */
    public void sendMessage(String openId, String templateId,
                            Map<String, TemplateData> data,
                            String url, String miniProgram) {
        // 1. 获取Access Token
        String accessToken = getAccessToken();
        if (Strings.isNullOrEmpty(accessToken)) {
            log.error("获取Access Token失败");
            return;
        }

        // 2. 构建请求数据
        JSONObject requestData = new JSONObject();
        requestData.put("touser", openId);
        requestData.put("template_id", templateId);

        if (url != null) {
            // 点击消息跳转的URL
            requestData.put("url", url);
        } else {
            requestData.put("url", "https://supervisory.njzscloud.com");
        }

        if (miniProgram != null) {
            JSONObject miniProgramObj = new JSONObject();
            miniProgramObj.put("appid", WxApiConfig.XCX_APP_ID);
            miniProgramObj.put("pagepath", miniProgram);
            requestData.put("miniprogram", miniProgramObj);
        }

        // 3. 构建模板数据
        JSONObject dataObj = new JSONObject();
        for (Map.Entry<String, TemplateData> entry : data.entrySet()) {
            JSONObject item = new JSONObject();
            item.put("value", entry.getValue().getValue());
            if (entry.getValue().getColor() != null) {
                item.put("color", entry.getValue().getColor());
            }
            dataObj.put(entry.getKey(), item);
        }
        requestData.put("data", dataObj);
        log.info("发送模板消息参数为：{}", JSONObject.toJSONString(requestData));

        // 4. 发送请求
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        String response = restTemplate.postForObject(WxApiConfig.SEND_TEMPLATE_MSG_URL + accessToken, JSONObject.toJSONString(requestData), String.class);

        // 5. 处理响应
        JSONObject jsonResponse = JSONObject.parseObject(response);
        if (null == jsonResponse) {
            log.error("发送模板消息失败，jsonResponse为null");
            return;
        }
        if (jsonResponse.getIntValue("errcode") != 0) {
            log.error("发送模板消息失败: " + jsonResponse.getString("errmsg"));
        }
    }

    /**
     * 获取Access Token
     */
    private String getAccessToken() {
        String tokenUrl = WxApiConfig.GET_TOKEN_URL + WxApiConfig.APP_ID + "&secret=" + WxApiConfig.APP_SECRET;

        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(tokenUrl, String.class);
        JSONObject jsonResponse = JSONObject.parseObject(response);
        if (null == jsonResponse) {
            log.error("获取Access Token失败");
            return "";
        }
        if (jsonResponse.getIntValue("errcode") != 0) {
            log.error("发送模板消息失败: " + jsonResponse.getString("errmsg"));
            return "";
        }
        return jsonResponse.getString("access_token");
    }

    public static String getSignature(String jsapi_ticket, String timestamp,
                                      String nonce, String js_url) {
//         对 jsapi_ticket、 timestamp 和 nonce 按字典排序 对所有待签名参数按照字段名的 ASCII
//         码从小到大排序（字典序）后，使用 URL 键值对的格式（即key1=value1&key2=value2…）拼接成字符串
//         string1。这里需要注意的是所有参数名均为小写字符。 接下来对 string1 作 sha1 加密，字段名和字段值都采用原始值，不进行
//         URL 转义。即 signature=sha1(string1)。
//         如果没有按照生成的key1=value&key2=value拼接的话会报错
        String[] paramArr = new String[]{"jsapi_ticket=" + jsapi_ticket, "timestamp=" + timestamp, "noncestr=" + nonce,
                "url=" + js_url};
        Arrays.sort(paramArr);
        // 将排序后的结果拼接成一个字符串
        String content = paramArr[0].concat("&" + paramArr[1]).concat("&" + paramArr[2]).concat("&" + paramArr[3]);
        log.info("拼接之后的content为:" + content);
        String genSignature = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            // 对拼接后的字符串进行 sha1 加密
            byte[] digest = md.digest(content.getBytes());
            genSignature = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 将 sha1 加密后的字符串与 signature 进行对比
        if (genSignature != null) {
            return genSignature;// 返回signature
        } else {
            return "false";
        }
    }

    /**
     * 将字节数组转换为十六进制字符串
     */
    private static String byteToStr(byte[] byteArray) {
        StringBuilder strDigest = new StringBuilder();
        for (byte b : byteArray) {
            strDigest.append(byteToHexStr(b));
        }
        return strDigest.toString();
    }

    /**
     * 将字节转换为十六进制字符串
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        return new String(tempArr);
    }

}
