package org.springblade.modules.mall.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.common.param.RangeParam;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.mall.entity.*;
import org.springblade.modules.mall.service.*;
import org.springblade.modules.mall.vo.GoodsInfoVO;
import org.springblade.modules.mall.wrapper.GoodsInfoWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 商品表 控制器
 *
 * @author BladeX
 * @since 2022-05-07
 */
@RestController
@AllArgsConstructor
@RequestMapping("mall/goodsinfo")
@Api(value = "商品表", tags = "商品表接口")
public class GoodsInfoController extends BladeController {

	@Resource
	private IGoodsInfoService goodsInfoService;
	@Resource
	private IGoodsImgService iGoodsImgService;
	@Resource
	private IGoodsSpecService goodsSpecService;
	@Resource
	private IGoodsParamsService goodsParamsService;
	@Resource
	private IBrandsInfoService brandsInfoService;
	@Resource
	private IActivitiesGoodsService activitiesGoodsService;


	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入goodsInfo")
	public R<GoodsInfoVO> detail(GoodsInfo goodsInfo) {
		GoodsInfo detail = goodsInfoService.detail(goodsInfo.getId());
		return R.data(GoodsInfoWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 商品表
	 */
	@PostMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入goodsInfo")
	public R<IPage<GoodsInfoVO>> list(@RequestBody GoodsInfo goodsInfo, @RequestBody Query query) {
		QueryWrapper<GoodsInfo> queryWrapper = Condition.getQueryWrapper(goodsInfo);
		if (StrUtil.isNotBlank(goodsInfo.getGoodsName())) {
			queryWrapper.like("goods_name", goodsInfo.getGoodsName());
			goodsInfo.setGoodsName(null);
		}
		if ("-1".equals(goodsInfo.getGoodsCategoryId())) {
			queryWrapper.isNull("goods_category_id");
			goodsInfo.setGoodsCategoryId(null);
		}
		if (StrUtil.isNotBlank(goodsInfo.getGoodsCategoryId())) {
			queryWrapper.likeRight("goods_category_id", goodsInfo.getGoodsCategoryId());
			goodsInfo.setGoodsCategoryId(null);
		}
//		if (StrUtil.isNotBlank(goodsInfo.getCid())) {
//			queryWrapper.likeRight("goods_category_id", goodsInfo.getCid());
//			goodsInfo.setCid(null);
//		}
		if (StrUtil.isNotBlank(goodsInfo.getDiscountRange())) {
			String[] discountRanges = goodsInfo.getDiscountRange().split("-");
			queryWrapper.and(i -> i.ge("discount", discountRanges[0]).le("discount", discountRanges[1]));
			goodsInfo.setDiscountRange(null);
		}
		RangeParam promotionRateRange = goodsInfo.getPromotionRateRange();
		if (promotionRateRange != null) {
			if (StrUtil.isNotBlank(promotionRateRange.getFrom())) {
				queryWrapper.ge("promotion_rate", promotionRateRange.getFrom());
			}
			if (StrUtil.isNotBlank(promotionRateRange.getTo())) {
				queryWrapper.le("promotion_rate", promotionRateRange.getTo());
			}
		}
		if (CollUtil.isNotEmpty(goodsInfo.getBrandIds())) {
			queryWrapper.in("brand_id", goodsInfo.getBrandIds());
		}
		if (StrUtil.isNotBlank(goodsInfo.getActivityDate())) {
			List<ActivitiesGoods> list = activitiesGoodsService.lambdaQuery().eq(ActivitiesGoods::getActivityDate, goodsInfo.getActivityDate()).select(ActivitiesGoods::getGoodsInfoId).list();
			if (CollUtil.isNotEmpty(list)) {
				List<Long> collect = list.stream().map(ActivitiesGoods::getGoodsInfoId).collect(Collectors.toList());
				queryWrapper.in("id", collect);
			} else {
				IPage<GoodsInfoVO> page = new Page<>();
				return R.data(page);
			}
		}
		IPage<GoodsInfo> pages = goodsInfoService.page(Condition.getPage(query), queryWrapper);
		IPage<GoodsInfoVO> goodsInfoVOIPage = GoodsInfoWrapper.build().pageVO(pages);
		if (CollUtil.isNotEmpty(goodsInfoVOIPage.getRecords())) {
			List<Long> collect = goodsInfoVOIPage.getRecords().stream().map(GoodsInfoVO::getBrandId).collect(Collectors.toList());
			HashSet<Long> longs = CollUtil.newHashSet(collect);
//			List<BrandsInfo> list = brandsInfoService.lambdaQuery().in(BrandsInfo::getId, longs).list();
//			Map<Long, BrandsInfo> brandsInfoMap = list.stream().collect(Collectors.toMap(BrandsInfo::getId, Function.identity()));
//			for (GoodsInfoVO record : goodsInfoVOIPage.getRecords()) {
//				record.setBrandDesc(brandsInfoMap.get(record.getBrandId()).getBrandName());
//			}
		}

		return R.data(goodsInfoVOIPage);
	}


	/**
	 * 自定义分页 商品表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入goodsInfo")
	public R<IPage<GoodsInfoVO>> page(GoodsInfoVO goodsInfo, Query query) {
		IPage<GoodsInfoVO> pages = goodsInfoService.selectGoodsInfoPage(Condition.getPage(query), goodsInfo);
		return R.data(pages);
	}

	/**
	 * 新增 商品表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入goodsInfo")
	public R save(@Valid @RequestBody GoodsInfo goodsInfo) {
		return R.status(goodsInfoService.save(goodsInfo));
	}

	/**
	 * 修改 商品表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入goodsInfo")
	public R update(@Valid @RequestBody GoodsInfo goodsInfo) {
		goodsInfoService.update(goodsInfo);
		return R.success("ok");
	}

	/**
	 * 新增或修改 商品表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入goodsInfo")
	public R submit(@Valid @RequestBody GoodsInfo goodsInfo) {
		GoodsInfo detail = goodsInfoService.getOne(Wrappers.lambdaQuery(GoodsInfo.class)
			.eq(GoodsInfo::getGoodsName, goodsInfo.getGoodsName()).eq(GoodsInfo::getBrandId, goodsInfo.getBrandId()));
		if (detail != null) {
			return R.fail("商品已存在");
		}
		goodsInfoService.submit(goodsInfo);
		return R.success("操作成功");
	}


	/**
	 * 删除 商品表
	 */
	@Transactional(rollbackFor = Exception.class)
	@PostMapping("/remove")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> longs = Func.toLongList(ids);
		goodsInfoService.removeByIds(longs);
		goodsSpecService.deleteByGoodsIds(longs);
		goodsParamsService.deleteByGoodsIds(longs);
		iGoodsImgService.deleteByGoodsIds(longs);
		return R.success("操作成功");
	}


	@PostMapping("/modifyState")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "批量修改商品状态", notes = "传入ids")
	public R modifyState(@ApiParam(value = "主键集合", required = true) @RequestParam String ids,
						 @ApiParam(value = "state", required = true) @RequestParam Integer state) {
		goodsInfoService.modifyState(Func.toLongList(ids), state);
		return R.success("操作成功");
	}

