package com.chinaweal.aiccs.aiccs.punishment.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chinaweal.aiccs.aiccs.punishment.entity.PunishmentMeasureFeedbackLog;
import com.chinaweal.aiccs.aiccs.punishment.entity.PunishmentSearchLog;
import com.chinaweal.aiccs.aiccs.punishment.entity.vo.PunishmentNameListVO;
import com.chinaweal.aiccs.aiccs.punishment.entity.vo.PunishmentSearchResultVO;
import com.chinaweal.aiccs.aiccs.punishment.service.IPunishmentMeasureFeedbackLogService;
import com.chinaweal.aiccs.aiccs.punishment.service.IPunishmentSearchLogService;
import com.chinaweal.aiccs.aiccs.punishment.service.JointPunishmentApiService;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.DesSupport;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.redis.RedisService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 联合惩戒Api Service 实现类
 *
 * @author lroyia
 * @since 2025/5/7 13:59
 **/
@Slf4j
@Service
public class JointPunishmentServiceImpl implements JointPunishmentApiService {

    @Value("${punishment.api.host}")
    private String host;
    @Value("${punishment.api.auth.systemName}")
    private String systemName;
    @Value("${punishment.api.auth.orgName}")
    private String orgName;
    @Value("${punishment.api.auth.tyshxydm}")
    private String tyshxydm;
    @Value("${punishment.api.auth.account}")
    private String account;
    @Value("${punishment.api.auth.password}")
    private String password;
    @Value("${punishment.api.auth.deckey}")
    private String deckey;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisService redisService;

    private final static String TOKEN_KEY = "punishment:api:token";
    private final static String TOKEN_TIME_KEY = "punishment:api:token:time";
    private final static String TOKEN_RUNNING_KEY = "punishment:api:token:running";

    @Autowired
    private IPunishmentSearchLogService punishmentSearchLogService;
    @Autowired
    private IPunishmentMeasureFeedbackLogService punishmentMeasureFeedbackLogService;


