package com.skr.mdm.api.authority.controller;

import com.skr.mdm.api.authority.service.MdmAuthorizationService;
import com.skr.mdm.dto.LoginAdminDTO;
import com.skr.mdm.result.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author nfq
 * @date 2021/1/20 17:59
 */
@RestController
@RequestMapping("authorization")
@Api(tags = "授权管理")
public class AuthorizationController {

    @Autowired
    private MdmAuthorizationService authorizationService;

    @PostMapping("config")
    @ApiOperation(value = "授权配置")
    public ResponseResult config(@RequestParam MultipartFile file, @ApiIgnore Authentication authentication) throws IOException {
        LoginAdminDTO loginAdminDTO = (LoginAdminDTO) authentication.getPrincipal();
        return authorizationService.config(file, loginAdminDTO);
    }

    @PostMapping("info")
    @ApiOperation(value = "授权信息")
    public ResponseResult info(@ApiIgnore Authentication authentication) {
        LoginAdminDTO loginAdminDTO = (LoginAdminDTO) authentication.getPrincipal();
        return authorizationService.info(loginAdminDTO.getCompanyId());
    }

    @PostMapping("encrypt")
    @ApiOperation(value = "授权加密")
    public ResponseResult info(@RequestParam Long data) {
        return authorizationService.encrypt(data);
    }

    @PostMapping("file")
    @ApiOperation(value = "生成授权文件")
    public ResponseResult info(@RequestParam(required = false) Integer authorizationNumber,
                               @RequestParam(required = false) Long expireTime,
                               @RequestParam String machineCode,
                               HttpServletResponse response) throws Exception {
        if (authorizationNumber == null && expireTime == null) {
            return ResponseResult.failure();
        }
        authorizationService.createEncryptFile(authorizationNumber, expireTime, machineCode, response);
        return ResponseResult.success();
    }
}
