package com.saye.hospitalgd.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.saye.hospitalgd.commons.string.StringDUtil;
import com.saye.hospitalgd.model.FinanceUser;
import com.saye.hospitalgd.service.NotifyService;
import com.saye.hospitalgd.service.system.FinanceUserService;
import com.saye.hospitalgd.service.system.ServiceParamsService;
import com.saye.hospitalgd.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * @author thuang
 * @version 1.0
 * @description: 消息推送服务实现类
 * @date 2024/12/19 18:00
 */
@Service
public class NotifyServiceImpl implements NotifyService {

    private static final Logger log = LoggerFactory.getLogger(NotifyServiceImpl.class);

    @Autowired
    private FinanceUserService financeUserService;

    @Autowired
    private ServiceParamsService serviceParamsService;

    @Override
    public void sendReconciliationNotify(String tradeDate, String status, String message) throws Exception {
        try {
            // 获取所有启用的财务人员
            List<FinanceUser> financeUsers = financeUserService.findActiveFinanceUsers();
            
            if (financeUsers == null || financeUsers.isEmpty()) {
                log.info("没有启用的财务人员，跳过消息推送");
                return;
            }

            // 获取中转服务地址
            List<HashMap<Object, Object>> serviceParams = serviceParamsService.findParamValByParamCode("hgd_dmz");
            String transferUrl = StringDUtil.changeNullToEmpty(serviceParams.get(0).get("PARAM_VAL"));
            if (transferUrl == null || transferUrl.trim().isEmpty()) {
                log.error("未配置中转服务地址(hgd_dmz)");
                return;
            }

            // 构建消息推送URL
            String notifyUrl = transferUrl.endsWith("/") ? 
                transferUrl + "sendNotifyYJJ" : 
                transferUrl + "/sendNotifyYJJ";

            // 为每个财务人员发送通知
            for (FinanceUser financeUser : financeUsers) {
                if (financeUser.getOpenId() != null && !financeUser.getOpenId().trim().isEmpty()) {
                    sendNotifyToFinanceUser(financeUser, tradeDate, status, message, notifyUrl);
                } else {
                    log.warn("财务人员 {} 没有OpenID，跳过消息推送", financeUser.getName());
                }
            }

        } catch (Exception e) {
            log.error("发送对账通知失败", e);
            throw e;
        }
    }

    /**
     * 发送通知给指定财务人员
     * @param financeUser 财务人员信息
     * @param tradeDate 对账日期
     * @param status 对账状态
     * @param message 对账消息
     * @param notifyUrl 通知URL
     */
    private void sendNotifyToFinanceUser(FinanceUser financeUser, String tradeDate, String status, 
                                       String message, String notifyUrl) {
        try {
            // 构建通知参数
            HashMap<String, Object> notifyParams = new HashMap<>();
            notifyParams.put("openid", financeUser.getOpenId());
            notifyParams.put("tradeDate", tradeDate);
            notifyParams.put("status", status);
            notifyParams.put("message", message);
            notifyParams.put("userName", financeUser.getName());

            // 发送通知
            String response = HttpClientUtil.doPost(notifyUrl, notifyParams);
            log.debug("发送对账通知响应: " + response);

            // 增加空值检查
            if (response == null || response.trim().isEmpty()) {
                log.error("调用中转服务失败，返回为空，接收人: {}", financeUser.getName());
                return;
            }

            JSONObject jsonResponse = JSON.parseObject(response);
            // 兼容多种成功状态码格式
            Integer code = jsonResponse.getInteger("code");
            Integer errCode = jsonResponse.getInteger("errcode");
            Integer errCodeInt = jsonResponse.getInteger("errCode");
            
            // 判断成功条件：code=0 或 errcode=0 或 errCode=0 或 errCode="0"
            boolean isSuccess = (code != null && code == 0) || 
                               (errCode != null && errCode == 0) ||
                               (errCodeInt != null && errCodeInt == 0) ||
                               "0".equals(jsonResponse.getString("errCode"));
            
            if (isSuccess) {
                log.info("对账通知发送成功，接收人: {}", financeUser.getName());
            } else {
                // 兼容多种错误消息字段：msg/errMsg
                String errorMsg = jsonResponse.getString("msg");
                if (errorMsg == null || errorMsg.trim().isEmpty()) {
                    errorMsg = jsonResponse.getString("errMsg");
                }
                log.error("对账通知发送失败，接收人: {}, 错误信息: {}", 
                    financeUser.getName(), errorMsg);
            }

        } catch (Exception e) {
            log.error("发送对账通知异常，接收人: {}", financeUser.getName(), e);
        }
    }

