package com.izouma.wenlvju.web;

import com.izouma.wenlvju.domain.Record;
import com.izouma.wenlvju.domain.User;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.dto.RecordExcelDTO;
import com.izouma.wenlvju.enums.AuthorityName;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.RecordRepo;
import com.izouma.wenlvju.repo.UserRepo;
import com.izouma.wenlvju.security.Authority;
import com.izouma.wenlvju.service.RecordService;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.utils.SecurityUtils;
import com.izouma.wenlvju.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
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("/record")
@AllArgsConstructor
public class RecordController extends BaseController {
    private RecordService recordService;
    private RecordRepo    recordRepo;
    private UserRepo      userRepo;

    //@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("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<Record> all(@RequestBody PageQuery pageQuery) {
        return recordService.all2(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);
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<Record> data = all(pageQuery).getContent();
        List<RecordExcelDTO> collect = data.stream().map(RecordExcelDTO::new).collect(Collectors.toList());
        ExcelUtils.export(response, collect);
    }

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

    @ApiOperation("增加监管人")
    @PostMapping("/addSupervisor")
    public Record addSupervisor(@RequestParam Long id, @RequestParam Long userId) {
        return recordService.addSupervisor(id, userId);
    }

    @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());
    }
}

