package com.izouma.wenlvju.web;

import cn.hutool.core.collection.CollUtil;
import com.izouma.wenlvju.domain.Record;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.dto.RecordDTO;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.RecordRepo;
import com.izouma.wenlvju.service.RecordService;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.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;

@Slf4j
@RestController
@RequestMapping("/record")
@AllArgsConstructor
public class RecordController extends BaseController {
    private RecordService recordService;
    private RecordRepo    recordRepo;

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


    @PreAuthorize("hasAnyRole('ADMIN','DISTRICT','DISTRICT_STAFF','EXPERT')")
    @PostMapping("/all")
    public Page<Record> all(@RequestBody PageQuery pageQuery) {
        return recordService.all2(pageQuery);
    }

    @PreAuthorize("hasRole('ORGANIZER')")
    @PostMapping("/byOrganization")
    public Page<Record> byOrganization(@RequestBody PageQuery pageQuery) {
        return recordService.all(pageQuery);
    }

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

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        recordRepo.softDelete(id);
    }

    @PostMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, @RequestBody PageQuery pageQuery) throws IOException {
        List<Record> data = all(pageQuery).getContent();
        List<RecordDTO> collect = recordService.excel(data);
        if (CollUtil.isEmpty(collect)){
            return;
        }
        ExcelUtils.export(response, collect);
    }

    @GetMapping("/update")
    public Record update() {
        Record record = recordRepo.findFirstByDelIsTrue();
        record.setDel(false);
        return recordRepo.save(record);
    }

    @PostMapping("/allDTO")
    public Page<Record> allDTO(@RequestBody PageQuery pageQuery) {
//        Map<Long, String> userMap = userRepo.findAllByAuthoritiesContainsAndDelFalse(Authority.get(AuthorityName.ROLE_SUPERVISOR))
//                .stream()
//                .collect(Collectors.toMap(User::getId, User::getNickname));
        return recordService.all(pageQuery);
//                .map(record -> {
//                    record.setSupervisorNickname(userMap.get(record.getSupervisorUserId()));
//                    return record;
//                });
    }

    @GetMapping("/supervisor")
    public List<Record> supervisor() {
//        return recordRepo.findAllBySupervisorUserId(SecurityUtils.getAuthenticatedUser().getId());
        return null;
    }

    @PostMapping("/byToday")
    @ApiOperation("今日所有备案")
    public List<Record> byToday( String district) {
        return recordService.byToday( district);
    }

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

