/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.platform.controller;
import com.yami.shop.common.util.R;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yami.shop.bean.dto.ListCategoryDTO;
import com.yami.shop.bean.model.Category;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.vo.ListCategoryVO;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.service.CategoryService;
import com.yami.shop.common.config.Constant;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.ShopDetailService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 商品分类管理实现
 *
 * @author lgh
 * @version 1.0.0
 * @since 2018-11-26
 */
@RestController
@RequestMapping("/prod/category")
public class CategoryController {

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private ProductService productService;

	@Resource
	private ShopDetailService shopDetailService;

	/**
	 * 获取分类信息
	 */
	@GetMapping("/info/{categoryId}")
	public R<Category> info(@PathVariable("categoryId") Long categoryId){
		Category category = categoryService.getById(categoryId);
		return R.SUCCESS(category);
	}

	/**
	 * 保存分类
	 */
	@SysLog("保存分类")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('prod:category:save')")
	public R<Void> save(@RequestBody Category category){
		category.setShopId(Constant.PLATFORM_SHOP_ID);
		category.setRecTime(new Date());
		category.setGrade(getGradeByParentId(category.getParentId()));
		categoryService.saveCategroy(category);
		return R.SUCCESS();
	}

	/**
	 * 更新分类
	 */
	@SysLog("更新分类")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('prod:category:update')")
	public R<String> update(@RequestBody Category category){
		Category categoryById = categoryService.getById(category.getCategoryId());
		if (Objects.equals(categoryById.getParentId(), Constant.CATEGORY_ID) && !Objects.equals(category.getParentId(), Constant.CATEGORY_ID)){
			return R.FAIL("一级分类不能改为二级分类");
		}else if(Objects.equals(category.getParentId(), Constant.CATEGORY_ID) && !Objects.equals(categoryById.getParentId(), Constant.CATEGORY_ID)){
			return R.FAIL("二级分类不能改为一级分类");
		}
		category.setGrade(getGradeByParentId(category.getParentId()));
		category.setOldCategoryName(categoryById.getCategoryName());
		categoryService.updateCategroy(category);
		return R.SUCCESS();
	}

	/**
	 * 删除分类
	 */
	@SysLog("删除分类")
	@DeleteMapping("/{categoryId}")
	@PreAuthorize("@pms.hasPermission('prod:category:delete')")
	public R<String> delete(@PathVariable("categoryId") Long categoryId){
		if (categoryService.count(new LambdaQueryWrapper<Category>().eq(Category::getParentId,categoryId)) >0) {
			return R.FAIL("请删除子分类，再删除该分类");
		}
		int categoryProdCount = productService.count(new LambdaQueryWrapper<Product>().eq(Product::getCategoryId, categoryId).ne(Product::getStatus, -1));
		if (categoryProdCount>0){
			return R.FAIL("该分类下还有商品，请先删除该分类下的商品");
		}
		Category category = categoryService.getById(categoryId);
		categoryService.deleteCategroy(category);
		return R.SUCCESS();
	}

	/**
	 * 所有的
	 */
	@GetMapping("/listCategory")
	public R<IPage<Category>> listCategory(@RequestParam Integer maxGrade,
													   @RequestParam(value = "shopId", required = false) String shopId,
													   @RequestParam(value = "categoryName", required = false) String categoryName,
													   @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
													   @RequestParam(value = "size", required = false, defaultValue = "10") Integer size){
		IPage<Category> page = categoryService.page(new Page<>(current, size), new LambdaQueryWrapper<Category>()
				.le(Category::getGrade, maxGrade)
				.eq(Objects.nonNull(shopId), Category::getShopId, shopId)
				.like(StringUtils.isNotEmpty(categoryName), Category::getCategoryName, categoryName)
				.orderByDesc(Category::getSeq)
				.orderByDesc(Category::getCategoryId));
		List<Category> records = page.getRecords();
		if (CollectionUtil.isNotEmpty(records)) {
			for (Category record : records) {
				ShopDetail shopDetail = shopDetailService.getById(record.getShopId());
				record.setShopName(shopDetail.getShopName());
			}
		}
		return R.SUCCESS(page);
	}

	@PostMapping("/listCategoryNew")
	@ApiOperation("分类查询")
	public R<IPage<ListCategoryVO>> listCategoryNew(@RequestBody ListCategoryDTO listCategoryDTO){
		return R.SUCCESS(categoryService.listCategory(listCategoryDTO));
	}

//	/**
//	 * 所有的
//	 */
//	@GetMapping("/listCategory")
//	public ResponseEntity<List<Category>> listCategory(Long shopId){
//		shopId = shopId == null ? SecurityUtils.getSysUser().getShopId():shopId;
//		return ResponseEntity.ok(categoryService.list(new LambdaQueryWrapper<Category>()
//				.le(Category::getGrade, 2)
//				.eq(Category::getShopId, shopId)
//				.orderByAsc(Category::getSeq)));
//	}


	private int getGradeByParentId(Long parentId) {
		// 如果上级为id为0，则设置分类等级为0
		if (Objects.equals(parentId,0L)) {
			return 0;
		}
		Category parentCategory = categoryService.getById(parentId);
		return parentCategory.getGrade() + 1;
	}

	/**
	 * 平台的分类
	 */
	@GetMapping("/platformCategory")
	public R<List<Category>> platformCategory(@RequestParam Integer maxGrade){

		return R.SUCCESS(categoryService.list(new LambdaQueryWrapper<Category>()
				.le(Category::getGrade, maxGrade)
				.eq(Category::getShopId, Constant.PLATFORM_SHOP_ID)
				.orderByAsc(Category::getSeq)));
	}

	@ApiOperation("按名称模糊匹配店铺")
	@GetMapping("/getShopByName")
	public R<List<ShopDetail>> getShopByName(@RequestParam(value = "shopName", required = false) String shopName) {
		List<ShopDetail> list = shopDetailService.list(new LambdaQueryWrapper<ShopDetail>()
				.like(StringUtils.isNotEmpty(shopName), ShopDetail::getShopName, shopName));
		return R.SUCCESS(list);
	}

}
