package cn.superdesk.uniorder.controller.marketing;

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterprise;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedOrderLastMonth;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedStatisticsVirtVo;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysEnterpriseDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.marketing.UnifiedStatisticsVirtCommonDubboConsumerService;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@RestController
@RequestMapping("/statistics")
public class UnifiedStatisticsVirtCommonController extends BaseController {


	@Autowired
	private UnifiedStatisticsVirtCommonDubboConsumerService unifiedStatisticsVirtDubboConsumerService;
	@Autowired
	private SysEnterpriseDubboConsumerService               sysEnterpriseDubboConsumerService;
	////戴德粮行统计

	/**
	 * 企业统计列表
	 *
	 * @return
	 */
	@PostMapping("/data")
	@ResponseBody
	public R<List<UnifiedStatisticsVirtVo>> userdata() {

		R<List<UnifiedStatisticsVirtVo>> result = new R<>();

		try {

			Map<String, Object> params = new HashMap<>();

			if (!StringUtils.isEmpty(getString("virtIds"))) {
				String[] virtIds = getString("virtIds").split(",");
				params.put("virtIds", virtIds);
			}

			// params.put("virtIds", getLong("virtIds"));
			String dt = getString("dt");
			if (StringUtils.isEmpty(dt)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
				dt = sdf.format(DateUtil.date());
			}

			params.put("sYear", dt.substring(0, 4));
			params.put("sMonth", dt.substring(5));

			List<UnifiedStatisticsVirtVo> data = unifiedStatisticsVirtDubboConsumerService.findAllVo(params);

			if (!StringUtils.isEmpty(getString("virtIds"))) {

				String[] virtIds = getString("virtIds").split(",");

				if (virtIds.length != data.size()) {

					for (int i = 0; i < virtIds.length; i++) {
						String vi = virtIds[i];
						if (vi != "") {
							boolean exists = false;
							for (UnifiedStatisticsVirtVo item : data) {
								if (item.getVirtId().toString().equals(vi)) {
									exists = true;
									break;
								}
							}
							if (!exists) {

								UnifiedStatisticsVirtVo vo = new UnifiedStatisticsVirtVo();

								vo.setVirtId(Long.parseLong(vi));
								SysEnterprise virt = sysEnterpriseDubboConsumerService.findByVirtId(Long.parseLong(vi));
								vo.setVirtName(virt.getEnterpriseName());

								vo.setQuantity(0);

								vo.setSMonth(Integer.parseInt(dt.substring(5)));
								vo.setSYear(Integer.parseInt(dt.substring(0, 4)));

								/****************************************** mark by linjinyu at 20201125 重构 start ******************************************/
								vo.setOrderAmount(new BigDecimal("0"));
								vo.setOrderCostAmount(new BigDecimal("0"));
								vo.setOrderRefundAmount(new BigDecimal("0"));
								vo.setOrderRefundCostAmount(new BigDecimal("0"));
								vo.setOrderTransportAmount(new BigDecimal("0"));

								vo.setGoodsAmount(new BigDecimal("0"));
								vo.setGoodsCostAmount(new BigDecimal("0"));
								vo.setGoodsRefundAmount(new BigDecimal("0"));
								vo.setGoodsRefundCostAmount(new BigDecimal("0"));
								vo.setGoodsTransportAmount(new BigDecimal("0"));

								/****************************************** mark by linjinyu at 20201125 重构   end ******************************************/
								vo.setPayableAmount(new BigDecimal("0"));


								data.add(vo);
							}
						}
					}
				}
			}

			result.setSuccess(true);
			result.setData(data);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage(e.getMessage());

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


	/**
	 * 项目订单分析统计
	 *
	 * @return
	 */
	@PostMapping("/getdatabyyear")
	@ResponseBody
	public R<List<Map<String, Object>>> getDataByYear() {

		R<List<Map<String, Object>>> result = new R<>();

		try {
			List<Map<String, Object>> returnList = new ArrayList<>();

			String  virtId = getString("virtId");
			Integer year   = getInteger("year");

			for (int i = 1; i < 13; i++) {

				Map<String, Object> returnMap = new HashMap<>();
				Map<String, Object> params    = new HashMap<>();

				if (!StringUtils.isEmpty(virtId)) {
					params.put("virtId", virtId);
				}

				params.put("sYear", year);
				params.put("sMonth", i);

				List<UnifiedStatisticsVirtVo> data = unifiedStatisticsVirtDubboConsumerService.findAllVo(params);

				double payablemoney = 0;
				if (data != null && data.size() > 0) {

					for (UnifiedStatisticsVirtVo item : data) {
						if (item.getPayableAmount() == null) {
							item.setPayableAmount(new BigDecimal("0"));
						}
						payablemoney += item.getPayableAmount().doubleValue();
					}
				}

				returnMap.put("month", i);
				returnMap.put("payablemoney", new BigDecimal(payablemoney).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

				returnList.add(returnMap);
			}

			result.setSuccess(true);
			result.setData(returnList);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage(e.getMessage());

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

		return result;
	}

	/**
	 * 近一月订单数据
	 *
	 * @return
	 */
	@PostMapping("/getlastmonth")
	@ResponseBody
	public R<UnifiedOrderLastMonth> getLastMonth() {

		R<UnifiedOrderLastMonth> result = new R<>();

		try {

			UnifiedOrderLastMonth data = unifiedStatisticsVirtDubboConsumerService.getLastMonth();

			Map<String, Object> params = new HashMap<>();

			params.put("lastmonth", 1);
			params.put("isdaide", 1);

			BigDecimal returnAmount = unifiedStatisticsVirtDubboConsumerService.getReturnAmount(params);

			if (returnAmount == null) {
				returnAmount = new BigDecimal("0");
			}

			if (data == null) {
				data = new UnifiedOrderLastMonth();
			}

			if (data.getOrderAmount() == null) {
				data.setOrderAmount(new BigDecimal(0));
			}

			if (data.getPayableAmount() == null) {
				data.setPayableAmount(new BigDecimal(0));
			}

			if (data.getOrderTotal() == null) {
				data.setOrderTotal(0);
			}

			data.setOrderAmount(data.getPayableAmount().add(returnAmount));

			result.setSuccess(true);
			result.setData(data);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage(e.getMessage());

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

		return result;
	}

	/**
	 * 截止当前统计
	 *
	 * @return
	 */
	@PostMapping("/getnowstatistics")
	@ResponseBody
	public R<Map<String, Object>> getNowStatistics() {

		R<Map<String, Object>> result = new R<>();

		try {
			Map<String, Object> params      = new HashMap<>();
			Map<String, Object> queryparams = new HashMap<>();

			queryparams.put("isdaide", 1);

			// 未对账金额
			BigDecimal undzamount = unifiedStatisticsVirtDubboConsumerService.getundzamount(queryparams);
			if (undzamount == null) {
				undzamount = new BigDecimal("0");
			}

			params.put("undzamount", undzamount);
			// 代开票金额
			BigDecimal uninvamount = unifiedStatisticsVirtDubboConsumerService.getuninvamount(queryparams);
			if (uninvamount == null) {
				uninvamount = new BigDecimal("0");
			}
			params.put("uninvamount", uninvamount);

			// 待汇款金额
			BigDecimal unpaymoney = unifiedStatisticsVirtDubboConsumerService.getunpaymoney(queryparams);
			if (unpaymoney == null) {
				unpaymoney = new BigDecimal("0");
			}

			params.put("unpaymoney", unpaymoney);

			result.setSuccess(true);
			result.setData(params);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage(e.getMessage());

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

		return result;
	}
}
