package com.yizhi.application.report.research;

import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.plugins.Page;
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.ResearchReportClient;
import com.yizhi.research.application.vo.domain.StatisticsResearchVo;
import com.yizhi.statistics.application.entity.StatisticsResearch;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.system.remote.ReportClient;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;



/**
 * 调研报表统计
 * @author mei
 *
 */

@Api(tags = "报表统计-调研", description = "报表统计-调研")
@RestController
@RequestMapping("/manage/report/research2/")
public class ReportResearch {

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

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

	@Autowired
	private ResearchClient researchClient;
	@Autowired
	private AccountClient accountClient;
	@Autowired
	private ResearchReportClient researchReportClient;
	@Autowired
	private ReportClient reportClient;

	@ApiOperation(value = "调研统计", notes = "调研统计", response = ReportResearchVo.class)
	@GetMapping("/group")
	public Response<ReportResearchVo> researchGroup(
			@ApiParam(value = "开始时间（yyyy-mm-dd）", required = false) @RequestParam(name = "startDate", required = false) String startDate,
			@ApiParam(value = "结束时间（yyyy-mm-dd）", required = false) @RequestParam(name = "endDate", required = false) String endDate,
			@ApiParam(value = "调研关键字", required = false) @RequestParam(name = "kwd", required = false) String kwd,
			@ApiParam(value = "每页条数，默认10", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize,
			@ApiParam(value = "当前页数", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo) {
		if( startDate == ""){
			startDate = null;
		}
		if( endDate == ""){
			endDate = null;
		}
		if(kwd != null){
			kwd = kwd.replace(" ","");
		}
		if(kwd == ""){
			kwd = null;
		}
		Map<String,Integer> pageMap=new HashMap<String, Integer>();
		Page<StatisticsResearchVo> page;
		List<StatisticsResearchVo> list;
		try{
			RequestContext context= ContextHolder.get();
			Long companyId=context.getCompanyId();
			List<Long> orgIds=context.getOrgIds();
			Long siteId=context.getSiteId();
			page= researchReportClient.researchGroup(startDate,endDate,kwd,pageSize,pageNo,companyId,orgIds,siteId);
			list=page.getRecords();
			pageMap.put("pageNo", pageNo);
		    pageMap.put("pageSize", pageSize);
		    pageMap.put("pageTotal",page.getTotal());
			return Response.ok(list,pageMap);
		} catch (Exception e) {
			LOGGER.error("", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}

	}

	@ApiOperation(value = "调研统计-查看", notes = "调研统计-查看", response = ReportResearchViewVo.class)
	@GetMapping("/group/view")
	public Response<ReportResearchViewVo> researchGroupView(
			@ApiParam(value = "开始时间（yyyy-mm-dd）", required = false) @RequestParam(name = "startDate", required = false) String startDate,
			@ApiParam(value = "结束时间（yyyy-mm-dd）", required = false) @RequestParam(name = "endDate", required = false) String endDate,
            @ApiParam(value = "是否参加", required = false) @RequestParam(name = "state", required = false) Integer state,
			@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 = "pageNo", required = true, defaultValue = "1") Integer pageNo,
			@ApiParam(value = "每页的个数", required = false) @RequestParam(name = "pageSize", required = true,defaultValue = "10") Integer pageSize) {
		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;
		}
        Map<String, Integer> pageMap = new HashMap<String, Integer>();
        pageMap.put("pageNo", pageNo);
        pageMap.put("pageSize", pageSize);
		try {
			RequestContext context=ContextHolder.get();
			Page<StatisticsResearchVo> page=researchReportClient.researchGroupView(startDate,endDate,researchId,orgNameorOrgCode,accountName,state,pageSize,pageNo);
			List<StatisticsResearchVo> list=page.getRecords();
		    pageMap.put("pageTotal" , page.getTotal());
			return Response.ok(list,pageMap);
			/*PageInfo<ReportAccountRespVO> page =reportClient.getAccounts(reportAccountReqVO);
		if (0 == page.getRecords().size()) {
		    pageMap.put("pageTotal",0);
			return Response.ok(reportResearchViewVos,pageMap);
		}
		    Research research=researchClient.getResearchView(researchId);
            if(research==null){
                return Response.fail("","查询的调研不存在");
            }
            List<TrResearchAnswer> trResearchAnswers = research.getTrResearchAnswers();
			Integer visible = research.getVisibleRange();
			List<ReportAccountRespVO> reportAccountRespVOS = page.getRecords();
			StringBuilder sb;
				for (ReportAccountRespVO reportAccountRespVO : reportAccountRespVOS) {
					sb=new StringBuilder();
					List<String> parentOrgNames=reportAccountRespVO.getParentOrgNames();
					String parentOrgName="";
					for(String s : parentOrgNames){
						sb.append(s);
					}
					parentOrgName=sb.toString();
					reportResearchViewVo = new ReportResearchViewVo();
					reportResearchViewVo.setAccountFullName(reportAccountRespVO.getUserFullName());
					reportResearchViewVo.setAccountName(reportAccountRespVO.getUserName());
					reportResearchViewVo.setParentOrgName(parentOrgName);
					reportResearchViewVo.setOrgName(parentOrgName + "/" + reportAccountRespVO.getOrgName());
					if(visible==1) {
						for (TrResearchAnswer trResearchAnswer : trResearchAnswers) {
							if (reportAccountRespVO.getUserId().equals(trResearchAnswer.getAccountId())) {
								reportResearchViewVo.setState(1);
								reportResearchViewVo.setSubTime(trResearchAnswer.getSubmitTime());
								reportResearchViewVos.add(reportResearchViewVo);
							}
						}
						if (reportResearchViewVo.getState() == 0) {
							reportResearchViewVos.add(reportResearchViewVo);
						}
					}
					if(visible==2){
						List<Long> relationIds = research.getRelationIds();
						for (Long relationId : relationIds) {
							if (relationId.equals(reportAccountRespVO.getUserId()) || relationId.equals(reportAccountRespVO.getOrgId())) {
								for (TrResearchAnswer trResearchAnswer : trResearchAnswers) {
									if (reportAccountRespVO.getUserId().equals(trResearchAnswer.getAccountId())) {
										reportResearchViewVo.setState(1);
										reportResearchViewVo.setSubTime(trResearchAnswer.getSubmitTime());
										reportResearchViewVos.add(reportResearchViewVo);
									}
								}
								if (reportResearchViewVo.getState() == 0) {
									reportResearchViewVos.add(reportResearchViewVo);
								}
							}
						}
					}
				}
			int start=(pageNo-1)*pageSize;
			int end=pageNo*pageSize;
			List<ReportResearchViewVo> reportResearchViewVos1=new LinkedList<ReportResearchViewVo>();
			List<ReportResearchViewVo> reportResearchViewVos2=new LinkedList<ReportResearchViewVo>();
                for(ReportResearchViewVo reportResearchViewVO: reportResearchViewVos){
					if(reportResearchViewVO.getState()==state && state==1){
						reportResearchViewVos1.add(reportResearchViewVO);
					}
					if(reportResearchViewVO.getState()==state && state==0){
						reportResearchViewVos1.add(reportResearchViewVO);
					}
					if(state==2){
						reportResearchViewVos1.add(reportResearchViewVO);
					}
				}
                pageMap.put("pageTotal", reportResearchViewVos1.size());
                for(int i=start;i<end;i++){
                    if(reportResearchViewVos1.size()==0||i>=reportResearchViewVos1.size()){
                        break;
                    }
                    reportResearchViewVos2.add(reportResearchViewVos1.get(i));
                }
			return Response.ok(reportResearchViewVos2,pageMap);*/

		}catch (Exception e){
			LOGGER.error("",e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@GetMapping("/asynchronous/load/data")
	public Response<String> intoCourseReport(@ApiParam(value = "开始时间（yyyy-mm-dd）", required = false) @RequestParam(name = "startDate", required = false) String startDate,
			@ApiParam(value = "结束时间（yyyy-mm-dd）", required = false) @RequestParam(name = "endDate", required = false) String endDate) {
		/*researchReportClient.asynchronousResearch(startDate,endDate);*/
		return Response.ok("ok");
	}
}
