package com.yunfeiyun.agmp.fms.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yunfeiyun.agmp.common.core.controller.BaseController;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.core.page.TableDataInfo;
import com.yunfeiyun.agmp.fms.domain.reqvo.SelectOfTssStatReqVo;
import com.yunfeiyun.agmp.fms.domain.resvo.SpmOrderOfTssStatResVo;
import com.yunfeiyun.agmp.fms.domain.resvo.SpmPayOfTssStatResVo;
import com.yunfeiyun.agmp.fms.service.IFmsTaskService;
import com.yunfeiyun.agmp.fms.service.ISpmOrderService;

/**
 * 溯源统计Controller
 * 
 * @author 马金朋
 * @date 2023-08-30
 */
@RestController
@RequestMapping("/tss/stat")
public class TssStatController extends BaseController {
	@Resource
	private ISpmOrderService spmOrderService;
	@Autowired
	private IFmsTaskService fmsTaskService;

	/**
	 * 统计概要：营收等情况
	 */
	@PreAuthorize("@ss.hasPermi('tss:stat:summary')")
	@GetMapping("/summary")
	public AjaxResult traceCodeStat(SelectOfTssStatReqVo reqVo) {
		reqVo.setStartTime(reqVo.getStartTime().substring(0, 4));
		Map<String, Object> moneyMap = getMoney(reqVo);
		// 总收入
		Double incomeTotal = Double.parseDouble(moneyMap.get("incomeTotal").toString());
		// 总支出
		Double payTotal = Double.parseDouble(moneyMap.get("payTotal").toString());
		// 总利润
		Double profitTotal = incomeTotal - payTotal;
		// 地块数量
		Integer dkNum = spmOrderService.selectDkCountOfTssTrace(reqVo);
		// 产品种类数量
		Integer goodsTypeNum = spmOrderService.selectGoodsTypeCountOfTssTrace(reqVo);

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("incomeTotal", incomeTotal);
		resultMap.put("payTotal", payTotal);
		resultMap.put("profitTotal", profitTotal);
		resultMap.put("dkNum", dkNum);
		resultMap.put("goodsTypeNum", goodsTypeNum);

		return AjaxResult.success(resultMap);
	}

	/**
	 * 投入成本占比
	 */
	@PreAuthorize("@ss.hasPermi('tss:stat:summary:pay')")
	@GetMapping("/summary/pay")
	public AjaxResult pay(SelectOfTssStatReqVo reqVo) {
		reqVo.setStartTime(reqVo.getStartTime().substring(0, 4));
		return AjaxResult.success(getMoney(reqVo));
	}

