package cn.chnmuseum.party.web.controller;

import cn.chnmuseum.party.web.controller.base.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 公共方法接口
 * </p>
 *
 * @author 杨建龙
 * @since 2018-10-11
 */
@Api(tags = "公共方法接口")
@RestController
@RequestMapping("/public")
public class PublicController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(PublicController.class);

    /**
     * 解密
     *
     * @param src byte[]
     * @param key String
     * @return byte[]
     * @throws Exception
     */
    private static byte[] decrypt(byte[] src, String key) throws Exception {
        // DES算法要求有一个可信任的随机数源
        SecureRandom random = new SecureRandom();
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(key.getBytes(StandardCharsets.UTF_8));
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        // 真正开始解密操作
        return cipher.doFinal(src);
    }

    /**
     * 验证token
     *
     * @return
     */
    @ApiOperation(value = "验证token")
    @GetMapping(value = "/authToken")
    @RequiresAuthentication  //@RequiresPermissions("/public/authToken")
    public ResponseEntity<Map<Object, String>> authToken() {
        try {
            Map<Object, String> map = new HashMap<>();
            map.put("status", "200");
            map.put("message", "验证成功");
            return ResponseEntity.status(HttpStatus.OK).body(map);
        } catch (Exception e) {
            logger.error("服务器错误!", e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

}