package com.yizhi.application.report.marketingcourse;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.tools.PageTools;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.course.application.feign.MarketingCourseClient;
import com.yizhi.course.application.feign.MarketingCourseExportClient;
import com.yizhi.course.application.vo.MarketingCourseViewVo;
import com.yizhi.course.application.vo.ReportMarketingCourseAccountVo;
import com.yizhi.course.application.vo.ReportMarketingCourseDataChartsVo;
import com.yizhi.course.application.vo.ReportMarketingCourseVo;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.system.remote.OrganizationClient;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.util.application.constant.MarketingCourseReportType;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
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.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 学习营销报表统计
 * @author mei
 *
 */

@Api(tags = "报表统计-学习营销", description = "报表统计-学习营销")
@RestController
@RequestMapping("/manage/report/marketingcourse")
public class ReportMarketingCourse {

	private static final Logger logger = LoggerFactory.getLogger(ReportMarketingCourse.class);

/*	static final String BY_COURSE_EXPORT = "by_course_export";//按课程导出
	static final String BY_USER_EXPORT = "by_user_export";//按用户导出
	static final String BY_USER_DETAIL_EXPORT = "by_user_detail_export";//按用户明细导出*/

	@Autowired
	private MarketingCourseClient marketingCourseClient;

	@Autowired
	private OrganizationClient organizationClient;

	@Autowired
	private AccountClient accountClient;

	@Autowired
	private MarketingCourseExportClient export;

	private static final DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");


	@ApiOperation(value = "图表数据统计", notes = "图表数据统计", response = ReportMarketingCourseDataChartsVo.class)
    @GetMapping("/chart/group")
    public Response<ReportMarketingCourseDataChartsVo> chartGroup(
    		@ApiParam(value = "开始时间（yyyy-mm-dd）", required = true) @RequestParam(name = "startDate", required = true) String startDate, 
    		@ApiParam(value = "结束时间（yyyy-mm-dd）", required = true) @RequestParam(name = "endDate", required = true) String endDate, 
    		@ApiParam(value = "类型：1按日 2按周 3按月（默认按日）", required = true) @RequestParam(name = "type", required = true, defaultValue = "1") Integer type, 
    		@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(StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
			return Response.ok();
		}
		Page<ReportMarketingCourseDataChartsVo> result =
				marketingCourseClient.chartGroup(startDate,endDate,type,pageSize,pageNo);
		/*Map<String, Integer> pageMap = new HashMap<String, Integer>();
		pageMap.put("pageNo", pageNo);
		pageMap.put("pageSize", pageSize);
		pageMap.put("pageTotal", dataChartsVos.size());*/
		List<ReportMarketingCourseDataChartsVo> ret = null;
		if(result != null){
			//pageMap.put("pageTotal", result.getTotal());
			ret = result.getRecords();
		}

		return Response.ok(ret, null);
		
		//return Response.ok(result.getRecords(), null);
	}
	
	@ApiOperation(value = "按课程统计", notes = "按课程统计", response = ReportMarketingCourseVo.class)
    @GetMapping("/group")
    public Response<ReportMarketingCourseVo> marketingCourseGroup(
    		@ApiParam(value = "开始时间（yyyy-mm-dd）", required = true) @RequestParam(name = "startDate", required = true) String startDate, 
    		@ApiParam(value = "结束时间（yyyy-mm-dd）", required = true) @RequestParam(name = "endDate", required = true) 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(StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
			return Response.ok();
		}

		Page<ReportMarketingCourseVo> result =
				marketingCourseClient.marketingCourseGroup(startDate,endDate,kwd,pageSize,pageNo);
		
		Map<String, Integer> pageMap = new HashMap<String, Integer>();
		pageMap.put("pageNo", pageNo);
		pageMap.put("pageSize", pageSize);
		pageMap.put("pageTotal",result.getTotal() );
		List<ReportMarketingCourseVo> ret = null;
		if(result != null){
			pageMap.put("pageTotal", result.getTotal());
			ret = result.getRecords();
		}

		return Response.ok(ret, pageMap);
	}