	/** 获取各类成本及收益的公共方法 */
	private Map<String, Object> getMoney(SelectOfTssStatReqVo reqVo) {
		Double incomeTotal = 0.0;// 总收入
		Double payTotal = 0.0;// 总支出()

		Double wlSum = 0.0;// 物流费用

		Double nzSum = 0.0;// 农资费用
		Double njSum = 0.0;// 农机费用
		Double rgSum = 0.0;// 人工费用

		Double jgSum = 0.0;// 加工费用
		Double bzSum = 0.0;// 包装费用
		Double csSum = 0.0;// 采收费用
		// 物流费用
		Map<String, Object> orderMap = spmOrderService.selectMoneyOfTssTrace(reqVo);
		if (orderMap != null) {
			incomeTotal = Double.parseDouble(orderMap.get("incomeSum").toString());
			wlSum = Double.parseDouble(orderMap.get("wlSum").toString());
		}

		// 农产品费用（采收，加工，包装）
		List<Map<String, Object>> goodsList = spmOrderService.selectFinishgoodsMoneyOfTssTrace(reqVo);
		if (goodsList != null) {
			for (Map<String, Object> goodsMap : goodsList) {
				if ("0".equals(goodsMap.get("finishgoodsType").toString())) {// 采收产品
					csSum = Double.parseDouble((goodsMap.get("sum") == null) ? "0" : goodsMap.get("sum").toString());
				} else if ("1".equals(goodsMap.get("finishgoodsType").toString())) {// 加工产品
					jgSum = Double.parseDouble((goodsMap.get("sum") == null) ? "0" : goodsMap.get("sum").toString());
				} else if ("2".equals(goodsMap.get("finishgoodsType").toString())) {// 包装产品
					bzSum = Double.parseDouble((goodsMap.get("sum") == null) ? "0" : goodsMap.get("sum").toString());
				}
			}
		}

		// 农活费用（人工，农机，农资）
		Map<String, Object> farmMap = fmsTaskService.selectSumTaskrcdMoney(reqVo);
		if (farmMap != null) {
			rgSum = Double.parseDouble((farmMap.get("rgSum") == null) ? "0" : farmMap.get("rgSum").toString());
			nzSum = Double.parseDouble((farmMap.get("nzSum") == null) ? "0" : farmMap.get("nzSum").toString());
			njSum = Double.parseDouble((farmMap.get("njSum") == null) ? "0" : farmMap.get("njSum").toString());
		}

		// 总支出
		payTotal = payTotal + wlSum + csSum + jgSum + bzSum + nzSum + njSum + rgSum;

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("incomeTotal", incomeTotal);
		resultMap.put("payTotal", payTotal);
		resultMap.put("wlSum", wlSum);
		resultMap.put("nzSum", nzSum);
		resultMap.put("njSum", njSum);
		resultMap.put("rgSum", rgSum);
		resultMap.put("jgSum", jgSum);
		resultMap.put("bzSum", bzSum);
		resultMap.put("csSum", csSum);
		List<Map<String, Object>> payMxList = new ArrayList<Map<String, Object>>();
		Map<String, Object> mxMap = null;
		mxMap = new HashMap<>();
		mxMap.put("key", "wlSum");
		mxMap.put("title", "物流");
		mxMap.put("value", wlSum);
		payMxList.add(mxMap);

		mxMap = new HashMap<>();
		mxMap.put("key", "nzSum");
		mxMap.put("title", "农资");
		mxMap.put("value", nzSum);
		payMxList.add(mxMap);

		mxMap = new HashMap<>();
		mxMap.put("key", "njSum");
		mxMap.put("title", "农机");
		mxMap.put("value", njSum);
		payMxList.add(mxMap);

		mxMap = new HashMap<>();
		mxMap.put("key", "rgSum");
		mxMap.put("title", "人工");
		mxMap.put("value", rgSum);
		payMxList.add(mxMap);

		mxMap = new HashMap<>();
		mxMap.put("key", "bzSum");
		mxMap.put("title", "包装");
		mxMap.put("value", bzSum);
		payMxList.add(mxMap);

		mxMap = new HashMap<>();
		mxMap.put("key", "jgSum");
		mxMap.put("title", "加工");
		mxMap.put("value", jgSum);
		payMxList.add(mxMap);

		mxMap = new HashMap<>();
		mxMap.put("key", "csSum");
		mxMap.put("title", "采收");
		mxMap.put("value", csSum);
		payMxList.add(mxMap);
		resultMap.put("payMxList", payMxList);

		return resultMap;
	}

