package com.izouma.dingdong.web.backstage;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.dingdong.dto.MerchantDTO;
import com.izouma.dingdong.web.BaseController;
import com.izouma.dingdong.domain.backstage.Category;
import com.izouma.dingdong.service.backstage.CategoryService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.backstage.CategoryRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.utils.excel.ExcelUtils;

import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/category")
@AllArgsConstructor
public class CategoryController extends BaseController {
    private CategoryService categoryService;
    private CategoryRepo categoryRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Category save(Category record) {
        if (record.getId() != null) {
            Category orig = categoryRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return categoryRepo.save(orig);
        }
        if (ObjectUtil.isNull(record.getParent())) {
            record.setParent(1L);
        }
        return categoryRepo.save(record);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<Category> all(PageQuery pageQuery) {
        return categoryRepo.findAll(toSpecification(pageQuery, Category.class), toPageRequest(pageQuery));
    }

    @GetMapping("/get/{id}")
    public Category get(@PathVariable Long id) {
        return categoryRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        categoryRepo.deleteById(id);
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<Category> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }

    @GetMapping("/tree")
    public List<Category> tree(Long id) {
        return categoryRepo.findAllByParent(id);
    }

    @GetMapping("/merchants")
    @ApiOperation("分类下的商家列表")
    public List<MerchantDTO> merchants(Long id) {
        return categoryService.categoryMer(id);
    }

}

