package com.yizhi.application.promptStatistics;

import com.yizhi.application.vo.PromptStatisticsVO;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.research.application.feign.ResearchClient;
import com.yizhi.research.application.vo.BaseModel;
import com.yizhi.research.application.vo.api.PageVo;
import com.yizhi.site.application.feign.api.SystemMailboxClients;
import com.yizhi.site.application.vo.domain.SystemMailboxParamVo;
import com.yizhi.training.application.feign.TrainingProjectClient;
import com.yizhi.training.application.vo.api.TrainingProjectMyParamVo;
import com.yizhi.util.application.domain.Response;
import com.yizhi.exam.application.feign.ExamApiClient;
import com.yizhi.exam.application.vo.dashboard.ExamDashboardQueryVO;
import com.yizhi.research.application.vo.domain.ResearchVo;
import com.yizhi.training.application.vo.api.TrainingProjectListVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

import com.baomidou.mybatisplus.plugins.Page;

@Api(tags = "提示统计接口")
@RestController
@RequestMapping("/api/prompt")
public class PromptStatisticsController {

    private static final Logger LOGGER = LoggerFactory.getLogger(PromptStatisticsController.class);

    @Autowired
    private ResearchClient researchClient;

    @Autowired
    private TrainingProjectClient trainingProjectClient;

    @Autowired
    private ExamApiClient examApiClient;

    @Autowired
    private SystemMailboxClients systemMailboxClients;

    @ApiOperation(value = "获取提示统计信息", notes = "获取总提示数量及各类提示数量统计")
    @GetMapping("/statistics")
    public Response<PromptStatisticsVO> getPromptStatistics() {
        try {
            PromptStatisticsVO statistics = new PromptStatisticsVO();

            RequestContext context = ContextHolder.get();

            // 1. 获取工作任务数量（调研表biz_type=1，已上架且处于调研期间）
            Integer workTaskCount = getWorkTaskCount(context);
            statistics.setWorkTaskCount(workTaskCount);

            // 2. 获取主题活动数量（培训项目已上架未结束）
            Integer themeActivityCount = getThemeActivityCount(context);
            statistics.setThemeActivityCount(themeActivityCount);

            // 3. 获取我要投票数量（调研表biz_type=2，已上架）
            Integer voteCount = getVoteCount(context);
            statistics.setVoteCount(voteCount);

            // 4. 获取培训测试数量（考试相关的提示数量）
            Integer trainingTestCount = getTrainingTestCount(context);
            statistics.setTrainingTestCount(trainingTestCount);

            // 5. 获取信箱提示数量（未读消息数量）
            Integer mailboxCount = getMailboxCount(context);
            statistics.setMailboxCount(mailboxCount);

            // 6. 计算总提示数量
            int totalPromptCount = workTaskCount + themeActivityCount + voteCount + trainingTestCount + mailboxCount;
            statistics.setTotalPromptCount(totalPromptCount);

            return Response.ok(statistics);
        } catch (Exception e) {
            LOGGER.error("获取提示统计信息失败", e);
            return Response.fail("500", "获取提示统计信息失败");
        }
    }

    /**
     * 获取工作任务数量
     * @param context
     * @return
     */
    private Integer getWorkTaskCount(RequestContext context) {
        try {
            PageVo pageVo = new PageVo();
            pageVo.setAccountId(context.getAccountId());
            pageVo.setDate(new Date());
            pageVo.setPageNo(1);
            pageVo.setPageSize(1);
            pageVo.setBizType(1); // 调研类型
            pageVo.setState(2); // 进行中的任务

            BaseModel<PageVo> model = new BaseModel<>();
            model.setDate(new Date());
            model.setObj(pageVo);
            model.setContext(context);

            // 获取调研列表，只取数量
            Page<ResearchVo> response = researchClient.apiListPage(model);
            if (response != null ) {

                return response.getTotal();
            }
            return 0;
        } catch (Exception e) {
            LOGGER.error("获取工作任务数量失败", e);
            return 0;
        }
    }

    /**
     * 获取主题活动数量
     * @param context
     * @return
     */
    private Integer getThemeActivityCount(RequestContext context) {
        try {
            TrainingProjectMyParamVo paramVo = new TrainingProjectMyParamVo();
            paramVo.setPageNo(1);
            paramVo.setPageSize(1);
            paramVo.setType(2); // 进行中的活动

            com.yizhi.training.application.model.BaseModel<TrainingProjectMyParamVo> model =
                    new com.yizhi.training.application.model.BaseModel<>();
            model.setContext(context);
            model.setDate(new Date());
            model.setObj(paramVo);

            // 获取培训项目列表，只取数量
            Page<TrainingProjectListVo> response = trainingProjectClient.apiMyPageList(model);
            if (response != null ) {
                return response.getTotal();
            }
            return 0;
        } catch (Exception e) {
            LOGGER.error("获取主题活动数量失败", e);
            return 0;
        }
    }

    /**
     * 获取投票数量
     * @param context
     * @return
     */
    private Integer getVoteCount(RequestContext context) {
        try {
            PageVo pageVo = new PageVo();
            pageVo.setAccountId(context.getAccountId());
            pageVo.setDate(new Date());
            pageVo.setPageNo(1);
            pageVo.setPageSize(1);
            pageVo.setBizType(2); // 投票类型
            pageVo.setState(2); // 进行中的投票

            BaseModel<PageVo> model = new BaseModel<>();
            model.setDate(new Date());
            model.setObj(pageVo);
            model.setContext(context);

            // 获取投票列表，只取数量
            Page<ResearchVo> response = researchClient.apiListPage(model);
            if (response != null ) {
                return response.getTotal();
            }
            return 0;
        } catch (Exception e) {
            LOGGER.error("获取投票数量失败", e);
            return 0;
        }
    }

    /**
     * 获取培训测试数量
     * @param context
     * @return
     */
    private Integer getTrainingTestCount(RequestContext context) {
        try {
            // 使用考试dashboard接口获取考试统计信息
            ExamDashboardQueryVO query = new ExamDashboardQueryVO();
            query.setSiteId(context.getSiteId());
            // 设置最近7天的时间范围
            Date endDate = new Date();
            Date startDate = new Date(endDate.getTime() - 7 * 24 * 60 * 60 * 1000L);
            query.setStartDate(startDate);
            query.setEndDate(endDate);

            Map<Long, Integer> examData = examApiClient.getExamDashboardData(query);
            // 返回考试数量
            return examData != null ? examData.size() : 0;
        } catch (Exception e) {
            LOGGER.error("获取培训测试数量失败", e);
            return 0;
        }
    }

    /**
     * 获取信箱提示数量（未读消息数量）
     * @param context
     * @return
     */
    private Integer getMailboxCount(RequestContext context) {
        try {
            // 获取未读消息数量
            Page<SystemMailboxParamVo> response = systemMailboxClients.selectMyPage(1,1, 2);
            if (response != null ) {
                return response.getTotal();
            }
            return 0;
        } catch (Exception e) {
            LOGGER.error("获取信箱提示数量失败", e);
            return 0;
        }
    }
}