	/**
	 * 年度收益/支出
	 */
	@PreAuthorize("@ss.hasPermi('tss:stat:summary:month:list')")
	@GetMapping("/summary/month/list")
	public AjaxResult monthPayList(SelectOfTssStatReqVo reqVo) {
		reqVo.setStartTime(reqVo.getStartTime().substring(0, 4));
		String year = reqVo.getStartTime().substring(0, 4) + "-";

		List<Map<String, Object>> incomeMoneyList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> payMoneyList = new ArrayList<Map<String, Object>>();
		Map<String, Object> payMap = null;
		Map<String, Object> incomeMoneyMap = null;
		for (int i = 0; i < 12; i++) {
			payMap = new HashMap<String, Object>();
			incomeMoneyMap = new HashMap<String, Object>();
			if (i + 1 <= 9) {
				payMap.put("time", year + "0" + (i + 1));// 月份
				incomeMoneyMap.put("time", year + "0" + (i + 1));// 月份
			} else {
				payMap.put("time", year + (i + 1));// 月份
				incomeMoneyMap.put("time", year + (i + 1));// 月份
			}
			payMoneyList.add(payMap);
			incomeMoneyList.add(incomeMoneyMap);
		}

		Double payTotal = 0.0;// 总支出()

		Double wlSum = 0.0;// 物流费用

		Double nzSum = 0.0;// 农资费用
		Double njSum = 0.0;// 农机费用
		Double rgSum = 0.0;// 人工费用

		Double jgSum = 0.0;// 加工费用
		Double bzSum = 0.0;// 包装费用
		Double csSum = 0.0;// 采收费用

		// 物流费用
		List<Map<String, Object>> orderList = spmOrderService.selectMoneyByMonthOfTssTrace(reqVo);
		Map<String, Map<String, Object>> orderGroupMap = null;
		if (orderList != null) {
			orderGroupMap = orderList.stream().collect(Collectors.toMap(e -> e.get("month").toString(), e -> e));
		}
		if (orderGroupMap == null) {
			orderGroupMap = new HashMap<String, Map<String, Object>>();
		}
		for (Map<String, Object> tempMap : incomeMoneyList) {
			tempMap.put("money", (orderGroupMap.get(tempMap.get("time")) == null) ? "0"
					: orderGroupMap.get(tempMap.get("time")).get("incomeSum"));
		}

		for (Map<String, Object> tempMap : payMoneyList) {
			tempMap.put("wlSum", (orderGroupMap.get(tempMap.get("time")) == null) ? "0"
					: orderGroupMap.get(tempMap.get("time")).get("wlSum"));
		}

		// 采收产品 0
		reqVo.setPayMxType("0");
		Map<String, Map<String, Object>> gooodsCsMap = spmOrderService.selectPayMonthByType(reqVo);
		for (Map<String, Object> tempMap : payMoneyList) {
			tempMap.put("csSum", gooodsCsMap.get(tempMap.get("time")) == null ? "0"
					: gooodsCsMap.get(tempMap.get("time")).get("money"));
		}

		// 加工产品 1
		reqVo.setPayMxType("1");
		Map<String, Map<String, Object>> gooodsJgMap = spmOrderService.selectPayMonthByType(reqVo);
		for (Map<String, Object> tempMap : payMoneyList) {
			tempMap.put("jgSum", (gooodsJgMap.get(tempMap.get("time")) == null) ? "0"
					: gooodsJgMap.get(tempMap.get("time")).get("money"));
		}

		// 包装产品 2
		reqVo.setPayMxType("2");
		Map<String, Map<String, Object>> gooodsBzMap = spmOrderService.selectPayMonthByType(reqVo);
		for (Map<String, Object> tempMap : payMoneyList) {
			tempMap.put("bzSum", (gooodsBzMap.get(tempMap.get("time")) == null) ? "0"
					: gooodsBzMap.get(tempMap.get("time")).get("money"));
		}

		Map<String, Map<String, Object>> fmsRgMap = fmsTaskService.selectPayMonthByRg(reqVo);
		for (Map<String, Object> tempMap : payMoneyList) {
			tempMap.put("rgSum",
					(fmsRgMap.get(tempMap.get("time")) == null) ? "0" : fmsRgMap.get(tempMap.get("time")).get("money"));
		}

		Map<String, Map<String, Object>> fmsNjMap = fmsTaskService.selectPayMonthByNj(reqVo);
		for (Map<String, Object> tempMap : payMoneyList) {
			tempMap.put("njSum",
					(fmsNjMap.get(tempMap.get("time")) == null) ? "0" : fmsNjMap.get(tempMap.get("time")).get("money"));
		}

		Map<String, Map<String, Object>> fmsNzMap = fmsTaskService.selectPayMonthByNz(reqVo);
		for (Map<String, Object> tempMap : payMoneyList) {
			tempMap.put("nzSum",
					(fmsNzMap.get(tempMap.get("time")) == null) ? "0" : fmsNzMap.get(tempMap.get("time")).get("money"));
		}

		// 总支出
		for (Map<String, Object> tempMap : payMoneyList) {
			wlSum = Double.parseDouble(tempMap.get("wlSum").toString());
			csSum = Double.parseDouble(tempMap.get("csSum").toString());
			jgSum = Double.parseDouble(tempMap.get("jgSum").toString());
			bzSum = Double.parseDouble(tempMap.get("bzSum").toString());
			nzSum = Double.parseDouble(tempMap.get("nzSum").toString());
			njSum = Double.parseDouble(tempMap.get("njSum").toString());
			rgSum = Double.parseDouble(tempMap.get("rgSum").toString());
			payTotal = wlSum + csSum + jgSum + bzSum + nzSum + njSum + rgSum;
			tempMap.put("money", payTotal);
			tempMap.remove("wlSum");
			tempMap.remove("csSum");
			tempMap.remove("jgSum");
			tempMap.remove("bzSum");
			tempMap.remove("nzSum");
			tempMap.remove("njSum");
			tempMap.remove("rgSum");
		}

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("incomeMoneyList", incomeMoneyList);
		resultMap.put("payMoneyList", payMoneyList);

		return AjaxResult.success(resultMap);
	}

