package com.ylcm.sys.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ylcm.sys.common.Constants;
import com.ylcm.sys.common.ExcelUtil;
import com.ylcm.sys.domain.AdSpecial;
import com.ylcm.sys.enums.AdSpecialShowEnvEnum;
import com.ylcm.sys.enums.AdSpecialTypeEnum;
import com.ylcm.sys.excel.model.SpecialAnalysisExportDTO;
import com.ylcm.sys.form.AdSpecialAnalysisBenchmarkingQueryForm;
import com.ylcm.sys.form.AdSpecialAnalysisQueryForm;
import com.ylcm.sys.service.AdSpecialService;
import com.ylcm.sys.service.SpecialAnalysisService;
import com.ylcm.sys.vo.AdSpecialAnalysisBenchmarkingVO;
import com.ylcm.sys.vo.AdSpecialAnalysisVO;
import com.ylcm.sys.vo.AdSpecialDistVO;
import com.ylcm.sys.vo.AdSpecialTopVO;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

@Slf4j
@Controller
@RequestMapping("/special_analysis")
public class SpecialAnalysisController extends BaseController{

	@Resource
	private SpecialAnalysisService specialAnalysisService;
	@Resource
	private AdSpecialService adSpecialService;
	
	/**
	 * @param type 产品类型  
	 * @param keyword 产品名称
	 * @return
	 */
	@RequestMapping(value = "/index.do")
	public String brandAnalysis(ModelMap model, Integer type, String keyword) {

		/**
		 * 1.跳转到列表页面
		 */
		model.put("type", type);
		model.put("keyword", keyword);
		return "analysis/special_analysis";
	}
	
	@RequestMapping(value = "/ajax_list.do")
	public void ajaxSearchList(HttpServletResponse response, AdSpecialAnalysisQueryForm queryForm) {
		try {
			
			IPage<AdSpecialAnalysisVO> page = specialAnalysisService.page(queryForm);
			/**
			 *  处理播出环境	
			 */
			if(page!= null && CollectionUtils.isNotEmpty(page.getRecords())) {
				page.getRecords().stream().forEach(x ->{
					x.setShowEnvMsg(AdSpecialShowEnvEnum.getMsgByVal(x.getShowEnv()));
				});
			}
			/**
			 * 3.返回结果
			 */
			JSONObject jsonobj = new JSONObject();
			jsonobj.put("data", page);
			jsonobj.put("code", Constants.CODE_SUCCESS);
			ajaxJson(jsonobj.toString(), response);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			ajaxJson("{\"code\":\"0\",\"msg\":\"获取列表失败\"}", response);
		}
	}
	
	//产品专题广告投放排名
	@RequestMapping(value = "/product_rank.do")
	public void list_special_product_rank(HttpServletResponse response, Integer type, String startDate, String endDate) {
		try {
			
			List<AdSpecialTopVO> list = specialAnalysisService.specialTop(type, startDate, endDate);
			
			JSONObject jsonobj = new JSONObject();
			jsonobj.put("data", list);
			jsonobj.put("code", Constants.CODE_SUCCESS);
			ajaxJson(jsonobj.toString(), response);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			ajaxJson("{\"code\":\"0\",\"msg\":\"获取列表失败\"}", response);
		}
	}
	
	// 投放媒体分布
	@RequestMapping(value = "/media_dist.do")
	public void media_dist(HttpServletResponse response, Integer type, String productName, String startDate, String endDate) {
		try {
			
			List<AdSpecialDistVO> list = specialAnalysisService.mediaDist(type, productName, startDate, endDate);
			
			JSONObject jsonobj = new JSONObject();
			jsonobj.put("data", list);
			jsonobj.put("code", Constants.CODE_SUCCESS);
			ajaxJson(jsonobj.toString(), response);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			ajaxJson("{\"code\":\"0\",\"msg\":\"获取列表失败\"}", response);
		}
	}
	
	// 电视剧分布
	@RequestMapping(value = "/tv_dist.do")
	public void tv_dist(HttpServletResponse response, Integer type, String productName, String startDate, String endDate) {
		try {
			
			List<AdSpecialDistVO> list = specialAnalysisService.tvDist(type, productName, startDate, endDate);
			
			JSONObject jsonobj = new JSONObject();
			jsonobj.put("data", list);
			jsonobj.put("code", Constants.CODE_SUCCESS);
			ajaxJson(jsonobj.toString(), response);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			ajaxJson("{\"code\":\"0\",\"msg\":\"获取列表失败\"}", response);
		}
	}
	// 二级行业广告投放品牌分布
	@RequestMapping(value = "/second_ind_dist.do")
	public void second_ind_dist(HttpServletResponse response, Integer type, Integer launch, String secondInd, String startDate, String endDate) {
		try {
			
			List<AdSpecialDistVO> list = specialAnalysisService.secondIndDist(type, launch, secondInd, startDate, endDate);
			
			JSONObject jsonobj = new JSONObject();
			jsonobj.put("data", list);
			jsonobj.put("code", Constants.CODE_SUCCESS);
			ajaxJson(jsonobj.toString(), response);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			ajaxJson("{\"code\":\"0\",\"msg\":\"获取列表失败\"}", response);
		}
	}
	
