package com.izouma.dingdong.web.merchant;

import com.izouma.dingdong.dto.MerchantComplaintDTO;
import com.izouma.dingdong.web.BaseController;
import com.izouma.dingdong.domain.merchant.MerchantComplaint;
import com.izouma.dingdong.service.merchant.MerchantComplaintService;
import com.izouma.dingdong.dto.PageQuery;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.merchant.MerchantComplaintRepo;
import com.izouma.dingdong.utils.ObjUtils;
import com.izouma.dingdong.utils.excel.ExcelUtils;

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 java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/merchantComplaint")
@AllArgsConstructor
public class MerchantComplaintController extends BaseController {
    private MerchantComplaintService merchantComplaintService;
    private MerchantComplaintRepo    merchantComplaintRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public MerchantComplaint save(@RequestBody MerchantComplaint record) {
        if (record.getId() != null) {
            MerchantComplaint orig = merchantComplaintRepo.findById(record.getId())
                    .orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return merchantComplaintRepo.save(orig);
        }
        record.setTime(LocalDateTime.now());
        return merchantComplaintRepo.save(record);
    }


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

    @GetMapping("/allDto")
    public Page<MerchantComplaintDTO> allDto(PageQuery pageQuery) {
        return all(pageQuery).map(merchantComplaintService::toDto);
    }

    @GetMapping("/get/{id}")
    public MerchantComplaint get(@PathVariable Long id) {
        return merchantComplaintRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }
    @GetMapping("/getDto/{id}")
    public MerchantComplaintDTO getDto(@PathVariable Long id) {
        return merchantComplaintService.toDto(merchantComplaintRepo.findById(id).orElseThrow(new BusinessException("无记录")));
    }

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

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