	@PostMapping("/modifyCategory")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "批量修改商品分类", notes = "传入ids")
	public R modifyCategory(@ApiParam(value = "主键集合", required = true) @RequestParam String ids,
						 @ApiParam(value = "categoryIds", required = true) @RequestParam String categoryIds) {
		goodsInfoService.modifyCategory(Func.toLongList(ids), categoryIds);
		return R.success("操作成功");
	}

	@PostMapping("/modifyZoneType")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "批量修改专区类型", notes = "传入ids")
	public R modifyZoneType(@ApiParam(value = "主键集合", required = true) @RequestParam String ids,
							 @ApiParam(value = "zoneType", required = true) @RequestParam Integer zoneType,
							@ApiParam(value = "activityDate") @RequestParam String activityDate) {
		goodsInfoService.modifyZoneType(Func.toLongList(ids), zoneType, DateUtil.parse(activityDate, "yyyy-MM-dd"));
		return R.success("操作成功");
	}

	@PostMapping("/setActivityGoods")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "设置活动商品", notes = "传入ids")
	public R setActivityGoods(@ApiParam(value = "主键集合", required = true) @RequestParam String ids,
							@ApiParam(value = "activityDate") @RequestParam String activityDate) {
		goodsInfoService.setActivityGoods(Func.toLongList(ids), DateUtil.parse(activityDate, "yyyy-MM-dd"));
		return R.success("操作成功");
	}
}