	@ApiOperation(value = "按课程统计-下载结果数据", notes = "按课程统计下载导出")
	@GetMapping("/group/export")
	public Response<String> marketingCourseGroupExport(
			@ApiParam(value = "开始时间（yyyy-mm-dd）", required = true) @RequestParam(name = "startDate", required = true) String startDate,
			@ApiParam(value = "结束时间（yyyy-mm-dd）", required = true) @RequestParam(name = "endDate", required = true) String endDate,
			@ApiParam(value = "课程关键字", required = false) @RequestParam(name = "kwd", required = false) String kwd
	){
		Map<String,Object> parament = new HashMap<>();
		// 共同字段
		/*RequestContext requestContext = ContextHolder.get();
		logger.info("%%%%%%%%%%%%%%%%%%%%上下文信息="+JSON.toJSONString(requestContext));
		parament.put("requestContext",requestContext);*/

		String exportName = "学习营销课程打开转发统计";
		parament.put("exportName",exportName);
		parament.put("business", MarketingCourseReportType.BY_COURSE_EXPORT);// 导出的业务类型
		parament.put("startDate",startDate);
		parament.put("endDate",endDate);
		parament.put("kwd",kwd);
		String taskNo = LocalDateTime.now().format(formatter);
		parament.put("serialNo",taskNo);
		// 执行异步，并且设置成异步启动
		export.marketingCourseGroupExport(parament);

		return Response.ok("任务序号："+ taskNo+"。任务名称："+exportName+"_"+taskNo);
	}


	@ApiOperation(value = "按用户统计-下载用户统计", notes = "学习营销用户打开转发统计下载导出")
	@GetMapping("/account/group/export")
	public Response<ReportMarketingCourseAccountVo> marketingCourseAccountGroupExport(
			@ApiParam(value = "开始时间（yyyy-mm-dd）", required = true) @RequestParam(name = "startDate", required = true) String startDate,
			@ApiParam(value = "结束时间（yyyy-mm-dd）", required = true) @RequestParam(name = "endDate", required = true) String endDate,
			@ApiParam(value = "部门编码或名称", required = false) @RequestParam(name = "orgKwd", required = false) String orgKwd,
			@ApiParam(value = "用户关键字", required = false) @RequestParam(name = "accountKwd", required = false) String accountKwd,
			@ApiParam(value = "导出类型:{1:下载用户统计;2:下载阅读统计;3:下载打开明细;4:下载阅读明细}")
			@RequestParam(name = "exporType") String exporType) {

		Map<String,Object> parament = new HashMap<>();
		// 共同字段
		//parament.put("requestContext",ContextHolder.get());
		String exportName = "学习营销用户转发明细统计";

		// 1:下载用户统计;2:下载阅读统计;3:下载打开明细;4:下载阅读明细
		if(StringUtils.equals("1",exporType)){
			parament.put("business",MarketingCourseReportType.BY_USER_EXPORT);
			exportName = "学习营销用户打开转发统计";
		}else if(StringUtils.equals("2",exporType)){
			parament.put("business",MarketingCourseReportType.BY_COURSE_OPEN_EXPORT);
			exportName = "学习营销用户转发阅读统计";
		}else if(StringUtils.equals("3",exporType)){
			parament.put("business",MarketingCourseReportType.BY_USER_OPEN_EXPORT);
			exportName = "学习营销用户打开明细";
		}else if(StringUtils.equals("4",exporType)){
			parament.put("business",MarketingCourseReportType.BY_USER_DETAIL_EXPORT);
			exportName = "学习营销用户转发阅读明细";
		}

		parament.put("startDate",startDate);
		parament.put("endDate",endDate);
		parament.put("orgKwd",orgKwd);
		parament.put("accountKwd",accountKwd);
		String taskNo = LocalDateTime.now().format(formatter);
		parament.put("serialNo",taskNo);
		parament.put("exportName",exportName);
		// 执行异步，并且设置成异步启动
		//export.execute(parament,true);
		export.marketingCourseAccountGroupExport(parament);


		return Response.ok("任务序号："+ taskNo+"。任务名称："+exportName+"_"+taskNo);
	}

