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

package com.yami.shop.multishop.controller;

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.vo.ListCategoryVO;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.CategoryService;
import com.yami.shop.service.ProductService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 分类管理
 * @author lgh
 *
 */
@RestController
@RequestMapping("/prod/category")
public class CategoryController {

	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ProductService productService;


	/**
	 * 获取分类信息
	 */
	@GetMapping("/info/{categoryId}")
	public ResponseEntity<Category> info(@PathVariable("categoryId") Long categoryId){
		// 获取数据库中的分类，如果分类为空则抛异常
		Category category = categoryService.getCategoryByCategoryIdAndShopId(categoryId, SecurityUtils.getShopUser().getShopId());

		return ResponseEntity.ok(category);
	}

	/**
	 * 保存分类
	 */
	@SysLog("保存分类")
	@PostMapping
	public ResponseEntity<Void> save(@RequestBody Category category){
		category.setShopId(SecurityUtils.getShopUser().getShopId());
		category.setRecTime(new Date());
		Category categoryName = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName,category.getCategoryName())
				.eq(Category::getShopId,category.getShopId()));
		if(categoryName != null){
			throw new GlobalException("类目名称已存在！");
		}
		categoryService.saveCategroy(category);
		return ResponseEntity.ok().build();
	}

	/**
	 * 更新分类
	 */
	@SysLog("更新分类")
	@PutMapping
	public ResponseEntity<String> update(@RequestBody Category category){
		// 获取数据库中的分类，如果分类为空则抛异常
		categoryService.getCategoryByCategoryIdAndShopId(category.getCategoryId(),SecurityUtils.getShopUser().getShopId());
		category.setShopId(SecurityUtils.getShopUser().getShopId());
		Category categoryDB = categoryService.getById(category.getCategoryId());
		if (Objects.equals(categoryDB.getParentId(), Constant.CATEGORY_ID) && !Objects.equals(category.getParentId(), Constant.CATEGORY_ID)){
			return ResponseEntity.badRequest().body("一级分类不能改为二级分类");
		}else if(Objects.equals(category.getParentId(), Constant.CATEGORY_ID) && !Objects.equals(categoryDB.getParentId(), Constant.CATEGORY_ID)){
			return ResponseEntity.badRequest().body("二级分类不能改为一级分类");
		}
		if (Objects.equals(category.getParentId(),category.getCategoryId())) {
			return ResponseEntity.badRequest().body("分类的上级不能是自己本身");
		}
		Category categoryName = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName,category.getCategoryName())
														.eq(Category::getShopId,category.getShopId()).ne(Category::getCategoryId,category.getCategoryId()));
		if(categoryName != null){
			throw new GlobalException("类目名称已存在！");
		}
		category.setOldCategoryName(categoryDB.getCategoryName());
		categoryService.updateCategroy(category);
		return ResponseEntity.ok().build();
	}

	/**
	 * 删除分类
	 */
	@SysLog("删除分类")
	@DeleteMapping("/{categoryId}")
	public ResponseEntity<String> delete(@PathVariable("categoryId") Long categoryId){
//		if (categoryService.count(new LambdaQueryWrapper<Category>().eq(Category::getParentId,categoryId)) >0) {
//			return ResponseEntity.badRequest().body("请删除子分类，再删除该分类");
//		}
		int categoryProdCount = productService.count(new LambdaQueryWrapper<Product>().eq(Product::getShopCategoryId, categoryId).ne(Product::getStatus, -1));
		if (categoryProdCount>0){
			return ResponseEntity.badRequest().body("该分类下还有商品，请先删除该分类下的商品");
		}

		Category category = categoryService.getCategoryByCategoryIdAndShopId(categoryId,SecurityUtils.getShopUser().getShopId());
		categoryService.deleteCategroy(category);
		return ResponseEntity.ok().build();
	}

	/**
	 * 获取一级分类
	 */
	@GetMapping("/listCategory")
	public ResponseEntity<IPage<Category>> listCategory(@RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
														@RequestParam(value = "size", required = false, defaultValue = "10") Integer size,
														@RequestParam(value = "shopId", required = false) Long shopId){
		IPage<Category> page = categoryService.page(new Page<>(current, size), new LambdaQueryWrapper<Category>()
//														.le(Category::getGrade, 1)
//														.eq(Category::getShopId, SecurityUtils.getShopUser().getShopId())
				.eq(Objects.nonNull(shopId), Category::getShopId, shopId)
				.orderByDesc(Category::getSeq)
				.orderByDesc(Category::getCategoryId));
//		return ResponseEntity.ok(categoryService.list(new LambdaQueryWrapper<Category>()
//														.le(Category::getGrade, 1)
//														.eq(Category::getShopId, SecurityUtils.getShopUser().getShopId())
//														.orderByAsc(Category::getSeq)));
		return ResponseEntity.ok(page);
	}
	@PostMapping("/listCategoryNew")
	@ApiOperation("分类查询")
	public ResponseEntity<IPage<ListCategoryVO>> listCategoryNew(@RequestBody ListCategoryDTO listCategoryDTO){
		return ResponseEntity.ok(categoryService.listCategory(listCategoryDTO));
	}

	@ApiOperation(value = "商户分类导入文件")
	@RequestMapping(value = "/exportExcel", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity exportExcel(@RequestParam("excelFile") MultipartFile excelFile) throws Exception {
		if(excelFile == null) {
			throw new GlobalException("网络繁忙，请稍后重试");
		}
		Long shopId = SecurityUtils.getShopUser().getShopId();
		return ResponseEntity.ok("成功导入： " + categoryService.parseCategoryFile(excelFile,shopId) + "条数据！");
	}
	/**
	 * 平台的分类
	 */
	@GetMapping("/platformCategory")
	public ResponseEntity<List<Category>> listCategory(@RequestParam Integer maxGrade){
		return ResponseEntity.ok(categoryService.list(new LambdaQueryWrapper<Category>()
				.le(Category::getGrade, maxGrade)
				.eq(Category::getStatus, 1)
				.eq(Category::getShopId, Constant.PLATFORM_SHOP_ID)
				.orderByAsc(Category::getSeq)));
	}

}
