package com.izouma.zhirongip.web.supply;

import com.izouma.zhirongip.domain.Setting;
import com.izouma.zhirongip.dto.PatentExcelDto;
import com.izouma.zhirongip.repo.SettingRepo;
import com.izouma.zhirongip.service.SettingService;
import com.izouma.zhirongip.utils.SecurityUtils;
import com.izouma.zhirongip.web.BaseController;
import com.izouma.zhirongip.domain.supply.Patent;
import com.izouma.zhirongip.service.supply.PatentService;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.exception.BusinessException;
import com.izouma.zhirongip.repo.supply.PatentRepo;
import com.izouma.zhirongip.utils.ObjUtils;
import com.izouma.zhirongip.utils.excel.ExcelUtils;

import io.swagger.annotations.ApiOperation;
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;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/patent")
@AllArgsConstructor
@Slf4j
public class PatentController extends BaseController {
    private final PatentService  patentService;
    private final PatentRepo     patentRepo;
    private final SettingService settingService;
    private final SettingRepo    settingRepo;

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


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

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

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

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<PatentExcelDto> data = all(pageQuery)
                .getContent().stream()
                .map(PatentExcelDto::from)
                .collect(Collectors.toList());
        List<Setting> settings = settingService.getTree(settingRepo.findAllByFlag(1));
        data.forEach(d -> {
            d.setIndustryName(settings.stream().filter(s -> s.getId().equals(d.getIndustryClass())).findFirst()
                                      .map(Setting::getName).orElse(null));
        });
        ExcelUtils.export(response, data);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("审核")
    @PostMapping("/audit")
    public void audit(@RequestParam Long id, @RequestParam boolean pass, String remark) {
        patentService.audit(id, pass, remark);
    }

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

