package com.easyproject.clientbus.service.feedback.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.coze.openapi.client.workflows.run.RunWorkflowReq;
import com.coze.openapi.client.workflows.run.RunWorkflowResp;
import com.coze.openapi.service.service.CozeAPI;
import com.easyproject.clientbus.domain.dto.FeedbackDto;
import com.easyproject.clientbus.service.feedback.IFeedbackService;
import com.easyproject.common.core.domain.AjaxClientResult;
import com.easyproject.common.core.domain.AjaxResult;
import com.easyproject.common.utils.ServletUtils;
import com.easyproject.common.utils.coze.ChatAiForCozeUtils;
import com.easyproject.common.utils.ip.IpUtils;
import com.easyproject.service.domain.coze.CozeTokenSet;
import com.easyproject.service.domain.operate.OperateFeedback;
import com.easyproject.service.mapper.operate.OperateFeedbackMapper;
import com.easyproject.service.service.ICozeJwtService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 方法说明: 意见反馈相关接口
 *
 * @param
 * @author java-101
 * @return
 * @date 2025-03-23 18:42:35
 */
@Slf4j
@Service
public class FeedbackServiceImpl implements IFeedbackService {

    @Resource
    private OperateFeedbackMapper operateFeedbackMapper;
    @Resource
    private ICozeJwtService cozeJwtService;

    /**
     * 方法说明: 意见反馈
     *
     * @param
     * @return
     * @author java-101
     * @date 2025-03-23 18:47:21
     */
    @Override
    public AjaxClientResult feedback(FeedbackDto dto) {
        if (ObjectUtil.isEmpty(dto.getFeedbackContent())) {
            return AjaxClientResult.error("反馈内容不能为空");
        }
        Map<String, Object> resultMap = new HashMap<>();

        Integer code = 0;//0 不相关、1：与改进相关（需要落库）
        //调用工作流，进行自动回复反馈
        String answerInfo = feedBackCheckAnswer(dto.getFeedbackContent());//知识库查询判断
        if (ObjectUtil.isEmpty(answerInfo)) {
            //智能体功能改进相关判断
            code = feedBackCheckType(dto.getFeedbackContent());
        }else{
            resultMap.put("code", 1);//1=智能体有回答，2=与改进相关（写入数据库），3=与改进无关
            resultMap.put("message", answerInfo);
            return AjaxClientResult.success(resultMap);
        }

        if(code == 1){//与改进相关（写入数据库）
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            OperateFeedback feedback = new OperateFeedback();
            feedback.setFeedbackContent(dto.getFeedbackContent());
            feedback.setPhone(dto.getPhone());
            feedback.setStatus(1);
            feedback.setIpAddress(ip);
            feedback.setCreateTime(DateUtil.date());

            int result = operateFeedbackMapper.insert(feedback);
            if (result > 0) {
                resultMap.put("code", 2);
                resultMap.put("message", "该问题与智能体功能改进优化相关");
                return AjaxClientResult.success(resultMap);
            } else {
                return AjaxClientResult.error();
            }
        }else{
            resultMap.put("code", 3);
            resultMap.put("message", "该问题与智能体功能改进优化不相关");
            return AjaxClientResult.success(resultMap);
        }
    }

    /**
     * 方法说明: 知识库查询判断
     *
     * @param
     * @return
     * @author java-101
     * @date 2025-07-19 11:05:33
     */
    private String feedBackCheckAnswer(String feedbackContent) {
        log.info("1-在线反馈-知识库查询判断【请求开始】");
        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();
        if (ObjectUtil.isEmpty(tokenSet)) {
            return null;
        }
        //初始化客户端
        CozeAPI coze = ChatAiForCozeUtils.getCozeClient(tokenSet.getPersonToken());

        String workflowID = "7526832363935023147";//FeedBack_Check_Answer知识库査询判断

        Map<String, Object> data = new HashMap<>();
        data.put("input", feedbackContent);
        RunWorkflowReq req = RunWorkflowReq.builder().workflowID(workflowID).parameters(data).build();

        RunWorkflowResp resp = coze.workflows().runs().create(req);

        log.info("1-在线反馈-知识库查询判断【请求结束】");
        //System.out.println(resp);

        String dataStr = resp.getData();
        JSONObject innerJson = JSONUtil.parseObj(dataStr);

        // 获取code和message
        Integer code = innerJson.getInt("code");//0=无法解答您的问题，1=智能体有回答
        String message = innerJson.getStr("message");

        // 输出结果
        /*System.out.println("1-Code: " + code);
        System.out.println("1-Message: " + message);*/
        if (code == 1) {
            return message;
        }else{
            return null;
        }
    }

    /**
     * 方法说明: 智能体功能改进相关判断
     *
     * @param
     * @return
     * @author java-101
     * @date 2025-07-19 11:17:28
     */
    private Integer feedBackCheckType(String feedbackContent) {
        log.info("2-在线反馈-智能体功能改进相关判断【请求开始】");
        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();
        if (ObjectUtil.isEmpty(tokenSet)) {
            return null;
        }
        //初始化客户端
        CozeAPI coze = ChatAiForCozeUtils.getCozeClient(tokenSet.getPersonToken());

        String workflowID = "7527209761322909748";//FeedBack_Check_Type智能体功能改进相关判断

        Map<String, Object> data = new HashMap<>();
        data.put("input", feedbackContent);
        RunWorkflowReq req = RunWorkflowReq.builder().workflowID(workflowID).parameters(data).build();

        RunWorkflowResp resp = coze.workflows().runs().create(req);
        log.info("2-在线反馈-智能体功能改进相关判断【请求结束】");
        //System.out.println(resp);

        String dataStr = resp.getData();
        JSONObject innerJson = JSONUtil.parseObj(dataStr);

        // 获取code和message
        Integer code = innerJson.getInt("code");
        String message = innerJson.getStr("message");

        // 输出结果
       /* System.out.println("2-Code: " + code);
        System.out.println("2-Message: " + message);*/
        return code;
    }

}
