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

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.shop.YhShopMapper;
import com.cyksj.model.dto.YhShopSkuDownInfo;
import com.cyksj.model.entity.YhShop;
import com.cyksj.model.entity.YhShopGoodsSku;
import com.cyksj.model.views.YhShopAvailableGoodsView;
import com.cyksj.model.views.YhShopGoodsRateView;
import com.cyksj.model.views.YhShopGoodsView;
import com.cyksj.redis.RedisService;
import com.cyksj.service.mange.RefreshCacheService;
import com.cyksj.service.shop.YhShopGoodsSkuService;
import com.cyksj.web.util.StpYhShopManageUser;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/*
 *项目名: yhlxj
 *文件名: ShopController
 *创建者: JavaZou
 *创建时间:2023/9/20 14:12
 */
@Slf4j
@RestController
@RequestMapping("/yhShop/manage/goods")
@RequiredArgsConstructor
public class YhShopGoodsController {
	private final BeanSearcher beanSearcher;

	private final YhShopGoodsSkuService yhShopGoodsSkuService;

	private final RedisService redisService;

	private final YhShopMapper yhShopMapper;

	private final HttpServletRequest request;

	private final RefreshCacheService refreshCacheService;

	/**
	 * 新增平台
	 */
	@PostMapping("/post")
	public Result<Void> saveGoods(@RequestBody List<Long> goodsIds){
		long userId = StpYhShopManageUser.getLoginIdAsLong();
		yhShopGoodsSkuService.saveGoods(goodsIds, userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 设置店铺平台价格
	 */
	@PutMapping("/put")
	public Result<Void> updShopGoodsRate(@RequestBody List<YhShopGoodsSku> goodsSkus){
		long userId = StpYhShopManageUser.getLoginIdAsLong();
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getUserId, userId).last("limit 1"));
		goodsSkus.forEach(sku -> {
			YhShopGoodsRateView.YhShopGoodsSkuRateView yhShopGoodsSkuRateView = beanSearcher.searchFirst(YhShopGoodsRateView.YhShopGoodsSkuRateView.class, MapUtils.builder().field(YhShopGoodsRateView.YhShopGoodsSkuRateView::getSkuId,sku.getSkuId()).build());
			if (sku.getPrice().compareTo(yhShopGoodsSkuRateView.getMaxPrice()) > 0 || sku.getPrice().compareTo(yhShopGoodsSkuRateView.getMinPrice()) < 0){
				throw BusinessRuntimeException.getInstance("价格不能超出区间范围");
			}
			sku.setUserId(userId);
			sku.setYhsId(yhShop.getId());
		});
		yhShopGoodsSkuService.saveOrUpdateBatch(goodsSkus);
		refreshCacheService.refreshShopUserIdCacheByYshId(yhShop.getId());
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 上下架
	 */
	@PutMapping("/put/goodsStatus/{goodsId}")
	public Result<Void> updGoodsStatus(@PathVariable Long goodsId, Boolean status) {
		long userId = StpYhShopManageUser.getLoginIdAsLong();
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getUserId, userId).last("limit 1"));
		List<YhShopGoodsView.YhShopGoodsSkuView> list = beanSearcher.searchAll(YhShopGoodsView.YhShopGoodsSkuView.class, MapUtils.builder().put("uid", String.format("and ysgs.user_id = %s", userId))
				.field(YhShopGoodsView.YhShopGoodsSkuView::getGoodsId, goodsId).build());
		list.forEach(sku -> {
			YhShopGoodsRateView.YhShopGoodsSkuRateView yhShopGoodsSkuRateView = beanSearcher.searchFirst(YhShopGoodsRateView.YhShopGoodsSkuRateView.class, MapUtils.builder().field(YhShopGoodsRateView.YhShopGoodsSkuRateView::getSkuId, sku.getSkuId()).build());
			if (sku.getShopSkuPrice().compareTo(yhShopGoodsSkuRateView.getMaxPrice()) > 0 || sku.getShopSkuPrice().compareTo(yhShopGoodsSkuRateView.getMinPrice()) < 0) {
				throw BusinessRuntimeException.getInstance("价格不能超出区间范围");
			}
		});
		yhShopGoodsSkuService.update(Wrappers.lambdaUpdate(YhShopGoodsSku.class).eq(YhShopGoodsSku::getGoodsId, goodsId).eq(YhShopGoodsSku::getDeleted, true).eq(YhShopGoodsSku::getUserId, userId).set(YhShopGoodsSku::getStatus, status));
		refreshCacheService.refreshShopUserIdCacheByYshId(yhShop.getId());
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}


	/**
	 * 删除平台
	 */
	@PutMapping("/del/{goodsId}")
	public Result<Void> updGoodsStatus(@PathVariable Long goodsId){
		long userId = StpYhShopManageUser.getLoginIdAsLong();
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getUserId, userId).last("limit 1"));
		yhShopGoodsSkuService.update(Wrappers.lambdaUpdate(YhShopGoodsSku.class).eq(YhShopGoodsSku::getGoodsId, goodsId).eq(YhShopGoodsSku::getUserId, userId).set(YhShopGoodsSku::getDeleted, false));
		refreshCacheService.refreshShopUserIdCacheByYshId(yhShop.getId());
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 查询可选择的平台
	 */
	@GetMapping("/get/available/goods")
	public Result<SearchResult<YhShopAvailableGoodsView>> getAvailableGoods(){
		long userId = StpYhShopManageUser.getLoginIdAsLong();
		SearchResult<YhShopAvailableGoodsView> search = beanSearcher.search(YhShopAvailableGoodsView.class, MapUtils.flatBuilder(request.getParameterMap())
				.put("condition", String.format("and (select count(*) from yh_shop_goods_sku where user_id = %s and goods_id = yr.goods_id and deleted is true) = 0", userId))
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}


	/**
	 * 查询平台
	 */
	@GetMapping("/get")
	public Result<SearchResult<YhShopGoodsView>> goodsList(){
		long userId = StpYhShopManageUser.getLoginIdAsLong();
		SearchResult<YhShopGoodsView> search = beanSearcher.search(YhShopGoodsView.class, MapUtils.flatBuilder(request.getParameterMap()).field(YhShopGoodsView::getUserId, userId).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 平台详情
	 */
	@GetMapping("/get/goods/detail/{goodsId}")
	public Result<List<YhShopGoodsView.YhShopGoodsSkuView>> getGoodsDetail(@PathVariable Long goodsId) {
		long userId = StpYhShopManageUser.getLoginIdAsLong();
		List<YhShopGoodsView.YhShopGoodsSkuView> views = beanSearcher.searchAll(YhShopGoodsView.YhShopGoodsSkuView.class, MapUtils.builder().put("uid", String.format("and ysgs.user_id = %s", userId))
				.field(YhShopGoodsView.YhShopGoodsSkuView::getGoodsId, goodsId).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(views);
	}

	/**
	 * 小店规格被下架提示
	 * @return
	 */
	@GetMapping("/get/sku/down/info")
	public Result<List<YhShopSkuDownInfo>> yhShopSkuSysStatusDownInfo() {
		long userId = StpYhShopManageUser.getLoginIdAsLong();
		List<YhShopSkuDownInfo> infos = yhShopGoodsSkuService.yhShopSkuSysStatusDownInfo(userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(infos);
	}

	/**
	 * 删除提示
	 */
	@DeleteMapping("/delete/sku/down/info")
	public Result<String> deleteSkuDownInfo() {
		long userId = StpYhShopManageUser.getLoginIdAsLong();
		yhShopGoodsSkuService.deleteSkuDownInfo(userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}
}
