package com.cyksj.web.controller.manage.mirrorshop.manage;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.GoodsDonMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.views.*;
import com.cyksj.service.mirrorshop.CmsUserMirrorShopService;
import com.cyksj.web.util.StpUserMirrorShopManageUser;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * admin/镜像店铺后台/数据
 * 项目名: yhlxj2
 * 文件名: CmsUserMirrorShopDataController
 * 创建者: JavaZou
 * 创建时间:2024/11/7 12:03
 */
@RestController
@RequestMapping("/mirrorShop/manage/data")
@RequiredArgsConstructor
public class CmsUserMirrorShopDataController {
	private final UserMirrorShopMapper userMirrorShopMapper;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final CmsUserMirrorShopService cmsUserMirrorShopService;

	private final GoodsDonMapper goodsDonMapper;



	/**
	 * 店铺分销平台数据详情
	 */
	@GetMapping("/get/distribute/detail/data")
	public Result<YhShopUserDistributeDetailView> getDistributeDetail() {
		long yhShopUserId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		User user = beanSearcher.searchFirst(User.class, MapUtils.builder().field(User::getId, yhShopUserId).onlySelect(User::getMpMoney).build());
		BigDecimal wApplyMoney = user.getMpMoney().divide(BigDecimal.valueOf(100), 2, RoundingMode.DOWN);
		//已提现
		Number gotApplyMoney = beanSearcher.searchSum(UserMirrorShopDistributeMoneyApply.class, MapUtils.builder()
				.field(UserMirrorShopDistributeMoneyApply::getUserId, yhShopUserId)
				.field(UserMirrorShopDistributeMoneyApply::getVerifyStatus, YhShopDistributeMoneyApply.Status.success.name())
				.build(), "money");
		Number reMoneyPoints = beanSearcher.searchSum(UserMirrorShopDistributeWaitingSendPoints.class, MapUtils.builder().field(UserMirrorShopDistributeWaitingSendPoints::getShopUserId, yhShopUserId).field(UserMirrorShopDistributeWaitingSendPoints::getSendStatus, UserMirrorShopDistributeWaitingSendPoints.Status.success.name()).build(), "money");
		Number wMoneyPoints = beanSearcher.searchSum(UserMirrorShopDistributeWaitingSendPoints.class, MapUtils.builder().field(UserMirrorShopDistributeWaitingSendPoints::getShopUserId, yhShopUserId).field(UserMirrorShopDistributeWaitingSendPoints::getSendStatus, UserMirrorShopDistributeWaitingSendPoints.Status.waiting.name()).build(), "money");

		YhShopUserDistributeDetailView detailView = new YhShopUserDistributeDetailView();
		detailView.setWMoney(BigDecimal.valueOf(wMoneyPoints.doubleValue()).divide(BigDecimal.valueOf(100), 2, RoundingMode.DOWN));
		detailView.setReMoney(BigDecimal.valueOf(reMoneyPoints.doubleValue()).divide(BigDecimal.valueOf(100),2,RoundingMode.DOWN));

		detailView.setWApplyMoney(wApplyMoney);
		detailView.setGotApplyMoney(BigDecimal.valueOf(gotApplyMoney.doubleValue()).divide(BigDecimal.valueOf(100), 2, RoundingMode.DOWN));
		return GatewayResponse.SUCCESS.newBuilder().toResult(detailView);
	}



	/**
	 * 店铺待入账数据统计
	 */
	@GetMapping("/get/wMoney/statisticsData")
	public Result<YhShopBrokenLineCpsUserWMoneyView> getWMoneyStatisticsDataView(Long firstDate, Long lastDate) {
		long yhShopUserId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		DateTime first = null;
		DateTime end = null;
		if (firstDate != null) {
			first = DateUtil.date(firstDate);
		}
		if (lastDate != null) {
			end = DateUtil.date(lastDate);
		}
		YhShopBrokenLineCpsUserWMoneyView brokenLineCpsUserWMoneyView = Optional.ofNullable(cmsUserMirrorShopService.getWMoneyStatisticsDate(yhShopUserId, first, end)).orElse(new YhShopBrokenLineCpsUserWMoneyView());
		List<YhShopUserWMoneyStatisticsDataView> dataView = cmsUserMirrorShopService.getWMoneyStatisticsDataView(yhShopUserId, first, end);
		brokenLineCpsUserWMoneyView.setDataView(dataView);
		return GatewayResponse.SUCCESS.newBuilder().toResult(brokenLineCpsUserWMoneyView);
	}

	/**
	 * 数据中心折线图
	 */
	@GetMapping("/get/data/brokenLine")
	public Result<UserMirrorShopOrderDataStatisticsView> getDataBrokenLine(Long firstDate, Long lastDate) {
		long yhShopUserId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		UserMirrorShop userMirrorShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
				.eq(UserMirrorShop::getUserId, yhShopUserId)
				.last("limit 1"));
		String first = null;
		String end = null;
		if (firstDate != null) {
			first = DateUtil.format(DateTime.of(firstDate), "yyyy-MM-dd");
		}
		if (lastDate != null) {
			end = DateUtil.format(DateTime.of(lastDate), "yyyy-MM-dd");
		}
		UserMirrorShopOrderDataStatisticsView brokenLineObjView = Optional.ofNullable(userMirrorShopMapper.selectOrderBrokenLineMoney(userMirrorShop.getId(), first, end))
				.orElse(new UserMirrorShopOrderDataStatisticsView());