	// 专题广告数据分析导出
	@RequestMapping(value = "/export.do")
    public void export(AdSpecialAnalysisQueryForm queryForm,
    		HttpServletRequest request, HttpServletResponse response) {
		
		String fileName =  queryForm.getType() == null ? "专题数据分析列表" :
				AdSpecialTypeEnum.PRODUCT.getCode().equals(queryForm.getType()) ? "专题广告数据分析列表" : "专题栏目数据分析列表";
		ExcelUtil.exportExcelToWebsite(response,fileName,new SpecialAnalysisExportDTO(),(currentPage, pageSize) -> {
			queryForm.setPageNo(currentPage);
			queryForm.setPageSize(pageSize);
			return toExport(specialAnalysisService.page(queryForm).getRecords());
		});
    }
	
	private List<SpecialAnalysisExportDTO> toExport(List<AdSpecialAnalysisVO> list) {
		List<SpecialAnalysisExportDTO> exportDTOs = new ArrayList<SpecialAnalysisExportDTO>();
		if (CollectionUtils.isNotEmpty(list)) {
			list.stream().forEach(x ->{
				exportDTOs.add(new SpecialAnalysisExportDTO.SpecialAnalysisExportDTOBuilder().adSpecialAnalysisVO(x).build());
			});
		}
		return exportDTOs;
	}
	
	// 对标分析--->跳转到对标页面
	@RequestMapping(value = "/benchmarking.do")
	public String benchmarking(ModelMap model, Integer type, String ids, String startDate ,String endDate, String day) {
		if(type == null) {
			return "redirect:index.do";
		}
		if(StringUtils.isNotBlank(ids)) {
			AdSpecialAnalysisBenchmarkingQueryForm queryForm = new AdSpecialAnalysisBenchmarkingQueryForm(type,ids);
			queryForm.toQueryForm();
			queryForm.setPageSize(3); //最大限制3个产品
			IPage<AdSpecialAnalysisBenchmarkingVO> page = specialAnalysisService.benchmarkingPage(queryForm);
			if(page!= null && CollectionUtils.isNotEmpty(page.getRecords())) {
				model.addAttribute("brandList", page.getRecords());
				model.addAttribute("brandNameList",StringUtils.join(page.getRecords().stream().map(x -> x.getProductName()).collect(Collectors.toList()),"|"));
				model.addAttribute("brandIdList",StringUtils.join(page.getRecords().stream().map(x -> x.getId()).collect(Collectors.toList()),"|"));
			}
		}
		model.addAttribute("type", type);
		model.addAttribute("startDate", startDate);
		model.addAttribute("endDate", endDate);
		model.addAttribute("day", day);
		return "analysis/benchmarking";
	}
	
	@RequestMapping(value = "/add_benchmarking.do")
	public String detail(ModelMap model, Integer type, String ids, String startDate ,String endDate ,String day) {
		if(type == null) {
			return "redirect:index.do";
		}
        model.put("type", type);
        model.put("ids", ids);
        model.addAttribute("startDate", startDate);
		model.addAttribute("endDate", endDate);
		model.addAttribute("day", day);
        return "analysis/benchmark_brand_choose";
	}
	
	// 行业广告对标产品下拉列表
	@RequestMapping(value = "/benchmarking_list.do")
	public void brand_dist(HttpServletResponse response, AdSpecialAnalysisBenchmarkingQueryForm queryForm) {
		JSONObject jsonobj = new JSONObject();
		try {
	    //获取已对标的产品名		
	    queryForm.toQueryForm();
	    if(CollectionUtils.isNotEmpty(queryForm.getIdList())) {
	    	Collection<AdSpecial> adSpecialList = adSpecialService.listByIds(queryForm.getIdList());
	    	List<String> productNameList = adSpecialList.stream().map(x -> x.getProductName()).collect(Collectors.toList());
	    	queryForm.setProductNameList(productNameList);
	    	queryForm.setIdList(null);
	    }
		//获取未对标的产品名
		IPage<AdSpecialAnalysisBenchmarkingVO> page = specialAnalysisService.benchmarkingPage(queryForm);
		JSONArray results = new JSONArray();
		for (AdSpecialAnalysisBenchmarkingVO select : page.getRecords()) {
			JSONObject obj = new JSONObject();
			obj.put("id", select.getId());
			obj.put("text", select.getProductName());
			results.add(obj);
		}
		jsonobj.put("results", results);
		jsonobj.put("total", page.getTotal());
		ajaxJson(jsonobj.toString(), response);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			ajaxJson(jsonobj.toString(), response);
		}
	}
}
