package shop.alien.second.platform;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiSort;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.second.SecondGoodsCategory;
import shop.alien.mapper.second.SecondGoodsCategoryMapper;
import shop.alien.second.service.SecondGoodsCategoryService;

import java.util.List;

@Slf4j
@Api(tags = {"二手平台-商品类型"})
@ApiSort(9)
@CrossOrigin
@RestController
@RequestMapping("/second/goodsCategory")
@RequiredArgsConstructor
public class PlatformSecondCategoryController {

    private final SecondGoodsCategoryService service;

    @Autowired
    private SecondGoodsCategoryMapper mapper;

    @ApiOperation("新增商品类型")
    @PostMapping("/insertSecondGoodsCategory")
    public R<String> insertSecondGoodsCategory(@RequestBody SecondGoodsCategory category) throws Exception {
        log.info("SecondGoodsCategoryController.insertSecondGoodsCategory?category={}", category.toString());

        // 查询商品类型名称
        QueryWrapper<SecondGoodsCategory> repeatCategory = new QueryWrapper<>();
        repeatCategory.eq("category_name", category.getCategoryName().trim());
        List<SecondGoodsCategory> list = mapper.selectList(repeatCategory);
        if (list.size() > 0) {
            return R.fail("商品类型名称已存在，请修改商品类型名称！");
        }

        Integer reporting = service.insertSecondGoodsCategory(category);
        if (0 == reporting) {
            return R.fail("新增商品类型失败");
        } else {
            return R.data("新增商品类型成功");
        }
    }

    @ApiOperation("修改商品类型")
    @PostMapping("/updateSecondGoodsCategory")
    public R<String> updateSecondGoodsCategory(@RequestBody SecondGoodsCategory category) throws Exception  {
        log.info("SecondGoodsCategoryController.updateSecondGoodsCategory?category={}", category.toString());
        Integer reporting = service.updateSecondGoodsCategory(category);
        if (0 == reporting) {
            return R.fail("修改商品类型失败");
        } else {
            return R.data("修改商品类型成功");
        }
    }

    @ApiOperation("搜索商品类型树形结构")
    @PostMapping("/querySecondGoodsTree")
    public R<List<SecondGoodsCategory>> querySecondGoodsTree() throws Exception {
        return R.data(service.querySecondGoodsTree(), "查询成功");
    }
}
