package com.izouma.jmrh.web;

import cn.hutool.core.convert.Convert;
import com.izouma.jmrh.domain.Expert;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.ExpertRepo;
import com.izouma.jmrh.service.ExpertService;
import com.izouma.jmrh.utils.ObjUtils;
import com.izouma.jmrh.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;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/expert")
@AllArgsConstructor
public class ExpertController extends BaseController {
    private final ExpertService expertService;
    private final ExpertRepo    expertRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<Expert> all(@RequestBody PageQuery pageQuery) {
        Map<String, Object> query = pageQuery.getQuery();
        Object fieldObj = query.get("field");
        Long field = Convert.convert(Long.class, fieldObj);
        query.remove("field");

        return expertService.all(pageQuery, field);
    }

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

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

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

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