		if (brokenLineObjView != null) {
			String timeSql = StrUtil.EMPTY;
			if (firstDate != null) {
				first = DateUtil.format(DateTime.of(firstDate), "yyyy-MM-dd HH:mm:ss");
				timeSql += String.format(" and o.created_time >= '%s'", first);
			}
			if (lastDate != null) {
				end = DateUtil.format(DateTime.of(lastDate), "yyyy-MM-dd HH:mm:ss");
				timeSql += String.format(" and o.created_time < '%s'", end);
			}
			MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
			if (StrUtil.isNotEmpty(timeSql)) {
				builder.put("time", timeSql);
			}
			builder.put("mid", String.format(" and mp_id = %s", userMirrorShop.getId()));
			List<UserMirrorShopOrderView> views = beanSearcher.searchAll(UserMirrorShopOrderView.class,builder.build());
			Map<Long, List<UserMirrorShopOrderView>> goodsMap = views.stream().collect(Collectors.groupingBy(UserMirrorShopOrderView::getGoodsId));
			brokenLineObjView.setGoodsData(goodsMap);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(brokenLineObjView);
	}

	/**
	 * 店铺分销订单收入统计
	 */
	@GetMapping("/get/distribute/orders/statisticsData")
	public Result<SearchResult<UserMirrorShopDsOrderStatisticsView>> getUserDistributeOrdersStatisticsView(Long firstDate, Long lastDate) {
		long yhShopUserId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		UserMirrorShop yhShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
				.eq(UserMirrorShop::getUserId, yhShopUserId).last("limit 1"));
		String first = null;
		String end = null;
		String timeSql = StrUtil.EMPTY;
		if (firstDate != null) {
			first = DateUtil.format(DateTime.of(firstDate), "yyyy-MM-dd HH:mm:ss");
			timeSql += String.format(" and o.created_time >= '%s'", first);
		}
		if (lastDate != null) {
			end = DateUtil.format(DateTime.of(lastDate), "yyyy-MM-dd HH:mm:ss");
			timeSql += String.format(" and o.created_time < '%s'", end);
		}
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		builder.put("yhs_id", String.format("uor.mp_id = %s", yhShop.getId()));
		if (StrUtil.isNotEmpty(timeSql)) {
			builder.put("time", timeSql);
		}
		SearchResult<UserMirrorShopDsOrderStatisticsView> search = beanSearcher.search(UserMirrorShopDsOrderStatisticsView.class, builder.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 店铺分销订单收入详细
	 */
	@GetMapping("/get/distribute/orders/detail/data")
	public Result<SearchResult> getUserDistributeOrdersDetailView(@RequestParam(defaultValue = "1") Integer type, Long firstDate, Long lastDate) {
		long yhShopUserId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		UserMirrorShop yhShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
				.eq(UserMirrorShop::getUserId, yhShopUserId).last("limit 1"));
		String first = null;
		String end = null;
		String timeSql = StrUtil.EMPTY;
		if (firstDate != null) {
			first = DateUtil.format(DateTime.of(firstDate), "yyyy-MM-dd HH:mm:ss");
			timeSql += String.format(" and o.created_time >= '%s'", first);
		}
		if (lastDate != null) {
			end = DateUtil.format(DateTime.of(lastDate), "yyyy-MM-dd HH:mm:ss");
			timeSql += String.format(" and o.created_time < '%s'", end);
		}
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		builder.put("yhs_id", String.format("mp_id = %s", yhShop.getId()));
		if (StrUtil.isNotEmpty(timeSql)) {
			builder.put("time", timeSql);
		}
		SearchResult search;
		if (type == 1) {
			search = beanSearcher.search(UserMirrorShopDsOrderDetailView.class, builder.build());
		} else {
			//加盟订单提成
			search = beanSearcher.search(UserMirrorShopDsJoinOrderDetailView.class, builder.build());
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 店铺分销商品列表
	 */
	@GetMapping("/get/orders/goods")
	public Result<List<GoodsDon>> getGoodsList() {
		long yhShopUserId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		UserMirrorShop yhShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
				.eq(UserMirrorShop::getUserId, yhShopUserId).last("limit 1"));
		if (yhShop == null) {
			return GatewayResponse.SUCCESS.newBuilder().toResult();
		}
		List<GoodsDon> goodsDons = goodsDonMapper.getUserMirrorShopShopDistributeGoodsDetail(yhShop.getId());
		return GatewayResponse.SUCCESS.newBuilder().toResult(goodsDons);
	}

	/**
	 * 提现记录
	 */
	@GetMapping("/get/apply/money")
	public Result<SearchResult<UserMirrorShopDistributeMoneyApply>> getApplyMoney() {
		long yhShopUserId = StpUserMirrorShopManageUser.getLoginIdAsLong();
		SearchResult<UserMirrorShopDistributeMoneyApply> search = beanSearcher.search(UserMirrorShopDistributeMoneyApply.class, MapUtils.flatBuilder(request.getParameterMap()).field(UserMirrorShopDistributeMoneyApply::getUserId, yhShopUserId).orderBy(UserMirrorShopDistributeMoneyApply::getId).desc().build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}
}
