package shop.alien.store.controller;

import com.alibaba.fastjson2.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiSort;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import shop.alien.entity.result.R;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Api(tags = {"ai审核"})
@ApiSort(9)
@CrossOrigin
@RestController
@RequestMapping("/aiAudit")
@RequiredArgsConstructor
@RefreshScope
public class AiAuditController {

    private final RestTemplate restTemplate;

    @Value("${third-party-user-name-admin.base-url}")
    private String userName;

    @Value("${third-party-user-name-admin.base-url}")
    private String userNameAdmin;

    @Value("${third-party-pass-word.base-url}")
    private String passWord;

    @Value("${third-party-login.base-url:http://192.168.2.250:9100/ai/user-auth-core/api/v1/auth/login}")
    private String loginUrl;

    @Value("${third-party-text-check.base-url:http://verify.ailien.shop:8099/api/v1/moderate}")
    private String aiTextCheckUrl;

    @Value("${third-party-content_compliance-check.base-url:http://verify.ailien.shop:8099/api/v1/moderate}")
    private String aiContentCheckUrl;

    @ApiOperation("ai文本审核")
    @ApiOperationSupport(order = 1)
    @GetMapping("/getAiAuditTextCheckResult")
    public R<JSONObject> getAiAuditTextCheckResult(String text) {
        String accessToken = fetchAiServiceToken();
        if (!StringUtils.hasText(accessToken)) {
            return R.fail("调用AI文字审核文本接口 登录接口失败");
        }
        return getAiAuditTextCheck(accessToken, text);
    }

    @ApiOperation("ai文本审核")
    @ApiOperationSupport(order = 2)
    @GetMapping("/getAiAuditContentCheckResult")
    public R<JSONObject> getAiAuditContentCheckResult(String text) {
        String accessToken = fetchAiServiceAdminToken();
        if (!StringUtils.hasText(accessToken)) {
            return R.fail("调用AI文字审核内容接口 登录接口失败");
        }
        return getAiAuditContentCheck(accessToken, text);
    }

    private R<JSONObject> getAiAuditTextCheck(String accessToken, String text) {
        JSONObject data = new JSONObject();
        data.put("is_trade_related", true);

        // 初始化请求体Map
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("text", text);
        HttpHeaders aiHeaders = new HttpHeaders();
        aiHeaders.setContentType(MediaType.APPLICATION_JSON);
        aiHeaders.set("Authorization", "Bearer " + accessToken);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, aiHeaders);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(aiTextCheckUrl, request, String.class);
            if (response.getStatusCodeValue() != 200) {
                throw new RuntimeException("AI文字审核接口调用失败 http状态：" + response.getStatusCode());
            }
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(response.getBody())) {
                JSONObject taskObject = JSONObject.parseObject(response.getBody());
                if (taskObject.getInteger("code") == 200) {
                    data = taskObject.getJSONObject("data");
                }
            }
        } catch (Exception e) {
            log.error("调用AI文字审核接口 接口异常------", e);
        }

        return R.data(data);
    }

    private R<JSONObject> getAiAuditContentCheck(String accessToken, String text) {
        JSONObject data = new JSONObject();
        data.put("is_compliant", true);

        // 初始化请求体Map
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("text", text);
        HttpHeaders aiHeaders = new HttpHeaders();
        aiHeaders.setContentType(MediaType.APPLICATION_JSON);
        aiHeaders.set("Authorization", "Bearer " + accessToken);
//        aiHeaders.set("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1cHN0b3JlQGFkbWluLmNvbSIsImlkIjo2LCJ0aW1lIjoxNzYyOTI1NDAzLjY1MTY5MjZ9.07lz8Ox2cGC28UCmqcKCt5R6Rfwtgs-Eiu0ttgWRxws");

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, aiHeaders);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(aiContentCheckUrl, request, String.class);
            if (response.getStatusCodeValue() != 200) {
                throw new RuntimeException("AI文字审核文本接口调用失败 http状态：" + response.getStatusCode());
            }
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(response.getBody())) {
                JSONObject taskObject = JSONObject.parseObject(response.getBody());
                if (taskObject.getInteger("code") == 200) {
                    data = taskObject.getJSONObject("data");
                }
            }
        } catch (Exception e) {
            log.error("调用AI文本审核接口 接口异常------", e);
        }

        return R.data(data);
    }

    private String fetchAiServiceToken() {
        log.info("登录Ai服务获取token...{}", loginUrl);
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("username", userName);
        formData.add("password", passWord);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(loginUrl, requestEntity, String.class);
            if (response != null && response.getStatusCodeValue() == 200 && response.getBody() != null) {
                JSONObject jsonObject = JSONObject.parseObject(response.getBody());
                JSONObject dataJson = jsonObject.getJSONObject("data");
                return dataJson != null ? dataJson.getString("access_token") : null;
            }
            log.error("请求差评申诉辅助系统 登录接口失败 http状态：{}", response != null ? response.getStatusCode() : null);
        } catch (Exception e) {
            log.error("调用差评申诉辅助系统登录接口异常", e);
        }
        return null;
    }

    private String fetchAiServiceAdminToken() {
        log.info("登录Ai服务获取token...{}", loginUrl);
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("username", userNameAdmin);
        formData.add("password", passWord);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(loginUrl, requestEntity, String.class);
            if (response != null && response.getStatusCodeValue() == 200 && response.getBody() != null) {
                JSONObject jsonObject = JSONObject.parseObject(response.getBody());
                JSONObject dataJson = jsonObject.getJSONObject("data");
                return dataJson != null ? dataJson.getString("access_token") : null;
            }
            log.error("请求差评申诉辅助系统 登录接口失败 http状态：{}", response != null ? response.getStatusCode() : null);
        } catch (Exception e) {
            log.error("调用差评申诉辅助系统登录接口异常", e);
        }
        return null;
    }
}
