package org.springblade.modules.QRCode.service;


import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson.JSON;
import org.springblade.common.cache.CacheNames;
import org.springblade.common.cache.PaymentCache;
import org.springblade.modules.QRCode.entity.SingleCodeDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springblade.modules.QRCode.utils.CodeUtils;



/**
 * @author: lianghanqiang
 * @description: 二维码服务层
 * @since: 7/29/21 -- 10:35 AM
 */
@Service
public class QRCodeService {
	
	@Autowired
	private CacheManager cacheManager;

	private static AES aes;
	private static Digester md5;

	public static final String QR_CODE = PaymentCache.QR_CODE;
	public static final String BAR_CODE = PaymentCache.BAR_CODE;

	private static final String PRIVATE_KEY = "DYgj5EIMVrj2W9xN";
	private static final String IV = "eLPO4EIMVrj2W9xN";

	 static  {
		 aes = new AES("CBC", "PKCS7Padding",
			 PRIVATE_KEY.getBytes(),
			 // iv加盐，按照实际需求添加
			 IV.getBytes());
		  md5 = new Digester(DigestAlgorithm.MD5);
	}

	/**
	 *  生成二维码，二维码类型为收款码则缓存
	 * */
	@Cacheable(cacheNames = {CacheNames.PAYMENT},key ="#root.target.QR_CODE + #content.id",unless = "#content.type!='Charge_Code'")
	public String fetchQRCode(SingleCodeDto content, String logo){
		return CodeUtils.createCode(logo,md5.digestHex(JSON.toJSONString(content)));
	}

	/**
	 *  生成条形码，条形码类型为收款码则缓存
	 * */
	@Cacheable(cacheNames = {CacheNames.PAYMENT},key ="#root.target.BAR_CODE + #content.id",unless = "#content.type!='Charge_Code'")
	public String fetchBar(SingleCodeDto content){
		return CodeUtils.createBar(md5.digestHex(JSON.toJSONString(content)));
	}

	public String enCode(Object content){
		return aes.encryptHex(JSON.toJSONString(content));
	}

	public String encodeMD5(Object content,String id){
		return md5.digestHex(JSON.toJSONString(content)+id);
	}

	public <T> T  deCode(String content,Class<T> clazz) {
		return JSON.parseObject(aes.decryptStr(content), clazz);
	}

	public static void main(String[] args) {
		System.out.println(PRIVATE_KEY.getBytes().length);
		String content = "123465asdf";
		String encryptHex = aes.encryptHex(content);
		String decryptStr = aes.decryptStr(encryptHex);
		System.out.println(encryptHex);
		System.out.println(decryptStr);
	}
}
