package com.ruoyi.framework.aspectj;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.DataDictClass;
import com.ruoyi.common.annotation.Dict;
import com.ruoyi.common.api.CommonAPI;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.CommonConstant;
import com.ruoyi.common.utils.OConvertUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
* @Description: å—å…¸aopç±»
* @Date: 21-11-17
*/
@Aspect
@Component
@SuppressWarnings({"unused"})
@Slf4j
public class DictAspect {
@Autowired
private CommonAPI commonAPI;
// 定义切点Pointcut
@Pointcut("@annotation(dataDictClass)")
public void dataDictClass(DataDictClass dataDictClass) {
}
@Around("@annotation(dataDictClass)")
public Object doAround(ProceedingJoinPoint pjp, DataDictClass dataDictClass) throws Throwable {
long time1 = System.currentTimeMillis();
Object result = pjp.proceed();
long time2 = System.currentTimeMillis();
log.debug("获å–JSONæ•°æ® è€—æ—¶ï¼š" + (time2 - time1) + "ms");
long start = System.currentTimeMillis();
this.parseDictText(result);
long end = System.currentTimeMillis();
log.debug("è§£æžæ³¨å…¥JSONæ•°æ® è€—æ—¶" + (end - start) + "ms");
return result;
}
/**
* 本方法针对返回对象为Result çš„IPage的分页列表数æ®è¿›è¡ŒåЍæ€å—典注入
* å—典注入实现 é€šè¿‡å¯¹å®žä½“ç±»æ·»åŠ æ³¨è§£@dict æ¥æ ‡è¯†éœ€è¦çš„å—典内容,å—典分为å•å—å…¸codeå³å¯ ,tableå—å…¸ code table texté…åˆä½¿ç”¨ä¸ŽåŽŸæ¥jeecg的用法相åŒ
* 示例为SysUser å—æ®µä¸ºsex æ·»åŠ äº†æ³¨è§£@Dict(dicCode = "sex") 会在å—å…¸æœåŠ¡ç«‹é©¬æŸ¥å‡ºæ¥å¯¹åº”çš„text ç„¶åŽåœ¨è¯·æ±‚list的时候将这个å—å…¸textï¼Œå·²å—æ®µåç§°åŠ _dictTextå½¢å¼è¿”回到å‰ç«¯
* 例输入当å‰è¿”回值的就会多出一个sex_dictTextå—æ®µ
* {
* sex:1,
* sex_dictText:"ç”·"
* }
* å‰ç«¯ç›´æŽ¥å–值sext_dictText在tableé‡Œé¢æ— 需å†è¿›è¡Œå‰ç«¯çš„å—典转æ¢äº†
* customRender:function (text) {
* if(text==1){
* return "ç”·";
* }else if(text==2){
* return "女";
* }else{
* return text;
* }
* }
* ç›®å‰vue是这么进行å—典渲染到table上的多了就很麻烦了 这个直接在æœåŠ¡ç«¯æ¸²æŸ“å®Œæˆå‰ç«¯å¯ä»¥ç›´æŽ¥ç”¨
*
* @param result
*/
private void parseDictText(Object result) {
// TableDataInfo分页
if (result instanceof TableDataInfo) {
(((TableDataInfo) result)).setRows(transformation(((TableDataInfo<?>) result).getRows()));
}
if (result instanceof AjaxResult) {
// 分页
if (((AjaxResult) result).getData() instanceof IPage) {
((IPage) ((AjaxResult) result).getData()).setRecords(transformation(((IPage) ((AjaxResult) result).getData()).getRecords()));
}
// æ— åˆ†é¡µ-list
if (((AjaxResult) result).getData() instanceof ArrayList) {
(((AjaxResult) result)).setData(transformation((List<?>) ((AjaxResult) result).getData()));
}
// object
if (((AjaxResult) result).getData() instanceof Object) {
(((AjaxResult) result)).setData(transformation(Arrays.asList(((AjaxResult<?>) result).getData())).get(0));
}
}
}
/**
* 翻译å—典文本
*
* @param code
* @param text
* @param table
* @param key
* @return
*/
private String translateDictValue(String code, String text, String table, String key) {
if (OConvertUtils.isEmpty(key)) {
return null;
}
StringBuffer textValue = new StringBuffer();
String[] keys = key.split(",");
for (String k : keys) {
String tmpValue = null;
log.debug(" å—å…¸ key : " + k);
if (k.trim().length() == 0) {
continue; //跳过循环
}
if (!StringUtils.isEmpty(table)) {
log.debug("--DictAspect------dicTable=" + table + " ,dicText= " + text + " ,dicCode=" + code);
tmpValue = commonAPI.translateDictFromTable(table, text, code, k.trim());
} else {
tmpValue = commonAPI.translateDict(code, k.trim());
}
if (tmpValue != null) {
if (!"".equals(textValue.toString())) {
textValue.append(",");
}
textValue.append(tmpValue);
}
}
return textValue.toString();
}
/**
* æ•°æ®è½¬æ¢
*
* @param list
* @return
*/
private List<JSONObject> transformation(List<?> list) {
List<JSONObject> items = new ArrayList<>();
for (Object record : list) {
ObjectMapper mapper = new ObjectMapper();
String json = "{}";
try {
//解决@JsonFormat注解解æžä¸äº†çš„问题详è§SysAnnouncement类的@JsonFormat
json = mapper.writeValueAsString(record);
} catch (JsonProcessingException e) {
log.error("jsonè§£æžå¤±è´¥" + e.getMessage(), e);
}
JSONObject item = JSONObject.parseObject(json);
//update-begin--Author:scott -- Date:20190603 ----forï¼šè§£å†³ç»§æ‰¿å®žä½“å—æ®µæ— 法翻译问题------
//for (Field field : record.getClass().getDeclaredFields()) {
for (Field field : OConvertUtils.getAllFields(record)) {
//update-end--Author:scott -- Date:20190603 ----forï¼šè§£å†³ç»§æ‰¿å®žä½“å—æ®µæ— 法翻译问题------
if (field.getAnnotation(Dict.class) != null) {
String code = field.getAnnotation(Dict.class).dicCode();
String text = field.getAnnotation(Dict.class).dicText();
String table = field.getAnnotation(Dict.class).dictTable();
String key = String.valueOf(item.get(field.getName()));
//翻译å—典值对应的txt
String textValue = translateDictValue(code, text, table, key);
log.debug(" å—å…¸Val : " + textValue);
log.debug(" __翻译å—兏嗿®µ__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
}
//date类型默认转æ¢stringæ ¼å¼åŒ–日期
if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
}
}
items.add(item);
}
return items;
}
}