    /**
     * 请求token
     *
     * @return token
     * @author lroyia
     * @since 2025年5月7日14:48:58
     */
    private String getToken() {
        String token = redisService.get(TOKEN_KEY);
        if (StringUtils.isNotBlank(token)) {
            String timestamp = redisService.get(TOKEN_TIME_KEY);
            long time = Long.parseLong(timestamp);
            if (System.currentTimeMillis() - time < 60 * 1000 * 25) {
                return token;
            }
        }
        if (redisService.exists(TOKEN_RUNNING_KEY)) {
            return token;
        }
        redisService.set(TOKEN_RUNNING_KEY, Constant.TRUE_1_STR, 120);
        try {
            // 1. 创建请求头，指定JSON格式
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            // 2. 构造JSON请求体（可以是Map、POJO或JSON字符串）
            Map<String, Object> paramMap = new HashMap<>(5);
            paramMap.put("systemName", systemName);
            paramMap.put("orgName", orgName);
            paramMap.put("tyshxydm", tyshxydm);
            try {
                paramMap.put("account", DesSupport.encrypt(account, StandardCharsets.UTF_8, deckey));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            try {
                paramMap.put("password", DesSupport.encrypt(password, StandardCharsets.UTF_8, deckey));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            // 3. 封装请求实体
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(paramMap, headers);
            ResponseEntity<JSONObject> response = restTemplate.postForEntity(host + "/gzcreditApi/external-api/web/lhjc/getToken", request, JSONObject.class);
            if (response.getStatusCode() != HttpStatus.OK) {
                log.error("请求失败，响应码：{}", response.getStatusCode().value());
                return token;
            }
            log.info("请求token参数：{}", JSONObject.toJSONString(paramMap));
            JSONObject body = response.getBody();
            if (body != null) {
                body = body.getJSONObject("body");
                if (StringUtils.equals(Constant.TRUE_1_STR, body.getString("status"))) {
                    token = body.getString("token");
                    redisService.set(TOKEN_KEY, token, 60 * 30);
                    redisService.set(TOKEN_TIME_KEY, String.valueOf(System.currentTimeMillis()), 60 * 30);
                } else {
                    log.error("获取AccessToken失败，响应体：{}", body);
                }
            }
        } finally {
            redisService.remove(TOKEN_RUNNING_KEY);
        }
        return token;
    }

    @Override
    public PunishmentSearchResultVO searchPunishmentNameList(int xxztlb, String xxztmc, String xxzthm) {
        String token = getToken();
        Map<String, Object> paramMap = new HashMap<>(12);
        String busiNo = UUID.randomUUID().toString().replace(Constant.LINE, StringUtils.EMPTY);
        AICUser user = SSOUtil.getUser();
        paramMap.put("token", token);
        paramMap.put("busiNo", busiNo);
        paramMap.put("actcode", "RED_BLACK_JCCS_DATA");
        paramMap.put("systemName", systemName);
        paramMap.put("orgName", orgName);
        paramMap.put("tyshxydm", tyshxydm);
        paramMap.put("xxztlb", xxztlb);
        paramMap.put("xxztmc", xxztmc.trim());
        if (StringUtils.isNotBlank(xxzthm)) {
            xxzthm = xxzthm.trim();
            paramMap.put("xxzthm", xxzthm);
        }
        // TODO: 事项编码补充
        log.info("联合惩戒搜索请求参数：{}", JSONObject.toJSONString(paramMap));
        PunishmentSearchLog searchLog = new PunishmentSearchLog()
                .setCxcode(busiNo).setXxztlb(xxztlb)
                .setXxzthm(xxzthm).setXxztmc(xxztmc).setRequestBody(JSONObject.toJSONString(paramMap))
                .setCreatedBy(user.getPrimaryKey()).setCreatedTime(LocalDateTime.now());

        // 1. 创建请求头，指定JSON格式
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 2. 封装请求实体
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(paramMap, headers);
        searchLog.setLogStatus(Constant.FALSE_0_STR);
        PunishmentSearchResultVO result = new PunishmentSearchResultVO();
        result.setBusiNo(busiNo);
        try {
            ResponseEntity<JSONObject> response = restTemplate.postForEntity(host + "/gzcreditApi/external-api/web/lhjc/measureList", request, JSONObject.class);
            if (response.getStatusCode() != HttpStatus.OK) {
                searchLog.setResponseResult("请求失败，响应码：" + response.getStatusCode().value());
                log.error("请求失败，响应码：{}", response.getStatusCode().value());
                throw new BusinessException("请求远端接口失败");
            }
            JSONObject body = response.getBody();
            if (body != null) {
                body = body.getJSONObject("body");
                searchLog.setResponseResult(body.toJSONString());
                if (StringUtils.equals("000000", body.getString("code"))) {
                    JSONArray data = body.getJSONArray("mds");
                    if (data != null) {
                        searchLog.setLogStatus(Constant.TRUE_1_STR);
                        List<PunishmentNameListVO> list = JSONObject.parseArray(data.toJSONString(), PunishmentNameListVO.class);
                        result.setResult(list);
                        return result;
                    }
                } else {
                    throw new BusinessException("查询失败，" + body.getString("message"));
                }
            }
        } finally {
            punishmentSearchLogService.save(searchLog);
        }
        return result;
    }

    @Override
    public PunishmentMeasureFeedbackLog feedback(PunishmentMeasureFeedbackLog feedbackLog) {
        String token = getToken();
        String busiNo = UUID.randomUUID().toString().replace(Constant.LINE, StringUtils.EMPTY);
        Map<String, Object> paramMap = new HashMap<>(12);
        paramMap.put("token", token);
        paramMap.put("busiNo", busiNo);
        paramMap.put("systemName", systemName);
        paramMap.put("orgName", orgName);
        paramMap.put("creditCode", tyshxydm);
        paramMap.put("sid", feedbackLog.getSid());
        paramMap.put("mdmc", feedbackLog.getMdmc());
        paramMap.put("ztmc", feedbackLog.getZtmc());
        paramMap.put("ztlb", feedbackLog.getZtlb());
        paramMap.put("jclb", feedbackLog.getJclb());
        if (StringUtils.isNotBlank(feedbackLog.getTyshxydm())) {
            paramMap.put("tyshxydm", feedbackLog.getTyshxydm());
        }
        if (StringUtils.isNotBlank(feedbackLog.getQyzch())) {
            paramMap.put("qyzch", feedbackLog.getQyzch());
        }
        if (StringUtils.isNotBlank(feedbackLog.getZzjgdm())) {
            paramMap.put("zzjgdm", feedbackLog.getZzjgdm());
        }
        if (StringUtils.isNotBlank(feedbackLog.getZjlx())) {
            paramMap.put("zjlx", feedbackLog.getZjlx());
        }
        if (StringUtils.isNotBlank(feedbackLog.getZjhm())) {
            paramMap.put("zjhm", feedbackLog.getZjhm());
        }
        paramMap.put("csnr", feedbackLog.getCsnr());
        paramMap.put("sjje", feedbackLog.getSjje());
        paramMap.put("jcsm", feedbackLog.getJcsm());
        paramMap.put("qlbm", feedbackLog.getQlbm());
        paramMap.put("qlmc", feedbackLog.getQlmc());
        paramMap.put("cxcode", feedbackLog.getCxcode());
        AICUser user = SSOUtil.getUser();
        feedbackLog.setCreatedBy(user.getPrimaryKey());
        feedbackLog.setCreatedTime(LocalDateTime.now());
        log.info("联合惩戒反馈请求参数：{}", JSONObject.toJSONString(paramMap));
        // 1. 创建请求头，指定JSON格式
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 2. 封装请求实体
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(paramMap, headers);
        ResponseEntity<JSONObject> response = restTemplate.postForEntity(host + "/gzcreditApi/external-api/web/lhjc/feedback", request, JSONObject.class);
        if (response.getStatusCode() != HttpStatus.OK) {
            log.error("请求失败，响应码：{}", response.getStatusCode().value());
            throw new BusinessException("请求远端接口失败");
        }
        JSONObject body = response.getBody();
        if (body != null) {
            body = body.getJSONObject("body");
            if (StringUtils.equals("000000", body.getString("code"))) {
                feedbackLog.setBusiNo(busiNo);
                punishmentMeasureFeedbackLogService.save(feedbackLog);
            } else {
                throw new BusinessException("提交失败，" + body.getString("message"));
            }
        }
        return feedbackLog;
    }
}
