package com.ycwl.basic.integration.questionnaire.service;

import com.ycwl.basic.integration.common.exception.IntegrationException;
import com.ycwl.basic.integration.common.response.CommonResponse;
import com.ycwl.basic.integration.common.response.PageResponse;
import com.ycwl.basic.integration.common.service.IntegrationFallbackService;
import com.ycwl.basic.integration.questionnaire.client.QuestionnaireClient;
import com.ycwl.basic.integration.questionnaire.dto.answer.ResponseDetailResponse;
import com.ycwl.basic.integration.questionnaire.dto.answer.SubmitAnswerRequest;
import com.ycwl.basic.integration.questionnaire.dto.questionnaire.CreateQuestionnaireRequest;
import com.ycwl.basic.integration.questionnaire.dto.questionnaire.QuestionnaireResponse;
import com.ycwl.basic.integration.questionnaire.dto.statistics.QuestionnaireStatistics;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class QuestionnaireIntegrationService {

    private final QuestionnaireClient questionnaireClient;
    private final IntegrationFallbackService fallbackService;
    
    private static final String SERVICE_NAME = "zt-questionnaire";

    // ==================== 问卷查询接口（支持 fallback） ====================

    public QuestionnaireResponse getQuestionnaire(Long id) {
        log.info("获取问卷详情, id: {}", id);
        return fallbackService.executeWithFallback(
            SERVICE_NAME,
            "questionnaire:" + id,
            () -> {
                CommonResponse<QuestionnaireResponse> response = questionnaireClient.getQuestionnaire(id);
                return handleResponse(response, "获取问卷详情失败");
            },
            QuestionnaireResponse.class
        );
    }

    public PageResponse<QuestionnaireResponse> getQuestionnaireList(Integer page, Integer pageSize,
                                                                    String name, Integer status, String createdBy) {
        log.info("获取问卷列表, page: {}, pageSize: {}, name: {}, status: {}, createdBy: {}", 
                 page, pageSize, name, status, createdBy);
        CommonResponse<PageResponse<QuestionnaireResponse>> response =
                        questionnaireClient.getQuestionnaireList(page, pageSize, name, status, createdBy);
        return handleResponse(response, "获取问卷列表失败");
    }

    public QuestionnaireStatistics getStatistics(Long id) {
        log.info("获取问卷统计, id: {}", id);
        return fallbackService.executeWithFallback(
            SERVICE_NAME,
            "questionnaire:statistics:" + id,
            () -> {
                CommonResponse<QuestionnaireStatistics> response = questionnaireClient.getStatistics(id);
                return handleResponse(response, "获取问卷统计失败");
            },
            QuestionnaireStatistics.class
        );
    }

    public PageResponse<ResponseDetailResponse> getResponseList(Integer page, Integer pageSize, Long questionnaireId,
                                              String userId, String startTime, String endTime) {
        log.info("获取回答记录列表, page: {}, pageSize: {}, questionnaireId: {}, userId: {}", 
                 page, pageSize, questionnaireId, userId);
        CommonResponse<PageResponse<ResponseDetailResponse>> response =
                questionnaireClient.getResponseList(page, pageSize, questionnaireId, userId, startTime, endTime);
        return handleResponse(response, "获取回答记录列表失败");
    }

    public ResponseDetailResponse getResponseDetail(Long id) {
        log.info("获取回答详情, id: {}", id);
        return fallbackService.executeWithFallback(
            SERVICE_NAME,
            "response:" + id,
            () -> {
                CommonResponse<ResponseDetailResponse> response = questionnaireClient.getResponseDetail(id);
                return handleResponse(response, "获取回答详情失败");
            },
            ResponseDetailResponse.class
        );
    }

    // ==================== 问卷管理接口（直接执行，不支持 fallback） ====================

    public QuestionnaireResponse createQuestionnaire(CreateQuestionnaireRequest request, String userId) {
        log.info("创建问卷, name: {}, userId: {}", request.getName(), userId);
        CommonResponse<QuestionnaireResponse> response = questionnaireClient.createQuestionnaire(request, userId);
        return handleResponse(response, "创建问卷失败");
    }

    public QuestionnaireResponse updateQuestionnaire(Long id, CreateQuestionnaireRequest request, String userId) {
        log.info("更新问卷, id: {}, userId: {}", id, userId);
        CommonResponse<QuestionnaireResponse> response = questionnaireClient.updateQuestionnaire(id, request, userId);
        QuestionnaireResponse result = handleResponse(response, "更新问卷失败");
        // 清理问卷相关缓存
        clearQuestionnaireCache(id);
        return result;
    }

    public void deleteQuestionnaire(Long id, String userId) {
        log.info("删除问卷, id: {}, userId: {}", id, userId);
        CommonResponse<Void> response = questionnaireClient.deleteQuestionnaire(id, userId);
        handleResponse(response, "删除问卷失败");
        // 清理问卷相关缓存
        clearQuestionnaireCache(id);
    }

    public QuestionnaireResponse publishQuestionnaire(Long id, String userId) {
        log.info("发布问卷, id: {}, userId: {}", id, userId);
        CommonResponse<QuestionnaireResponse> response = questionnaireClient.publishQuestionnaire(id, userId);
        QuestionnaireResponse result = handleResponse(response, "发布问卷失败");
        // 清理问卷相关缓存（发布会改变状态）
        clearQuestionnaireCache(id);
        return result;
    }

    public QuestionnaireResponse stopQuestionnaire(Long id, String userId) {
        log.info("停止问卷, id: {}, userId: {}", id, userId);
        CommonResponse<QuestionnaireResponse> response = questionnaireClient.stopQuestionnaire(id, userId);
        QuestionnaireResponse result = handleResponse(response, "停止问卷失败");
        // 清理问卷相关缓存
        clearQuestionnaireCache(id);
        return result;
    }

    public ResponseDetailResponse submitAnswer(SubmitAnswerRequest request) {
        log.info("提交问卷答案, questionnaireId: {}, userId: {}", request.getQuestionnaireId(), request.getUserId());
        CommonResponse<ResponseDetailResponse> response = questionnaireClient.submitAnswer(request);
        ResponseDetailResponse result = handleResponse(response, "提交问卷答案失败");
        // 清理统计缓存（提交答案会影响统计）
        if (request.getQuestionnaireId() != null) {
            fallbackService.clearFallbackCache(SERVICE_NAME, "questionnaire:statistics:" + request.getQuestionnaireId());
        }
        return result;
    }

    /**
     * 清理问卷相关缓存
     */
    private void clearQuestionnaireCache(Long questionnaireId) {
        fallbackService.clearFallbackCache(SERVICE_NAME, "questionnaire:" + questionnaireId);
        fallbackService.clearFallbackCache(SERVICE_NAME, "questionnaire:statistics:" + questionnaireId);
    }



    // ==================== 工具方法 ====================

    private <T> T handleResponse(CommonResponse<T> response, String errorMessage) {
        if (response == null || !response.isSuccess()) {
            String msg = response != null && response.getMessage() != null 
                        ? response.getMessage() 
                        : errorMessage;
            Integer code = response != null ? response.getCode() : 5000;
            throw new IntegrationException(code, msg, SERVICE_NAME);
        }
        return response.getData();
    }
}