package com.izouma.dingdong.web.merchant;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.izouma.dingdong.domain.merchant.Goods;
import com.izouma.dingdong.service.merchant.MerchantService;
import com.izouma.dingdong.utils.SecurityUtils;
import com.izouma.dingdong.web.BaseController;
import com.izouma.dingdong.domain.merchant.MerchantClassification;
import com.izouma.dingdong.service.merchant.MerchantClassificationService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.merchant.MerchantClassificationRepo;
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.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Null;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/classification")
@AllArgsConstructor
public class MerchantClassificationController extends BaseController {
    private MerchantClassificationService merchantClassificationService;
    private MerchantClassificationRepo merchantClassificationRepo;
    private MerchantService merchantService;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    @ApiOperation("商家添加修改分类")
    public MerchantClassification save(@RequestBody MerchantClassification record) {
        //修改
        if (record.getId() != null) {
            MerchantClassification orig = merchantClassificationRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            MerchantClassification byName = merchantClassificationRepo.findByMerchantIdAndName(orig.getMerchantId(), orig.getName());
            if (ObjectUtil.isNotNull(byName)) {
                if (!byName.getId().equals(orig.getId())) {
                    throw new BusinessException("该分类已存在");
                }
            }
            return merchantClassificationRepo.save(orig);
        }
        MerchantClassification add = merchantClassificationService.add(SecurityUtils.getAuthenticatedUser().getId(), record);
        //添加
        return add;
        //return merchantClassificationRepo.save(record);
    }


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

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

    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        MerchantClassification classification = merchantClassificationRepo.findById(id).orElseThrow(new BusinessException("无分类"));
        if (StrUtil.isNotBlank(classification.getGoodsIds())) {
            throw new BusinessException("该分类下有商品，暂无法删除");
        }
        merchantClassificationRepo.deleteById(id);
    }

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

    @GetMapping("/my")
    @ApiOperation("商户下的分类名称")
    public List<MerchantClassification> my() {
        List<MerchantClassification> merchantClassifications = merchantClassificationRepo.findAllByMerchantId(merchantService.findMerchantId(SecurityUtils.getAuthenticatedUser().getId()));
        merchantClassifications.sort(Comparator.comparing(MerchantClassification::getSort));
        return merchantClassifications;
    }

    @GetMapping("/saveGoods")
    @ApiOperation("分类下添加商品")
    public MerchantClassification saveGoods(Long classificationId, String string) {
        return merchantClassificationService.saveGoods(classificationId, string);
    }

    @GetMapping("/delGoods")
    @ApiOperation("分类下删除商品")
    public void delGoods(Long classificationId, Long goodId) {
        merchantClassificationService.delGoods(classificationId, goodId);
    }

    @GetMapping("/saveOneGoods")
    @ApiOperation("分类下添加一个商品")
    public void saveOneGoods(Long classificationId, Long goodId) {
        merchantClassificationService.saveOneGoods(classificationId, goodId);
    }

    @GetMapping("/allGoods")
    @ApiOperation("分类下的所有商品")
    public List<Goods> allGoods(Long classificationId) {
        return merchantClassificationService.showGoods(classificationId);
    }

}