	@ApiOperation(value = "按用户统计", notes = "按用户统计", response = ReportMarketingCourseAccountVo.class)	
    @GetMapping("/account/group")
    public Response<ReportMarketingCourseAccountVo> marketingCourseAccountGroup(
    		@ApiParam(value = "开始时间（yyyy-mm-dd）", required = true) @RequestParam(name = "startDate", required = true) String startDate, 
    		@ApiParam(value = "结束时间（yyyy-mm-dd）", required = true) @RequestParam(name = "endDate", required = true) String endDate, 
    		@ApiParam(value = "部门编码或名称", required = false) @RequestParam(name = "orgKwd", required = false) String orgKwd,    
    		@ApiParam(value = "用户关键字", required = false) @RequestParam(name = "accountKwd", required = false) String accountKwd,    
    		@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){
		// 获取部门编码或名称关联的orgId
		if(StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
			return Response.ok();
		}
		Long companyId = ContextHolder.get().getCompanyId();
		if(StringUtils.isNotBlank(orgKwd)){
			List<Long> orgIds = organizationClient.findOrgIdByNameOrCode(orgKwd,companyId);
			logger.info("根据组织关键字查询用户信息={}", JSON.toJSONString(orgIds));
			if(CollectionUtils.isEmpty(orgIds)){
				orgKwd = "-1";
			}else {
				orgKwd = orgIds.stream().map(Object :: toString).collect(Collectors.joining(","));
			}
		}

		// 获取用户关键字对应的用户id集合
		if(StringUtils.isNotBlank(accountKwd)){
			List<Long> accountIds = accountClient.findAIdsByKeyword(accountKwd,companyId);
			logger.info("根据用户关键字查询用户信息={}", JSON.toJSONString(accountIds));
			if(CollectionUtils.isEmpty(accountIds)){
				accountKwd = "-1";
			}else {
				accountKwd = accountIds.stream().map(Object :: toString).collect(Collectors.joining(","));
			}
		}

		Page<ReportMarketingCourseAccountVo> result =
				marketingCourseClient.marketingCourseAccountGroup(startDate,
						endDate,orgKwd,accountKwd,pageSize,pageNo);

		Map<String, Integer> pageMap = new HashMap<String, Integer>();
		pageMap.put("pageNo", pageNo);
		pageMap.put("pageSize", pageSize);
		List<ReportMarketingCourseAccountVo> ret = null;
		if(result != null){
			pageMap.put("pageTotal", result.getTotal());
			ret = result.getRecords();
			List<Long> aids = ret.stream().map(obj->obj.getAccountId()).collect(Collectors.toList());
			List<AccountVO> accountVOS = accountClient.findByIds(aids);
			Map<Long,AccountVO> retMap = new HashMap<>();
			if(!CollectionUtils.isEmpty(accountVOS)){
				retMap = accountVOS.stream().parallel().collect(Collectors.toMap(key->key.getId(),val->val));
			}
			for(ReportMarketingCourseAccountVo obj : ret ){
				Long key = obj.getAccountId();
				if(retMap.containsKey(key)){
					AccountVO accountVO = retMap.get(key);
					obj.setOrgName(accountVO.getOrgName());
					obj.setAccountName(accountVO.getName());
					obj.setAccountFullName(accountVO.getFullName());
				}
			}
		}

		
		return Response.ok(ret, pageMap);
	}

	@ApiOperation(value = "营销课程名-浏览数据 明细", notes = "营销课程名-浏览数据 明细",response = MarketingCourseViewVo.class)
	@GetMapping("/course/view/list")
	public Response<MarketingCourseViewVo> marketingCourseViewList(
			@ApiParam(value = "课程id", required = true) @RequestParam(name = "courseId") Long courseId,
			@ApiParam(value = "昵称关键字") @RequestParam(name = "nikeName",required = false) String nikeName,
			@ApiParam(value = "每页条数，默认10") @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize,
			@ApiParam(value = "当前页数") @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo){
		Page<MarketingCourseViewVo> data = marketingCourseClient.marketingCourseViewList(courseId, nikeName, pageSize, pageNo);
		return Response.ok(PageTools.split(data));
	}

	@ApiOperation(value = "营销课程名-浏览数据 明细", notes = "营销课程名-浏览数据 明细")
	@GetMapping("/course/view/list/export")
	public Response<String> marketingCourseViewListExport(
			@ApiParam(value = "课程id", required = true) @RequestParam(name = "courseId") Long courseId){
		//Page<MarketingCourseViewVo> data = marketingCourseClient.marketingCourseViewList(courseId, nikeName, pageSize, pageNo);
		RequestContext rt = ContextHolder.get();
		return Response.ok(export.marketingCourseViewListExport(courseId, rt.getSiteId(), rt.getAccountId(),rt.getCompanyId()));
	}
}
