package com.izouma.nineth.web;

import com.izouma.nineth.domain.IdentityAuth;
import com.izouma.nineth.enums.AuthStatus;
import com.izouma.nineth.service.IdentityAuthService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.IdentityAuthRepo;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
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;

@RestController
@RequestMapping("/identityAuth")
@AllArgsConstructor
public class IdentityAuthController extends BaseController {
    private IdentityAuthService identityAuthService;
    private IdentityAuthRepo    identityAuthRepo;

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

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/get/{id}")
    public IdentityAuth get(@PathVariable Long id) {
        return identityAuthRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

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

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

    @PostMapping("/apply")
    public void apply(IdentityAuth identityAuth) {
        identityAuth.setUserId(SecurityUtils.getAuthenticatedUser().getId());
        identityAuthService.apply(identityAuth);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/pass")
    public void audit(@RequestParam Long id) {
        identityAuthService.audit(id, AuthStatus.SUCCESS);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/deny")
    public void deny(@RequestParam Long id) {
        identityAuthService.audit(id, AuthStatus.FAIL);
    }
}

