/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.projectcontentinfo.web;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.projectcontentinfo.entity.ProjectReportDataCompany;
import com.jeeplus.modules.projectcontentinfo.entity.ProjectReportDataInfo;
import com.jeeplus.modules.projectcontentinfo.entity.ProjectReportDataMonth;
import com.jeeplus.modules.projectcontentinfo.entity.ProjectReportDataOffice;
import com.jeeplus.modules.projectcontentinfo.service.ProjectReportStatisticsService;
import com.jeeplus.modules.sys.dao.OfficeDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 合同评价表Controller
 * @author 杨帆
 * @version 2018-03-23
 */
@Controller
@RequestMapping(value = "${adminPath}/projectreportstatistics/projectreportstatistics")
public class ProjectReportStatisticsController extends BaseController {

	@Autowired
	private ProjectReportStatisticsService projectReportStatisticsService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private OfficeDao officeDao;

	private List<String> xAxisData;
	private Map<String,List<Double>> yAxisData;
	private Map<String,Integer> yAxisIndex;
	private Map<String,Object> orientData;

	/**
	 * 合同评价信息列表页面
	 */
	@RequiresPermissions("projectreportstatistics:projectreportstatistics:list")
	@RequestMapping(value = {"list", ""})
	public String list(ProjectReportDataCompany projectReportDataCompany, HttpServletRequest request,
					   HttpServletResponse response, Model model,RedirectAttributes redirectAttributes) {
		int count = UserUtils.getSelectRoleMax();
		model.addAttribute("roleMax",count);
		if (count == 4){
			if (StringUtils.isBlank(projectReportDataCompany.getDate())){
				projectReportDataCompany.setDate(getYear(new Date()));
			}
			if (StringUtils.isNotBlank(projectReportDataCompany.getCheck()) && projectReportDataCompany.getCheck().equals("1")){
				ProjectReportDataMonth projectReportDataMonth = new ProjectReportDataMonth();
				projectReportDataMonth.setCompanyId(projectReportDataCompany.getCompanyId());
				projectReportDataMonth.setOfficeId(projectReportDataCompany.getOfficeId());
				projectReportDataMonth.setDate(projectReportDataCompany.getDate());
				List<ProjectReportDataMonth> list = new ArrayList<>();
				list = projectReportStatisticsService.findMonthCompanyList(projectReportDataMonth);
				model.addAttribute("list", list);
				model.addAttribute("showName", "月份");
				request.setAttribute("xAxisData", getxAxisData(list, 3));
				request.setAttribute("yAxisData", getyAxisData(list, 3));
				request.setAttribute("orientData", getorientData(list, 3));
			}else {
				if(StringUtils.isNotBlank(projectReportDataCompany.getCompanyId())){
					request.setAttribute("backState",1);
				}
				model.addAttribute("showName", "分公司");
				List<ProjectReportDataCompany> list = projectReportStatisticsService.findCompanyList(projectReportDataCompany);
				model.addAttribute("list", list);
				request.setAttribute("xAxisData", getxAxisData(list, 1));
				request.setAttribute("yAxisData", getyAxisData(list, 1));
				request.setAttribute("orientData", getorientData(list, 1));
			}
		}else if (count == 3){
			if(isOffice()){//如果所在分公司下没有子公司
				return "redirect:"+Global.getAdminPath()+"/projectreportstatistics/projectreportstatistics/officeList?repage";
			}
			if (StringUtils.isBlank(projectReportDataCompany.getDate())){
				projectReportDataCompany.setDate(getYear(new Date()));
			}
			if (StringUtils.isNotBlank(projectReportDataCompany.getCheck()) && projectReportDataCompany.getCheck().equals("1")){
				ProjectReportDataMonth projectReportDataMonth = new ProjectReportDataMonth();
				projectReportDataMonth.setCompanyId(projectReportDataCompany.getCompanyId());
				projectReportDataMonth.setOfficeId(projectReportDataCompany.getOfficeId());
				projectReportDataMonth.setDate(projectReportDataCompany.getDate());
				List<ProjectReportDataMonth> list = new ArrayList<>();
				list = projectReportStatisticsService.findMonthCompanyList(projectReportDataMonth);
				model.addAttribute("list", list);
				model.addAttribute("showName", "月份");
				request.setAttribute("xAxisData", getxAxisData(list, 3));
				request.setAttribute("yAxisData", getyAxisData(list, 3));
				request.setAttribute("orientData", getorientData(list, 3));
			}else {
				if(StringUtils.isNotBlank(projectReportDataCompany.getCompanyId())){
					request.setAttribute("backState",1);
				}
				model.addAttribute("showName", "分公司");
				List<ProjectReportDataCompany> list = projectReportStatisticsService.findBranchList(projectReportDataCompany);
				model.addAttribute("list", list);
				request.setAttribute("xAxisData", getxAxisData(list, 1));
				request.setAttribute("yAxisData", getyAxisData(list, 1));
				request.setAttribute("orientData", getorientData(list, 1));
			}
			return "modules/projectreportstatistics/projectReportCompanyList";
		}else if (count == 2){
			return "redirect:"+Global.getAdminPath()+"/projectreportstatistics/projectreportstatistics/infoList?repage";
		}else {
			request.setAttribute("xAxisData",new ArrayList<>());
			request.setAttribute("yAxisData",new HashMap<String,List<Double>>());
			request.setAttribute("orientData",new HashMap<String,Object>());
			model.addAttribute("list", new ArrayList<>());
		}
		return "modules/projectreportstatistics/projectReportCompanyList";
	}

