package org.springblade.modules.mall.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
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.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.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.mall.entity.GoodsInfo;
import org.springblade.modules.mall.entity.Store;
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.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
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 IGoodsParamsService goodsParamsService;
	@Resource
	private IBrandsInfoService brandsInfoService;
	@Resource
	private IStoreService storeService;


	/**
	 * 详情
	 */
	@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);
		}
		if (CollUtil.isNotEmpty(goodsInfo.getBrandIds())) {
			queryWrapper.in("brand_id", goodsInfo.getBrandIds());
		}
		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);
	}

	@GetMapping("/storePage")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "供应商商品分页", notes = "传入goodsInfo")
	public R<IPage<GoodsInfoVO>> storePage(GoodsInfoVO goodsInfo, Query query) {
		Store store = getByUserId();
		if(ObjectUtil.isEmpty(store)){
			return R.fail("供应商身份异常，请联系客服");
		}
		goodsInfo.setSupplierId(store.getId());
		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) {
		Assert.notNull(goodsInfo.getSupplierId(), "请选择供应商");
		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("操作成功");
	}

	/**
	 * 新增或修改 商品表  storeSubmit
	 */
	@PostMapping("/storeSubmit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "供应商商品新增或修改", notes = "传入goodsInfo")
	public R storeSubmit(@Valid @RequestBody GoodsInfo goodsInfo) {
		Store store = getByUserId();
		if(ObjectUtil.isEmpty(store)){
			return R.fail("供应商身份异常，请联系客服");
		}
		goodsInfo.setSupplierId(store.getId());
		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);
		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("/audit")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "审核")
	public R audit(@ApiParam(value = "id", required = true) @RequestParam String id,
				   @ApiParam(value = "remark", required = true) @RequestParam Integer auditStatus,
						 @ApiParam(value = "remark", required = true) @RequestParam String remark) {
		goodsInfoService.audit(id, auditStatus, remark);
		return R.success("操作成功");
	}

	@PostMapping("/batchImport")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "批量导入商品")
	public R batchImport(MultipartFile file, Long storeId) throws IOException {
		goodsInfoService.batchImport(file.getInputStream(), storeId);
		return R.success("操作成功");
	}

	@PostMapping("/batchImportStore")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "供应商批量导入商品")
	public R batchImportStore(MultipartFile file) throws IOException {
		Store byUserId = storeService.getByUserId();
		goodsInfoService.batchImport(file.getInputStream(), byUserId.getId());
		return R.success("操作成功");
	}

	@PostMapping("/copy")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "复制商品")
	public R copy(@ApiParam(value = "id", required = true) @RequestParam Long id) {
		goodsInfoService.copy(id);
		return R.success("操作成功");
	}

	public Store getByUserId(){
		return storeService.getOne(Wrappers.lambdaQuery(Store.class)
				.eq(Store::getUserId, AuthUtil.getUserId())
				.eq(Store::getState, 1)
				.eq(Store::getAuditState, 1));
	}
}