	/**
	 * 查询支出/投入明细列表（分页）
	 */
	@PreAuthorize("@ss.hasPermi('tss:stat:spm:pay:list')")
	@GetMapping("/spm/pay/list")
	public TableDataInfo spmPayList(SelectOfTssStatReqVo reqVo) {
		reqVo.setStartTime(reqVo.getStartTime().substring(0, 4));
		startPage();
		List<SpmPayOfTssStatResVo> list = new ArrayList<SpmPayOfTssStatResVo>();
		if ("01".equals(reqVo.getPayType())) {// 物流
			list = spmOrderService.selectSpmOrderPayOfTssStatList(reqVo);
		} else if ("02".equals(reqVo.getPayType())) {// 农资
			list = fmsTaskService.selectPayByNz(reqVo);
		} else if ("03".equals(reqVo.getPayType())) {// 农机
			list = fmsTaskService.selectPayByNj(reqVo);
		} else if ("04".equals(reqVo.getPayType())) {// 人工
			list = fmsTaskService.selectPayByRg(reqVo);
		} else if ("05".equals(reqVo.getPayType())) {// 加工
			list = spmOrderService.selectPayByJg(reqVo);
		} else if ("06".equals(reqVo.getPayType())) {// 包装
			list = spmOrderService.selectPayByBz(reqVo);
		} else if ("07".equals(reqVo.getPayType())) {// 采收
			list = spmOrderService.selectPayByCs(reqVo);
		}
		logger.debug("/spm/pay/list返回：" + list);
		return getDataTable(list);
	}

	/**
	 * 溯源统计页面使用：产品销售地（气泡图）
	 */
	@PreAuthorize("@ss.hasPermi('tss:stat:spm:order:money:city')")
	@GetMapping("/spm/order/money/city")
	public AjaxResult spmOrderMoneyCity(SelectOfTssStatReqVo reqVo) {
		reqVo.setStartTime(reqVo.getStartTime().substring(0, 4));
		return AjaxResult.success(spmOrderService.selectMoneyGroupByCity(reqVo));
	}

	/**
	 * 溯源统计农产品销售额top10
	 */
	@PreAuthorize("@ss.hasPermi('tss:stat:spm:order:money')")
	@GetMapping("/spm/order/money")
	public AjaxResult spmOrderMoney(SelectOfTssStatReqVo reqVo) {
		if (null == reqVo.getLimitNum()) {
			reqVo.setLimitNum(10);
		}
		reqVo.setStartTime(reqVo.getStartTime().substring(0, 4));
		return AjaxResult.success(spmOrderService.selectSpmOrderMoneyByTssStat(reqVo));
	}

	/**
	 * 查询销售明细列表（分页）
	 */
	@PreAuthorize("@ss.hasPermi('tss:stat:spm:order:list')")
	@GetMapping("/spm/order/list")
	public TableDataInfo spmOrderList(SelectOfTssStatReqVo reqVo) {
		reqVo.setStartTime(reqVo.getStartTime().substring(0, 4));
		startPage();
		List<SpmOrderOfTssStatResVo> list = spmOrderService.selectSpmOrderOfTssStatList(reqVo);
		return getDataTable(list);
	}

}
