package cn.superdesk.uniorder.controller._dashboard;


import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dto.vo._dashboard.*;
import cn.superdesk.uniorder.dubbo.consumer._permission.PermissionDubboCustomerService;
import cn.superdesk.uniorder.dubbo.consumer._dashboard.BackendDashboardDubboConsumerService;
import cn.superdesk.uniorder.common.excel.utils.ExcelExportModePoiHssfUtils;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import com.alibaba.fastjson2.JSON;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Api(value = "Dashboard-后端-首页-看板导出excel",tags = "Dashboard-后端-首页-看板导出excel")
@Slf4j
@RestController
@RequestMapping("/dashboard/export")
public class BackendDashboardExportController extends BaseController {

	@Autowired
	private BackendDashboardDubboConsumerService unifiedDashboardDubboConsumerService;

	@Autowired
	private PermissionDubboCustomerService permissionDubboCustomerService;


	/***
	 * 项目采购情况
	 * @return
	 */
	@RequestMapping("/getDashboardProjectPurchase")
	public void getDashboardProjectPurchase(HttpServletResponse response) {


		try {

			String queryYearMonth = getString("queryYearMonth");

			Map<String, Object> params = new HashMap<>();
			params.put("virtIds", permissionDubboCustomerService.getPermOutVirtIds(getToken()));//用户权限企业
			params.put("queryYearMonth", queryYearMonth);

			log.info("getDashboardProjectPurchase 项目采购情况-参数params:{}", JSON.toJSONString(params));
			List<UnifiedDashboardProjectPurchaseVo> list = unifiedDashboardDubboConsumerService.getDashboardProjectPurchase(params);

			for (UnifiedDashboardProjectPurchaseVo vo : list) {
				vo.setTimeStr(queryYearMonth);
			}

			String[] field = {"timeStr", "projectName", "orderAmount"};

			String[] fieldZhCn = {"时间", "项目名称", "项目采购额(元)"};

			HSSFWorkbook workbook = ExcelExportModePoiHssfUtils.createWorkbook(list, fieldZhCn, field, "项目采购情况");
			//准备将Excel的输出流通过response输出到页面下载
			response.reset();
			//二进制输出流
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");
			//这后面可以设置导出Excel的名称,此例中名为student.xls
			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("项目采购情况-" + queryYearMonth, "UTF-8") + ".xls");
			//刷新缓冲
			response.flushBuffer();

			//workbook将Excel写入到response的输出流中,供页面下载
			workbook.write(response.getOutputStream());


		} catch (Exception e) {

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

	}


	/***
	 * 年度采购情况
	 * @return
	 */
	@RequestMapping("/getDashboardYearPurchase")
	public void getDashboardYearPurchase(HttpServletResponse response) {


		try {


			//List<SelectOptionOrg> listSelectOptionOrg = permissionDubboCustomerService.getSelectPermOrgByToken(getToken());
			//List<SelectOptionVirt> listSelectOptionVirt = permissionDubboCustomerService.getSelectPermVirtByToken(getToken());

			String queryYear = getString("queryYear");//年度

			Map<String, Object> params = new HashMap<>();
			params.put("queryYear", queryYear);
			params.put("projectId", getString("projectId"));
			params.put("virtId", getString("virtId"));//查询权限
			params.put("virtIds", permissionDubboCustomerService.getPermOutVirtIds(getToken()));//用户权限企业


			log.info("getDashboardYearPurchase 年度采购情况-参数params:{}", JSON.toJSONString(params));

			//获得1-12月采购情况-可能有的月份没有数据需处理
			//1	2039	138.92
			//2	2723	323.97
			//3	4213	208.66
			List<UnifiedDashboardYearPurchaseVo> list = unifiedDashboardDubboConsumerService.getDashboardYearPurchase(params);

			if (list.size() < 12) {//补充月份值
				List<Integer> listQueryMonth = list.stream().map(t -> t.getMonthNum()).collect(Collectors.toList());
				for (int i = 0; i <= 12; i++) {
					if (!listQueryMonth.contains(i)) {
						UnifiedDashboardYearPurchaseVo vo = new UnifiedDashboardYearPurchaseVo(i, 0, BigDecimal.ZERO);
						list.add(vo);
					}
				}
			}


			for (UnifiedDashboardYearPurchaseVo vo : list) {
				vo.setYearStr(queryYear + "年");
				vo.setMonthNumStr(vo.getMonthNum() + "月");

				vo.setProjectName(getString("projectName"));
				vo.setVirtName(getString("virtName"));

			}

			String[] field = {"yearStr", "monthNumStr", "projectName", "virtName", "orderAmount", "orderNum"};

			String[] fieldZhCn = {"时间(年)", "时间(月)", "项目名称", "企业名称", "项目采购额(元)", "订单数(条)"};

			HSSFWorkbook workbook = ExcelExportModePoiHssfUtils.createWorkbook(list, fieldZhCn, field, queryYear + "年度采购情况分析");
			//准备将Excel的输出流通过response输出到页面下载
			response.reset();
			//二进制输出流
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");
			//这后面可以设置导出Excel的名称,此例中名为student.xls
			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(queryYear + "年度采购情况分析", "UTF-8") + ".xls");
			//刷新缓冲
			response.flushBuffer();

			//workbook将Excel写入到response的输出流中,供页面下载
			workbook.write(response.getOutputStream());


		} catch (Exception e) {


			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

	}

