package com.izouma.uwip.web;

import com.izouma.uwip.domain.LogoPatent;
import com.izouma.uwip.domain.Partner;
import com.izouma.uwip.repo.PartnerRepo;
import com.izouma.uwip.service.LogoPatentService;
import com.izouma.uwip.dto.PageQuery;
import com.izouma.uwip.exception.BusinessException;
import com.izouma.uwip.repo.LogoPatentRepo;
import com.izouma.uwip.utils.SecurityUtils;
import com.izouma.uwip.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.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/logoPatent")
@AllArgsConstructor
public class LogoPatentController extends BaseController {
    private LogoPatentService logoPatentService;
    private LogoPatentRepo    logoPatentRepo;
    private PartnerRepo       partnerRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public LogoPatent save(@RequestBody LogoPatent record) {
        Long id = SecurityUtils.getAuthenticatedUser().getId();
        return logoPatentService.save(record, id);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<LogoPatent> all(@RequestBody PageQuery pageQuery) {
        pageQuery.setSort("createdAt,desc");
        Map<Long, String> partnerMap = partnerRepo.findAll()
                .stream()
                .collect(Collectors.toMap(Partner::getId, Partner::getName));
        return logoPatentService.all(pageQuery).map(logoPatent -> {
            logoPatent.setClientPartner(partnerMap.get(logoPatent.getClientPartnerId()));
            logoPatent.setSupplierPartner(partnerMap.get(logoPatent.getSupplierPartnerId()));
            return logoPatent;
        });
    }

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

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

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

