package com.yizhi.application.research.controller.manage;

import com.yizhi.application.report.research.vo.ReportResearchAnalyze;
import com.yizhi.application.report.research.vo.ReportResearchViewVo;
import com.yizhi.application.report.research.vo.ReportResearchVo;
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.feign.ResearchQuestionClient;
import com.yizhi.research.application.feign.ResearchReportClient;
import com.yizhi.research.application.vo.domain.ResearchVo;
import com.yizhi.research.application.vo.domain.TrResearchQuestionVo;
import com.yizhi.research.application.vo.report.DownloadParamsVoOnTime;
import com.yizhi.statistics.application.entity.StatisticsResearch;
import com.yizhi.statistics.application.feign.StatisticsResearchReportClient;
import com.yizhi.statistics.application.refactor.TrResearchQuestionVO;
import com.yizhi.statistics.application.vo.research.DownloadParamsVo;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Api (tags = "导出-调研", description = "导出-调研")
@RestController
@RequestMapping ("/manage/export/research/")
public class ExportResearch2 {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExportResearch2.class);

    private SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    @Autowired
    private ResearchClient researchClient;


    @Autowired
    private ResearchQuestionClient researchQuestionClient;

    @Autowired
    private StatisticsResearchReportClient statisticsResearchClient;
    @Autowired
    private ResearchReportClient researchReportClient;


    @Value("${pc.host.url}")
    String pcHostUrl;

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    @ApiOperation (value = "导出调研参与人员统计", notes = "导出调研参与人员统计")
    @GetMapping ("/accounts")
    public Response<ReportResearchVo> reportResearchAccounts(
            @ApiParam (value = "调研id", required = true) @RequestParam (name = "researchId", required = true) Long researchId,
            @ApiParam (value = "部门关键字或者部门编码", required = false) @RequestParam (name = "orgNameorOrgCode", required = false) String orgNameorOrgCode,
            @ApiParam (value = "用户关键字", required = false) @RequestParam (name = "accountName", required = false) String accountName,
            @ApiParam (value = "参加状态", required = false) @RequestParam (name = "joinState", required = false) Integer joinState,
            @ApiParam (value = "开始时间", required = false) @RequestParam (name = "startDate", required = false) String startDate,
            @ApiParam (value = "结束时间", required = false) @RequestParam (name = "endDate", required = false) String endDate
    ) {
        try {
            if (startDate == "") {
                startDate = null;
            }
            if (endDate == "") {
                endDate = null;
            }
            if (orgNameorOrgCode != null) {
                orgNameorOrgCode = orgNameorOrgCode.replace(" ", "");
            }
            if (orgNameorOrgCode == "") {
                orgNameorOrgCode = null;
            }
            if (accountName != null) {
                accountName = accountName.replace(" ", "");
            }
            if (accountName == "") {
                accountName = null;
            }
            RequestContext context = ContextHolder.get();
            StatisticsResearch research = statisticsResearchClient.viewOne(researchId);
            if (research == null) {
                return Response.fail("该调研不存在");
            }
            Long taskId = System.currentTimeMillis();
            String taskName = research.getName() + "_用户清单" + "_" + taskId.toString();
            DownloadParamsVo paramsVo = new DownloadParamsVo();
            paramsVo.setResearchId(researchId);
            paramsVo.setResesrchName(research.getName());
            paramsVo.setAccountName(accountName);
            paramsVo.setContext(context);
            paramsVo.setJoinState(joinState);
            paramsVo.setStartTime(startDate);
            paramsVo.setEndTime(endDate);
            paramsVo.setOrgNameorOrgCode(orgNameorOrgCode);
            paramsVo.setTaskId(taskId);
            paramsVo.setTaskName(taskName);
            String serialNo = "USER-EXPORT-" + taskId.toString();
            paramsVo.setSerialNo(serialNo);

            statisticsResearchClient.reportResearchAccounts(paramsVo);
            String fileUril = pcHostUrl+"/api/v1/buckets/upload/objects/download/?preview=true&prefix="+taskName+".xlsx";
            return Response.ok(fileUril);
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }

    }

    @ApiOperation (value = "导出调研明细", notes = "导出调研明细")
    @GetMapping ("/details")
    public Response<ReportResearchViewVo> reportResearchDetails(
            @ApiParam (value = "调研id", required = true) @RequestParam (name = "researchId", required = true) Long researchId,
            @ApiParam (value = "部门关键字或者部门编码", required = false) @RequestParam (name = "orgNameorOrgCode", required = false) String orgNameorOrgCode,
            @ApiParam (value = "用户关键字", required = false) @RequestParam (name = "accountName", required = false) String accountName,
            @ApiParam (value = "参加状态", required = false) @RequestParam (name = "joinState", required = false) Integer joinState,
            @ApiParam (value = "开始时间", required = false) @RequestParam (name = "startDate", required = false) String startDate,
            @ApiParam (value = "结束时间", required = false) @RequestParam (name = "endDate", required = false) String endDate
    ) {
        RequestContext context = ContextHolder.get();
        try {
            if (startDate == "") {
                startDate = null;
            }
            if (endDate == "") {
                endDate = null;
            }
            if (orgNameorOrgCode != null) {
                orgNameorOrgCode = orgNameorOrgCode.replace(" ", "");
            }
            if (orgNameorOrgCode == "") {
                orgNameorOrgCode = null;
            }
            if (accountName != null) {
                accountName = accountName.replace(" ", "");
            }
            if (accountName == "") {
                accountName = null;
            }
            StatisticsResearch research = statisticsResearchClient.viewOne(researchId);
            if (research == null) {
                return Response.fail("该调研不存在");
            }

            Long taskId = System.currentTimeMillis();
            String serialNo = "RESEARCH-DETAILS-EXPORT-" + taskId.toString();
            String taskName = research.getName() + "_调研明细" + "_" + taskId.toString();
            DownloadParamsVo paramsVo = new DownloadParamsVo();
            paramsVo.setResearchId(researchId);
            paramsVo.setResesrchName(research.getName());
            paramsVo.setAccountName(accountName);
            paramsVo.setContext(context);
            paramsVo.setJoinState(joinState);
            paramsVo.setStartTime(startDate);
            paramsVo.setEndTime(endDate);
            paramsVo.setOrgNameorOrgCode(orgNameorOrgCode);
            paramsVo.setTaskId(taskId);
            paramsVo.setTaskName(taskName);
            paramsVo.setSerialNo(serialNo);
            List<TrResearchQuestionVo> trResearchQuestions = researchQuestionClient.listAll(researchId);
            if (trResearchQuestions == null) {
                trResearchQuestions = new ArrayList<TrResearchQuestionVo>();
            }
            List<TrResearchQuestionVO> statisticsQuestionsList = new ArrayList<>();
            if (trResearchQuestions.size() > 0){
                trResearchQuestions.forEach(questionVo -> {
                    TrResearchQuestionVO vo = new TrResearchQuestionVO();
                    BeanUtils.copyProperties(questionVo,vo);
                    statisticsQuestionsList.add(vo);
                });
            }

            paramsVo.setTrResearchQuestions(statisticsQuestionsList);
            statisticsResearchClient.reportResearchDetails(paramsVo);
            String fileUril = pcHostUrl+"/api/v1/buckets/upload/objects/download/?preview=true&prefix="+taskName+".xlsx";
            return Response.ok(fileUril);
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @ApiOperation (value = "导出调研分析统计", notes = "导出调研分析统计")
    @GetMapping ("/analyze")
    public Response<ReportResearchAnalyze> reportResearchanalyze(
            @ApiParam (value = "调研id", required = true) @RequestParam (name = "researchId", required = true) Long researchId,
            @ApiParam (value = "部门关键字或者部门编码", required = false) @RequestParam (name = "orgNameorOrgCode", required = false) String orgNameorOrgCode,
            @ApiParam (value = "用户关键字", required = false) @RequestParam (name = "accountName", required = false) String accountName,
            @ApiParam (value = "参加状态", required = false) @RequestParam (name = "joinState", required = false) Integer joinState,
            @ApiParam (value = "开始时间", required = false) @RequestParam (name = "startDate", required = false) String startDate,
            @ApiParam (value = "结束时间", required = false) @RequestParam (name = "endDate", required = false) String endDate
    ) {
        if (startDate == "") {
            startDate = null;
        }
        if (endDate == "") {
            endDate = null;
        }
        if (orgNameorOrgCode != null) {
            orgNameorOrgCode = orgNameorOrgCode.replace(" ", "");
        }
        if (orgNameorOrgCode == "") {
            orgNameorOrgCode = null;
        }
        if (accountName != null) {
            accountName = accountName.replace(" ", "");
        }
        if (accountName == "") {
            accountName = null;
        }

        RequestContext context = ContextHolder.get();
        try {
            StatisticsResearch research = statisticsResearchClient.viewOne(researchId);
            if (research == null) {
                return Response.fail("该调研不存在");
            }
            Long taskId = System.currentTimeMillis();
            String serialNo = "RESEARCH-ANALYZE-EXPORT-" + taskId.toString();

            String taskName = research.getName() + "_分析统计" + "_" + taskId.toString();
            DownloadParamsVo paramsVo = new DownloadParamsVo();
            paramsVo.setResearchId(researchId);
            paramsVo.setResesrchName(research.getName());
            paramsVo.setAccountName(accountName);
            paramsVo.setContext(context);
            paramsVo.setJoinState(joinState);
            paramsVo.setStartTime(startDate);
            paramsVo.setEndTime(endDate);
            paramsVo.setOrgNameorOrgCode(orgNameorOrgCode);
            paramsVo.setTaskId(taskId);
            paramsVo.setTaskName(taskName);
            paramsVo.setSerialNo(serialNo);
            statisticsResearchClient.reportResearchanalyze(paramsVo);
            String fileUril = pcHostUrl+"/api/v1/buckets/upload/objects/download/?preview=true&prefix="+taskName+".xlsx";
            return Response.ok(fileUril);
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @ApiOperation(value = "实时导出调研明细", notes = "导出调研明细")
    @GetMapping("/details/onTime")
    public Response<ReportResearchViewVo> reportResearchDetailsOnTime(
            @ApiParam(value = "调研id", required = true) @RequestParam(name = "researchId", required = true) Long researchId) {
        RequestContext context = ContextHolder.get();
        try {

            ResearchVo research = researchClient.getResearchView(researchId);
            if (research == null) {
                return Response.fail("该调研不存在");
            }

            Long taskId = System.currentTimeMillis();
            String serialNo = "RESEARCH-DETAILS-EXPORT-" + taskId.toString();
            String taskName = research.getName() + "_调研明细" + "_" + taskId.toString();
            DownloadParamsVoOnTime paramsVo = new DownloadParamsVoOnTime();
            paramsVo.setResearchId(researchId);
            paramsVo.setResesrchName(research.getName());
            paramsVo.setTaskId(taskId);
            paramsVo.setTaskName(taskName);
            paramsVo.setSerialNo(serialNo);
            paramsVo.setContext(context);

            researchReportClient.reportResearchDetails(paramsVo);
            String fileUril = pcHostUrl+"/api/v1/buckets/upload/objects/download/?preview=true&prefix="+taskName+".xlsx";
            return Response.ok(fileUril);
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @ApiOperation(value = "实时导出调研分析统计", notes = "导出调研分析统计")
    @GetMapping("/analyze/onTime")
    public Response<ReportResearchAnalyze> reportResearchanalyzeOnTime(
            @ApiParam(value = "调研id", required = true) @RequestParam(name = "researchId", required = true) Long researchId
    ) {


        RequestContext context = ContextHolder.get();
        try {
            ResearchVo research = researchClient.getResearchView(researchId);
            if (research == null) {
                return Response.fail("该调研不存在");
            }
            Long taskId = System.currentTimeMillis();
            String serialNo = "RESEARCH-ANALYZE-EXPORT-" + taskId.toString();

            String taskName = research.getName() + "_分析统计" + "_" + taskId.toString();
            DownloadParamsVoOnTime paramsVo = new DownloadParamsVoOnTime();
            paramsVo.setResearchId(researchId);
            paramsVo.setResesrchName(research.getName());
            paramsVo.setTaskId(taskId);
            paramsVo.setTaskName(taskName);
            paramsVo.setSerialNo(serialNo);
            paramsVo.setContext(context);
            researchReportClient.reportResearchanalyze(paramsVo);
            String fileUril = pcHostUrl+"/api/v1/buckets/upload/objects/download/?preview=true&prefix="+taskName+".xlsx";
            return Response.ok(fileUril);
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }
}