	/***
	 * 项目采购对比分析<:3>
	 * @return
	 */
	@RequestMapping("/getDashboardProjectPurchaseCompare")
	public void getDashboardProjectPurchaseCompare(HttpServletResponse response) {


		try {

			String queryYearMonth = getString("queryYearMonth");

			Map<String, Object> params = new HashMap<>();
			params.put("checkedProjectIds", getString("checkedProjectIds"));
			params.put("virtIds", permissionDubboCustomerService.getPermOutVirtIds(getToken()));//用户权限企业
			params.put("queryYearMonth", queryYearMonth);


			log.info("getDashboardProjectPurchaseCompare 项目采购对比分析-参数params:{}", JSON.toJSONString(params));
			List<UnifiedDashboardProjectPurchaseCompareVo> list = unifiedDashboardDubboConsumerService.getDashboardProjectPurchaseCompare(params);

			for (UnifiedDashboardProjectPurchaseCompareVo vo : list) {
				vo.setTimeStr(queryYearMonth);
			}


			String[] field = {"timeStr", "projectName", "orderAmount"};

			String[] fieldZhCn = {"时间", "项目名称", "项目采购额(元)"};

			HSSFWorkbook workbook = ExcelExportModePoiHssfUtils.createWorkbook(list, fieldZhCn, field, "项目采购对比分析");
			//准备将Excel的输出流通过response输出到页面下载
			//二进制输出流
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");
			//这后面可以设置导出Excel的名称,此例中名为student.xls
			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("项目采购对比分析-" + queryYearMonth, "UTF-8") + ".xls");
			//刷新缓冲
			response.flushBuffer();

			//workbook将Excel写入到response的输出流中,供页面下载
			workbook.write(response.getOutputStream());


		} catch (Exception e) {


			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

	}


	/***
	 * 采购分类分析
	 * @return
	 */
	@RequestMapping("/getDashboardPurchaseCateCompare")
	public void getDashboardPurchaseCateCompare(HttpServletResponse response) {


		try {

			String queryYearMonth = getString("queryYearMonth");//月度

			Map<String, Object> params = new HashMap<>();
			params.put("queryYearMonth", queryYearMonth);
			params.put("projectId", getString("projectId"));
			params.put("virtId", getString("virtId"));//查询权限
			params.put("virtIds", permissionDubboCustomerService.getPermOutVirtIds(getToken()));//用户权限企业


			log.info("getDashboardPurchaseCateCompare 采购分类分析-参数params:{}", JSON.toJSONString(params));

			//获得1-12月采购情况-可能有的月份没有数据需处理
			//1	2039	138.92
			//2	2723	323.97
			//3	4213	208.66
			List<UnifiedDashboardPurchaseCateCompareVo> list       = unifiedDashboardDubboConsumerService.getDashboardPurchaseCateCompare(params);
			List<UnifiedDashboardPurchaseCateCompareVo> returnList = new ArrayList<>();


			Double         maxOrderAmount = Double.valueOf(0);
			OptionalDouble optionalDouble = list.stream().mapToDouble(t -> t.getOrderAmount().doubleValue()).max();//最大值
			if (optionalDouble.isPresent()) {
				maxOrderAmount = optionalDouble.getAsDouble();
			}
			BigDecimal sumOrderAmount   = list.stream().map(t -> t.getOrderAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);//总计
			BigDecimal bdMaxOrderAmount = new BigDecimal(maxOrderAmount);

			//返回前9
			//第10为其他
			int        num              = 1;
			BigDecimal totalSale        = BigDecimal.ZERO;//前9总占比
			BigDecimal totalOrderAmount = BigDecimal.ZERO;//前9总金额
			for (UnifiedDashboardPurchaseCateCompareVo vo : list) {

				if (num < 10) {
					vo.setScale(vo.getOrderAmount().divide(bdMaxOrderAmount, 1, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)));//占比
					totalSale = totalSale.add(vo.getScale());
					totalOrderAmount = totalOrderAmount.add(vo.getOrderAmount());
					returnList.add(vo);
				} else if (num == 10) {
					vo.setScale(new BigDecimal(100).subtract(totalSale));
					vo.setOrderAmount(sumOrderAmount.subtract(totalOrderAmount));
					vo.setCateName("其他");
					returnList.add(vo);
					break;
				}

				++num;
			}


			for (UnifiedDashboardPurchaseCateCompareVo vo : list) {
				vo.setTimeStr(queryYearMonth);
				vo.setProjectName(getString("projectName"));
				vo.setVirtName(getString("virtName"));
			}

			String[] field = {"timeStr", "projectName", "virtName", "cateName", "orderAmount", "scale"};

			String[] fieldZhCn = {"时间", "项目名称", "企业名称", "分类名称", "采购额(元)", "采购占比"};

			HSSFWorkbook workbook = ExcelExportModePoiHssfUtils.createWorkbook(list, fieldZhCn, field, "分类采购情况分析");
			//准备将Excel的输出流通过response输出到页面下载
			response.reset();
			//二进制输出流
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");
			//这后面可以设置导出Excel的名称,此例中名为student.xls
			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("分类采购情况分析-" + queryYearMonth, "UTF-8") + ".xls");
			//刷新缓冲
			response.flushBuffer();

