package com.cyksj.web.controller.manage.goods.shop;

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.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.GoodsDonMapper;
import com.cyksj.mapper.manage.distribute.DistributePointsExchangeMoneyMapper;
import com.cyksj.mapper.shop.YhShopApplyRecordMapper;
import com.cyksj.mapper.shop.YhShopMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.YhShopApplyMoneyReq;
import com.cyksj.model.views.*;
import com.cyksj.service.cps.shop.YhShopManageService;
import com.cyksj.service.mange.RefreshCacheService;
import com.cyksj.web.util.StpYhShopManageUser;
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.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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/小店店铺/用户店铺后台
 *项目名: yhlxj
 *文件名: YhShopUserController
 *创建者: JavaZou
 *创建时间:2023/9/20 14:19
 */
@RestController
@RequestMapping("/yhShop/manage")
@RequiredArgsConstructor
public class YhShopUserController {
	private final YhShopManageService yhShopManageService;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final GoodsDonMapper goodsDonMapper;

	private final YhShopMapper yhShopMapper;

	private final YhShopApplyRecordMapper yhShopApplyRecordMapper;

	private final RefreshCacheService refreshCacheService;

	private final DistributePointsExchangeMoneyMapper distributePointsExchangeMoneyMapper;

	/**
	 * 店铺 信息详情
	 */
	@GetMapping("/get/shop/detail/data")
	public Result<YhShopDetailView> getShopDetail() {
		long yhShopUserId = StpYhShopManageUser.getLoginIdAsLong();
		YhShopDetailView detailView = beanSearcher.searchFirst(YhShopDetailView.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(YhShopDetailView::getUserId, yhShopUserId)
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(detailView);
	}

	/**
	 * 设置联系方式
	 */
	@PutMapping("/set/shop/contact")
	public Result<String> setShopContact(@RequestBody YhShop yhShop) {
		long userId = StpYhShopManageUser.getLoginIdAsLong();
		String contact = yhShop.getContact();
		YhShop dbShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getUserId, userId).last("limit 1"));
		if (dbShop == null) {
			throw BusinessRuntimeException.getInstance("店铺不存在");
		}
		dbShop.setContact(contact);
		yhShopMapper.updateById(dbShop);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 设置是否展示广告位
	 */
	@PutMapping("/set/shop/ad")
	public Result<String> setShopAd() {
		long userId = StpYhShopManageUser.getLoginIdAsLong();
		YhShop dbShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getUserId, userId).last("limit 1"));
		if (dbShop == null) {
			throw BusinessRuntimeException.getInstance("店铺不存在");
		}
		dbShop.setIsShowAd(!dbShop.getIsShowAd());
		yhShopMapper.updateById(dbShop);
		refreshCacheService.refreshUserShopMangeCache(dbShop.getCustomId());
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 申请修改
	 */
	@PutMapping("/update/shop")
	@Transactional(rollbackFor = Throwable.class)
	public Result<String> updateShop(@RequestBody YhShopApplyRecord record) {
		long userId = StpYhShopManageUser.getLoginIdAsLong();
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getUserId, userId).last("limit 1"));
		String name = record.getName();
		if (yhShop == null) {
			throw BusinessRuntimeException.getInstance("店铺不存在");
		}
		if (StrUtil.isEmpty(name)) {
			throw BusinessRuntimeException.getInstance("请输入申请修改的店铺名");
		}
		//是否存在正在修改的提交记录
		YhShopApplyRecord yhShopApplyRecord = yhShopApplyRecordMapper.selectOne(Wrappers.lambdaQuery(YhShopApplyRecord.class)
				.eq(YhShopApplyRecord::getUserId, userId)
				.eq(YhShopApplyRecord::getVerifyStatus, YhShopApplyRecord.Status.verify).last("limit 1"));

		if (yhShopApplyRecord != null) {
			throw BusinessRuntimeException.getInstance("您提交的修改申请正在审核中..");
		}
		//三个月可修改一次
		Integer count = yhShopApplyRecordMapper.selectCount(Wrappers.lambdaQuery(YhShopApplyRecord.class)
				.eq(YhShopApplyRecord::getUserId, userId)
				.isNull(YhShopApplyRecord::getCustomId)
				.ge(YhShopApplyRecord::getCreatedTime, DateUtil.offsetMonth(DateTime.now(), -3)));
		if (count > 0) {
			throw BusinessRuntimeException.getInstance("近三个月只可修改一次");
		}
		yhShopApplyRecord = new YhShopApplyRecord();
		yhShopApplyRecord.setVerifyStatus(YhShopApplyRecord.Status.verify);
		yhShopApplyRecord.setName(name);
		yhShopApplyRecord.setUserId(userId);
		yhShopApplyRecord.setBusinessId(yhShop.getBusinessId());
		yhShopApplyRecordMapper.insert(yhShopApplyRecord);

		if (StrUtil.isNotBlank(yhShop.getReason())) {
			yhShop.setReason(null);
			yhShopMapper.updateById(yhShop);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

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

		List<YhShopUserDistributeRateView> rateViews = beanSearcher.searchAll(YhShopUserDistributeRateView.class, MapUtils.builder()
				.put("uid", String.format("and user_id = %s", yhShopUserId))
				.orderBy(YhShopUserDistributeRateView::getRate).desc()
				.build());
		YhShopUserDistributeDetailView detailView = new YhShopUserDistributeDetailView();
		Map<String, List<YhShopUserDistributeRateView>> collect = rateViews.stream().filter(ct -> StrUtil.isNotBlank(ct.getCategoryName()) && ct.getRate() > 0).collect(Collectors.groupingBy(YhShopUserDistributeRateView::getCategoryName));
		detailView.setRateViews(collect);
		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 = StpYhShopManageUser.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(yhShopManageService.getWMoneyStatisticsDate(yhShopUserId, first, end)).orElse(new YhShopBrokenLineCpsUserWMoneyView());
		List<YhShopUserWMoneyStatisticsDataView> dataView = yhShopManageService.getWMoneyStatisticsDataView(yhShopUserId, first, end);
		brokenLineCpsUserWMoneyView.setDataView(dataView);
		return GatewayResponse.SUCCESS.newBuilder().toResult(brokenLineCpsUserWMoneyView);
	}

	/**
	 * 店铺分销订单收入统计
	 */
	@GetMapping("/get/distribute/orders/statisticsData")
	public Result<SearchResult<YhShopUserDistributeOrdersStatisticsView>> getUserDistributeOrdersStatisticsView(Long firstDate, Long lastDate) {
		long yhShopUserId = StpYhShopManageUser.getLoginIdAsLong();
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::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("yhs_id = %s", yhShop.getId()));
		if (StrUtil.isNotEmpty(timeSql)) {
			builder.put("time", timeSql);
		}
		SearchResult<YhShopUserDistributeOrdersStatisticsView> search = beanSearcher.search(YhShopUserDistributeOrdersStatisticsView.class, builder.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 店铺分销订单收入详细
	 */
	@GetMapping("/get/distribute/orders/detail/data")
	public Result<SearchResult<YhShopUserDistributeOrdersDetailView>> getUserDistributeOrdersDetailView(Long firstDate, Long lastDate) {
		long yhShopUserId = StpYhShopManageUser.getLoginIdAsLong();
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::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("yhs_id = %s", yhShop.getId()));
		if (StrUtil.isNotEmpty(timeSql)) {
			builder.put("time", timeSql);
		}
		SearchResult<YhShopUserDistributeOrdersDetailView> search = beanSearcher.search(YhShopUserDistributeOrdersDetailView.class, builder.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

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

	/**
	 * 申请 提现
	 */
	@PostMapping("/apply/money")
	public Result<String> yhShopApplyMoney(@RequestBody YhShopApplyMoneyReq applyMoneyReq) throws Exception {
		long userId = StpYhShopManageUser.getLoginIdAsLong();
		applyMoneyReq.setUserId(userId);
		return yhShopManageService.applyMoney(applyMoneyReq);
	}

	/**
	 * 后台添加用户店铺
	 */
	@PostMapping("/add/user/shop")
	public Result<String> addUserShop(@RequestBody YhShop yhShop) {
		yhShopManageService.addUserShop(yhShop);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 提现门槛
	 */
	@GetMapping("/applyMoney/threshold")
	public Result<DistributePointsExchangeMoney> getThreshold() {
		return GatewayResponse.SUCCESS.newBuilder().toResult(distributePointsExchangeMoneyMapper.selectOne(Wrappers.lambdaQuery(DistributePointsExchangeMoney.class).last("limit 1")));
	}
}