	/**
	 * 合同评价信息列表页面
	 */
	@RequiresPermissions("projectreportstatistics:projectreportstatistics:list")
	@RequestMapping(value = "officeList")
	public String officeList(ProjectReportDataOffice projectReportDataOffice, HttpServletRequest request,
							 HttpServletResponse response, Model model,RedirectAttributes redirectAttributes) {
		int count = UserUtils.getSelectRoleMax();
		model.addAttribute("roleMax",count);
		if (StringUtils.isBlank(projectReportDataOffice.getDate())){
			Date date = new Date();
			projectReportDataOffice.setDate(getYear(date));
		}
		if (StringUtils.isNotBlank(projectReportDataOffice.getCheck()) && projectReportDataOffice.getCheck().equals("1")){
			ProjectReportDataMonth projectReportDataMonth = new ProjectReportDataMonth();
			projectReportDataMonth.setOfficeId(projectReportDataOffice.getOfficeId());
			projectReportDataMonth.setCompanyId(projectReportDataOffice.getCompanyId());
			projectReportDataMonth.setDate(projectReportDataOffice.getDate());
			List<ProjectReportDataMonth> list = projectReportStatisticsService.findOfficeCompanyList(projectReportDataMonth);
			model.addAttribute("list", list);
			model.addAttribute("showName", "月份");
			request.setAttribute("xAxisData", getxAxisData(list, 3));
			request.setAttribute("yAxisData", getyAxisData(list, 3));
			request.setAttribute("orientData", getorientData(list, 3));
		}else {
			if(StringUtils.isNotBlank(projectReportDataOffice.getCompanyId())){
				request.setAttribute("backState",1);
			}
			List<ProjectReportDataOffice> list = projectReportStatisticsService.findListByOffice(projectReportDataOffice);
			model.addAttribute("list", list);
			model.addAttribute("showName", "部门");
			request.setAttribute("xAxisData", getxAxisData(list, 2));
			request.setAttribute("yAxisData", getyAxisData(list, 2));
			request.setAttribute("orientData", getorientData(list, 2));
		}

		return "modules/projectreportstatistics/projectReportOfficeList";
	}

