package com.izouma.zhirongip.web.resource;

import com.izouma.zhirongip.dto.CompanyDTO;
import com.izouma.zhirongip.web.BaseController;
import com.izouma.zhirongip.domain.resource.Company;
import com.izouma.zhirongip.service.resource.CompanyService;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.resource.CompanyRepo;
import com.izouma.zhirongip.utils.ObjUtils;
import com.izouma.zhirongip.utils.excel.ExcelUtils;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

@Slf4j
@RestController
@RequestMapping("/company")
@AllArgsConstructor
public class CompanyController extends BaseController {
    private final CompanyService companyService;
    private final CompanyRepo    companyRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<Company> all(@RequestBody PageQuery pageQuery) {
        return companyService.all(pageQuery);
    }

    @GetMapping("/get/{id}")
    public Company get(@PathVariable Long id) {
        return companyService.get(id);
    }

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

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<Company> data = companyService.excelAll(pageQuery).getContent();
        List<CompanyDTO> dtos = companyService.toDtoList(data);
        ExcelUtils.export(response, dtos);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/upload")
    public void uploadFile(@RequestParam("file") MultipartFile file) {
        InputStream is;
        try {
            is = file.getInputStream();
            companyService.upload(is);
        } catch (IOException e) {
            log.error("上传失败", e);
            throw new BusinessException("上传失败", e.getMessage());
        }
    }
}