    @Override
    public String getUserOpenId(String wechatName) throws Exception {
        try {
            // 获取中转服务地址
            List<HashMap<Object, Object>> serviceParams = serviceParamsService.findParamValByParamCode("hgd_dmz");
            String transferUrl = StringDUtil.changeNullToEmpty(serviceParams.get(0).get("PARAM_VAL"));
            if (transferUrl == null || transferUrl.trim().isEmpty()) {
                throw new Exception("未配置中转服务地址(hgd_dmz)");
            }

            // 构建获取OpenID的URL
            String openIdUrl = transferUrl.endsWith("/") ? 
                transferUrl + "getUserOpenId" : 
                transferUrl + "/getUserOpenId";

            // 构建请求参数
            HashMap<String, Object> params = new HashMap<>();
            params.put("wechatName", wechatName);

            // 发送请求
            String response = HttpClientUtil.doPost(openIdUrl, params);
            log.debug("获取OpenID响应: " + response);

            // 增加空值检查
            if (response == null || response.trim().isEmpty()) {
                throw new Exception("调用中转服务失败，返回为空。请检查中转服务地址是否正确或网络是否可达");
            }

            JSONObject jsonResponse = JSON.parseObject(response);
            // 兼容两种返回格式：code/errCode
            Integer code = jsonResponse.getInteger("code");
            Integer errCode = jsonResponse.getInteger("errCode");
            
            // 判断成功条件：code=0 或 errCode="0"
            boolean isSuccess = (code != null && code == 0) || 
                               (errCode != null && errCode == 0) ||
                               "0".equals(jsonResponse.getString("errCode"));
            
            if (isSuccess) {
                // 兼容两种数据字段：data/openid
                String openId = jsonResponse.getString("data");
                if (openId == null || openId.trim().isEmpty()) {
                    openId = jsonResponse.getString("openid");
                }
                
                if (openId != null && !openId.trim().isEmpty()) {
                    log.info("成功获取OpenID: {} for 微信名: {}", openId, wechatName);
                    return openId;
                } else {
                    throw new Exception("返回的OpenID为空");
                }
            } else {
                // 兼容两种错误消息字段：msg/errMsg
                String errorMsg = jsonResponse.getString("msg");
                if (errorMsg == null || errorMsg.trim().isEmpty()) {
                    errorMsg = jsonResponse.getString("errMsg");
                }
                throw new Exception("获取OpenID失败: " + errorMsg);
            }

        } catch (Exception e) {
            log.error("获取OpenID异常，微信名: {}", wechatName, e);
            throw e;
        }
    }

    @Override
    public String getUserOpenIdByPhone(String phone) throws Exception {
        try {
            // 获取中转服务地址
            List<HashMap<Object, Object>> serviceParams = serviceParamsService.findParamValByParamCode("hgd_dmz");
            String transferUrl = StringDUtil.changeNullToEmpty(serviceParams.get(0).get("PARAM_VAL"));
            if (transferUrl == null || transferUrl.trim().isEmpty()) {
                throw new Exception("未配置中转服务地址(hgd_dmz)");
            }

            // 构建获取OpenID的URL
            String openIdUrl = transferUrl.endsWith("/") ? 
                transferUrl + "getUserOpenId" : 
                transferUrl + "/getUserOpenId";


            // 构建请求参数
            HashMap<String, Object> params = new HashMap<>();
            params.put("phone", phone);
            params.put("yz", "joju@");

            // 发送请求
            String response = HttpClientUtil.doPost(openIdUrl, params);
            log.debug("根据手机号获取OpenID响应: " + response);

            // 增加空值检查
            if (response == null || response.trim().isEmpty()) {
                throw new Exception("调用中转服务失败，返回为空。请检查中转服务地址是否正确或网络是否可达");
            }

            JSONObject jsonResponse = JSON.parseObject(response);
            // 兼容两种返回格式：code/errCode
            Integer code = jsonResponse.getInteger("code");
            Integer errCode = jsonResponse.getInteger("errCode");
            
            // 判断成功条件：code=0 或 errCode="0"
            boolean isSuccess = (code != null && code == 0) || 
                               (errCode != null && errCode == 0) ||
                               "0".equals(jsonResponse.getString("errCode"));
            
            if (isSuccess) {
                String openId = jsonResponse.getString("openid");
                if (openId != null && !openId.trim().isEmpty()) {
                    log.info("成功根据手机号获取OpenID: {} for 手机号: {}", openId, phone);
                    return openId;
                } else {
                    throw new Exception("返回的OpenID为空");
                }
            } else {
                // 兼容两种错误消息字段：msg/errMsg
                String errorMsg = jsonResponse.getString("msg");
                if (errorMsg == null || errorMsg.trim().isEmpty()) {
                    errorMsg = jsonResponse.getString("errMsg");
                }
                throw new Exception("根据手机号获取OpenID失败: " + errorMsg);
            }

        } catch (Exception e) {
            log.error("根据手机号获取OpenID异常，手机号: {}", phone, e);
            throw e;
        }
    }
}


