package com.qs.mp.web.controller.api.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.qs.mp.admin.domain.Goods;
import com.qs.mp.admin.domain.GoodsCategory;
import com.qs.mp.admin.domain.vo.GoodsCategoryTreeVO;
import com.qs.mp.admin.service.IGoodsCategoryService;
import com.qs.mp.admin.service.IGoodsService;
import com.qs.mp.common.annotation.Log;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.enums.BusinessType;
import com.qs.mp.common.enums.ErrorCodeEnum;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @auther zhongcp
 * @create 2022-04-07 23:45:48
 * @describe 商品分类管理前端控制器
 */
@Api(tags = "商品分类管理API")
@RestController
@RequestMapping("/api/v1/mp/admin/goods/category/*")
@Component
public class GoodsCategoryMgrController extends BaseApiController {

  @Autowired
  private IGoodsCategoryService goodsCategoryService;

  @Autowired
  private IGoodsService goodsService;

  @PostMapping("/listTree")
  @PreAuthorize("@ss.hasPermi('business:category:list')")
  @ApiOperation("分类列表树状接口")
  @ApiResponses(
          @ApiResponse(code = 200, message = "成功", response = GoodsCategoryTreeVO.class)
  )
  public TableDataInfo listTree(@RequestBody JSONObject param) {
    startPage();

    // 获取父分类
    List<GoodsCategory> categoryList = goodsCategoryService.list(
            new LambdaQueryWrapper<GoodsCategory>()
                    .eq(GoodsCategory::getParentId, 0)
                    .orderByDesc(GoodsCategory::getSort));
    if (CollectionUtils.isEmpty(categoryList)) {
      return getErrorDataTable("分类信息不存在");
    }

    List<GoodsCategoryTreeVO> treeList =  categoryList.stream().map(goodsCategory -> {
      GoodsCategoryTreeVO goodsCategoryTreeVO = new GoodsCategoryTreeVO();
      BeanUtils.copyProperties(goodsCategory, goodsCategoryTreeVO);
      // 获取子分类
      List<GoodsCategory> list = goodsCategoryService.list(
              new LambdaQueryWrapper<GoodsCategory>()
                      .eq(GoodsCategory::getParentId, goodsCategory.getCategoryId())
                      .orderByDesc(GoodsCategory::getSort));
      goodsCategoryTreeVO.setGoodsCategoryList(list);
      return goodsCategoryTreeVO;
    }).collect(Collectors.toList());
    TableDataInfo res = getDataTable(categoryList);
    res.setRows(treeList);

    return res;
  }


  /**
   * 查询商品分类列表, 支持翻页
   *
   * @return
   */
  @PostMapping("/list")
  @PreAuthorize("@ss.hasPermi('business:category:list')")
  @ApiOperation("分类列表接口")
  @ApiResponses(
          @ApiResponse(code = 200,message = "查询成功",response = GoodsCategory.class)
  )
  public TableDataInfo list(@RequestBody JSONObject param) {
    startPage();
    List<GoodsCategory> categoryList = goodsCategoryService.list(
        new LambdaQueryWrapper<GoodsCategory>().orderByDesc(GoodsCategory::getSort));
    return getDataTable(categoryList);
  }

  /**
   * 查询商品分类列表, 支持翻页
   *
   * @return
   */
  @PostMapping("/items")
  public AjaxResult items(@RequestBody JSONObject param) {
    List<GoodsCategory> categoryList = goodsCategoryService.list(
        new LambdaQueryWrapper<GoodsCategory>().orderByDesc(GoodsCategory::getSort));
    return AjaxResult.success(categoryList);
  }

  /**
   * 获取商品分类详情信息
   *
   * @param
   * @return
   */
  @PostMapping(value = "/detail")
  @PreAuthorize("@ss.hasPermi('business:category:query')")
  public AjaxResult info(@RequestBody JSONObject jsonObject) {
    Long categoryId = jsonObject.getLong("categoryId");
    if (null == categoryId || 0 == categoryId) {
      return error(ErrorCodeEnum.ERROR_CODE_1001);
    }
    GoodsCategory category = goodsCategoryService.getById(categoryId);
    return AjaxResult.success(category);
  }


  /**
   * 新增商品分类信息
   *
   * @param
   * @return
   */
  @Log(title = "新增商品分类", businessType = BusinessType.INSERT)
  @ApiOperation(value = "新增商品分类", notes = "后台商品管理新增分类")
  @PostMapping("/create")
  @PreAuthorize("@ss.hasPermi('business:category:add')")
  public AjaxResult create(@Validated @RequestBody GoodsCategory goodsCategory) {
    // 1、校验名称是否重复
    int cnt = goodsCategoryService.count(new LambdaQueryWrapper<GoodsCategory>()
        .eq(GoodsCategory::getName, goodsCategory.getName()));
    if (cnt > 0) {
      return AjaxResult.error("分类名称已存在！");
    }
    // 2.保存
    goodsCategoryService.save(goodsCategory);
    return AjaxResult.success("保存成功");
  }

  /**
   * 编辑商品分类信息
   *
   * @param
   * @return
   */
  @Log(title = "修改商品分类", businessType = BusinessType.UPDATE)
  @ApiOperation(value = "编辑商品分类信息", notes = "后台商品管理修改商品分类信息")
  @PostMapping("/update")
  @PreAuthorize("@ss.hasPermi('business:category:edit')")
  public AjaxResult update(@Validated @RequestBody GoodsCategory goodsCategory) {
    if (null == goodsCategory || null == goodsCategory.getCategoryId()
        || 0 == goodsCategory.getCategoryId()) {
      return error(ErrorCodeEnum.ERROR_CODE_1001);
    }
    int cnt = goodsCategoryService.count(new LambdaQueryWrapper<GoodsCategory>()
        .eq(GoodsCategory::getName, goodsCategory.getName()).notIn(GoodsCategory::getCategoryId,
            Arrays.asList(goodsCategory.getCategoryId())));
    if (cnt > 0) {
      return AjaxResult.error("分类名称已存在！");
    }
    // 保存数据
    boolean rst = goodsCategoryService.updateById(goodsCategory);
    return rst ? AjaxResult.success("更新成功") : AjaxResult.error("更新失败");
  }


  /**
   * 删除商品分类
   *
   * @param
   * @return
   */
  @Log(title = "删除商品分类", businessType = BusinessType.DELETE)
  @PostMapping(value = "/remove")
  @PreAuthorize("@ss.hasPermi('business:category:remove')")
  @ApiOperation("删除商品分类")
  public AjaxResult remove(@RequestBody GoodsCategory goodsCategory) {

    if (null == goodsCategory.getCategoryId() || 0 == goodsCategory.getCategoryId()) {
      return error(ErrorCodeEnum.ERROR_CODE_1001);
    }
    int cnt = goodsService.count(new LambdaQueryWrapper<Goods>()
        .eq(Goods::getCategoryId, goodsCategory.getCategoryId()).eq(Goods::getIsDeleted, 0));
    if (cnt > 0) {
      return error(ErrorCodeEnum.ERROR_CODE_1024);
    }

    int count = goodsCategoryService.count(new LambdaQueryWrapper<GoodsCategory>()
            .eq(GoodsCategory::getParentId, goodsCategory.getCategoryId()));
    if (count > 0) {
      return error("删除失败，分类下存在子分类");
    }

    boolean res = goodsCategoryService.removeById(goodsCategory.getCategoryId());
    return res ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
  }

}