			//workbook将Excel写入到response的输出流中,供页面下载
			workbook.write(response.getOutputStream());


		} catch (Exception e) {


			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

	}


	/***
	 * 商品采购情况排名
	 * @return
	 */
	@RequestMapping("/getDashboardGoodsPurchaseRanking")
	public void getDashboardGoodsPurchaseRanking(HttpServletResponse response) {

		R<Map> result    = new R<>();
		Map    returnMap = new HashMap();

		try {

			String queryYearMonth = getString("queryYearMonth");//月度

			Map<String, Object> params = new HashMap<>();
			params.put("queryYearMonth", queryYearMonth);
			params.put("virtIds", permissionDubboCustomerService.getPermOutVirtIds(getToken()));//用户权限企业
			String projectId = getString("projectId");
			String virtId    = getString("virtId");


			log.info("getDashboardPurchaseCateCompare 商品采购情况排名-参数params:{}", JSON.toJSONString(params));


			List<UnifiedDashboardGoodsPurchaseRankingVo> allList     = unifiedDashboardDubboConsumerService.getDashboardGoodsPurchaseRanking(params);
			List<UnifiedDashboardGoodsPurchaseRankingVo> projectList = allList;
			List<UnifiedDashboardGoodsPurchaseRankingVo> virtList    = allList;

			if (StringUtils.isNotEmpty(projectId)) {
				params.put("projectId", getString("projectId"));
				projectList = unifiedDashboardDubboConsumerService.getDashboardGoodsPurchaseRanking(params);
				virtList = projectList;
			}

			if (StringUtils.isNotEmpty(virtId)) {
				params.put("virtId", getString("virtId"));//查询权限
				virtList = unifiedDashboardDubboConsumerService.getDashboardGoodsPurchaseRanking(params);
			}


			for (UnifiedDashboardGoodsPurchaseRankingVo vo : allList) {
				vo.setTimeStr(queryYearMonth);
			}

			for (UnifiedDashboardGoodsPurchaseRankingVo vo : projectList) {
				vo.setTimeStr(queryYearMonth);
				vo.setProjectName(getString("projectName"));
				vo.setVirtName(getString("virtName"));
			}

			for (UnifiedDashboardGoodsPurchaseRankingVo vo : virtList) {
				vo.setTimeStr(queryYearMonth);
				vo.setProjectName(getString("projectName"));
				vo.setVirtName(getString("virtName"));
			}

			String[] field = {"timeStr", "goodsName", "orderAmount"};

			String[] fieldZhCn = {"时间", "商品名称", "采购额(元)"};

			HSSFWorkbook workbook = ExcelExportModePoiHssfUtils.createWorkbook(allList, fieldZhCn, field, "商品采购总排行Top10");


			String[] commonField    = {"timeStr", "projectName", "virtName", "goodsName", "orderAmount"};
			String[] commonFsieldZn = {"时间", "项目名称", "企业名称", "商品名称", "采购额(元)"};
			workbook = ExcelExportModePoiHssfUtils.createSheetByWorkbook(projectList, commonFsieldZn, commonField, workbook, "项目采购总排行Top10");


			workbook = ExcelExportModePoiHssfUtils.createSheetByWorkbook(virtList, commonFsieldZn, commonField, workbook, "企业采购总排行Top10");


			//准备将Excel的输出流通过response输出到页面下载
			response.reset();
			//二进制输出流
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");
			//这后面可以设置导出Excel的名称,此例中名为student.xls
			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("商品采购情况排名-" + queryYearMonth, "UTF-8") + ".xls");
			//刷新缓冲
			response.flushBuffer();

			//workbook将Excel写入到response的输出流中,供页面下载
			workbook.write(response.getOutputStream());


		} catch (Exception e) {

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

	}


}