	/**
	 * 合同评价信息列表页面
	 */
	@RequiresPermissions("projectreportstatistics:projectreportstatistics:list")
	@RequestMapping(value = "infoList")
	public String infoList(ProjectReportDataInfo projectReportDataInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		int count = UserUtils.getSelectRoleMax();
		model.addAttribute("roleMax",count);
		if(StringUtils.isNotBlank(projectReportDataInfo.getOfficeId())){
			request.setAttribute("backState",1);
		}
		if (StringUtils.isBlank(projectReportDataInfo.getDate())){
			Date date = new Date();
			projectReportDataInfo.setDate(getYear(date));
		}
		Page<ProjectReportDataInfo> page = projectReportStatisticsService.findPageByInfo(new Page<ProjectReportDataInfo>(request, response),projectReportDataInfo);
		model.addAttribute("page",page);
		return "modules/projectreportstatistics/projectReportInfoList";
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("projectreportstatistics:projectreportstatistics:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(ProjectReportDataCompany projectReportDataCompany, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			if (StringUtils.isBlank(projectReportDataCompany.getCheck())){
				String fileName = "合同统计表-分公司"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
				List<ProjectReportDataCompany> list = projectReportStatisticsService.findCompanyList(projectReportDataCompany);
				String agent = request.getHeader("USER-AGENT");
				new ExportExcel("合同统计表-分公司", ProjectReportDataCompany.class).setDataList(list).write(response, fileName,agent).dispose();
				return null;
			}else {
				String fileName = "合同统计表-分公司"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
				ProjectReportDataMonth projectReportDataMonth = new ProjectReportDataMonth();
				projectReportDataMonth.setCompanyId(projectReportDataCompany.getCompanyId());
				projectReportDataMonth.setOfficeId(projectReportDataCompany.getOfficeId());
				projectReportDataMonth.setDate(projectReportDataCompany.getDate());
				List<ProjectReportDataMonth> list = new ArrayList<>();
				if (StringUtils.isBlank(projectReportDataCompany.getCompanyId()) || StringUtils.isBlank(projectReportDataCompany.getName())){
					list = projectReportStatisticsService.findMonthCompanyList(projectReportDataMonth);
				}else {
					list = projectReportStatisticsService.findMonthCompanyList(projectReportDataMonth);
				}
				String agent = request.getHeader("USER-AGENT");
				new ExportExcel("合同统计表-分公司", ProjectReportDataCompany.class).setDataList(list).write(response, fileName,agent).dispose();
				return null;
			}

		} catch (Exception e) {
			addMessage(redirectAttributes, "导出合同统计表-分公司记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/projectreportstatistics/projectreportstatistics/list?repage";
    }
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("projectreportstatistics:projectreportstatistics:export")
	@RequestMapping(value = "exportOffice", method=RequestMethod.POST)
	public String exportFileOffice(ProjectReportDataOffice projectReportDataOffice, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			if (StringUtils.isBlank(projectReportDataOffice.getCheck())) {
				String fileName = "合同统计表-部门" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
				List<ProjectReportDataOffice> list = projectReportStatisticsService.findListByOffice(projectReportDataOffice);
				String agent = request.getHeader("USER-AGENT");
				new ExportExcel("合同统计表-部门", ProjectReportDataOffice.class).setDataList(list).write(response, fileName, agent).dispose();
				return null;
			}else {
				String fileName = "合同统计表-部门"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
				ProjectReportDataMonth projectReportDataMonth = new ProjectReportDataMonth();
				projectReportDataMonth.setOfficeId(projectReportDataOffice.getOfficeId());
				projectReportDataMonth.setDate(projectReportDataOffice.getDate());
				projectReportDataMonth.setCompanyId(projectReportDataOffice.getCompanyId());
				List<ProjectReportDataMonth> list = projectReportStatisticsService.findOfficeCompanyList(projectReportDataMonth);
				String agent = request.getHeader("USER-AGENT");
				new ExportExcel("合同统计表-部门", ProjectReportDataOffice.class).setDataList(list).write(response, fileName,agent).dispose();
				return null;
			}
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出合同统计表-部门记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/projectreportstatistics/projectreportstatistics/officeList?repage";
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("projectreportstatistics:projectreportstatistics:export")
	@RequestMapping(value = "exportInfo", method=RequestMethod.POST)
	public String exportFileInfo(ProjectReportDataInfo ProjectReportDataInfo, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "合同统计表-明细"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			Page<ProjectReportDataInfo> page = projectReportStatisticsService.findPageByInfo(new Page<ProjectReportDataInfo>(request, response),ProjectReportDataInfo);
			String agent = request.getHeader("USER-AGENT");
			new ExportExcel("合同统计表-明细", ProjectReportDataInfo.class).setDataList(page.getList()).write(response, fileName,agent).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出合同统计表-明细记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/projectreportstatistics/projectreportstatistics/infoList?repage";
	}

	public List<String> getxAxisData(List list,int type){
		xAxisData = new ArrayList<String>();
		if (type == 1){
			for(ProjectReportDataCompany w:(List<ProjectReportDataCompany>)list){
				if (!w.getName().equals("合计"))
				xAxisData.add(w.getName());
			}
		}else if (type == 2){
			for(ProjectReportDataOffice w:(List<ProjectReportDataOffice>)list){
				if (!w.getName().equals("合计"))
				xAxisData.add(w.getName());
			}
		}else{
			for(ProjectReportDataMonth w:(List<ProjectReportDataMonth>)list){
				if (!w.getName().equals("合计"))
					xAxisData.add(w.getName());
			}
		}

		return xAxisData;
	}

	public Map<String,List<Double>> getyAxisData(List list,int type){
		Random random = new Random();
		yAxisData = new HashMap<String,List<Double>>();
		List<Double> data = new ArrayList<Double>();
		if (type == 1){
			for(ProjectReportDataCompany w:(List<ProjectReportDataCompany>)list){
				if (!w.getName().equals("合计"))
				data.add((double)w.getReportCount());
			}
		}else if (type == 2){
			for(ProjectReportDataOffice w:(List<ProjectReportDataOffice>)list){
				if (!w.getName().equals("合计"))
				data.add((double)w.getReportCount());
			}
		}else{
			for(ProjectReportDataMonth w:(List<ProjectReportDataMonth>)list){
				if (!w.getName().equals("合计"))
					data.add((double)w.getReportCount());
			}
		}
		yAxisData.put("报告数量", data);
		return yAxisData;
	}
	//饼图
	public Map<String,Object> getorientData(List list,int type){
		orientData = new HashMap<String,Object>();
		List<Integer> data = new ArrayList<Integer>();
		if (type == 1){
			for(ProjectReportDataCompany w:(List<ProjectReportDataCompany>)list){
				if (!w.getName().equals("合计"))
				orientData.put(w.getName(),w.getReportCount());
			}
		}else if (type == 2){
			for(ProjectReportDataOffice w:(List<ProjectReportDataOffice>)list){
				if (!w.getName().equals("合计"))
				orientData.put(w.getName(),w.getReportCount());
			}
		}else{
			for(ProjectReportDataMonth w:(List<ProjectReportDataMonth>)list){
				if (!w.getName().equals("合计"))
					orientData.put(w.getName(),w.getReportCount());
			}
		}
		return orientData;
	}

	public static String getYear(Date date){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String str = format.format(date);
		return str.substring(0,4);
	}

	public static Map<String,String> getDate(){
		Map<String,String> map = new HashMap<>();
		Calendar cale = null;
		cale = Calendar.getInstance();
		int year = cale.get(Calendar.YEAR);
		int month = cale.get(Calendar.MONTH) + 1;
		int day = cale.get(Calendar.DATE);
		int hour = cale.get(Calendar.HOUR_OF_DAY);
		int minute = cale.get(Calendar.MINUTE);
		int second = cale.get(Calendar.SECOND);
		int dow = cale.get(Calendar.DAY_OF_WEEK);
		int dom = cale.get(Calendar.DAY_OF_MONTH);
		int doy = cale.get(Calendar.DAY_OF_YEAR);
		//System.out.println("Current Date: " + cale.getTime());
		map.put("date",cale.getTime()+"");
		//System.out.println("Year: " + year);
		map.put("year",year+"");
		//System.out.println("Month: " + month);
		map.put("month",month+"");
		//System.out.println("Day: " + day);
		map.put("day",day+"");
		//System.out.println("Hour: " + hour);
		map.put("hour",hour+"");
		//System.out.println("Minute: " + minute);
		map.put("minute",minute+"");
		//System.out.println("Second: " + second);
		map.put("second",second+"");
		//System.out.println("Day of Week: " + dow);
		map.put("dow",dow+"");
		//System.out.println("Day of Month: " + dom);
		map.put("dom",dom+"");
		//System.out.println("Day of Year: " + doy);
		map.put("doy",doy+"");


		// 获取当月第一天和最后一天
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String firstday, lastday;
		// 获取前月的第一天
		cale = Calendar.getInstance();
		cale.add(Calendar.MONTH, 0);
		cale.set(Calendar.DAY_OF_MONTH, 1);
		firstday = format.format(cale.getTime());
		// 获取前月的最后一天
		cale = Calendar.getInstance();
		cale.add(Calendar.MONTH, 1);
		cale.set(Calendar.DAY_OF_MONTH, 0);
		lastday = format.format(cale.getTime());
		System.out.println("本月第一天和最后一天分别是 ： " + firstday + " and " + lastday);
		// 获取当前日期字符串
		Date d = new Date();
		System.out.println("当前日期字符串1：" + format.format(d));
		System.out.println("当前日期字符串2：" + year + "/" + month + "/" + day + " "
				+ hour + ":" + minute + ":" + second);
		map.put("dateStr1",format.format(d));
		map.put("dateStr2",year + "/" + month + "/" + day + " "
				+ hour + ":" + minute + ":" + second);
		return map;
	}
	//分公司下是否存在子公司
	public Boolean isOffice(){
		String companyId= UserUtils.getSelectBranchOffice();
		List<Office>office=	officeDao.getAllBranch(companyId);
		if(office!=null&&office.size()>0){
			return false;
		}else{
			return true;
		}
	}
}