package com.zt.plat.module.qms.core.aspect;

import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.security.core.LoginUser;
import com.zt.plat.module.qms.core.aspect.annotation.Dict;
import com.zt.plat.module.qms.core.legend.LegendApi;
import com.zt.plat.module.qms.core.constant.CommonConstant;
import com.zt.plat.module.qms.core.legend.LegendConvertUtils;
import com.zt.plat.module.qms.core.legend.vo.DictModel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
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.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.zt.plat.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static com.zt.plat.module.qms.core.constant.CacheConstant.QMS_DICT_BIZ_CACHE;
import static com.zt.plat.module.qms.core.constant.CacheConstant.QMS_DICT_TABLE_CACHE;
import static com.zt.plat.module.qms.core.constant.DataTypeConstant.DICT_ANNOTATION_SPLIT;

@Aspect
@Component
@Slf4j
public class DictAspect {
    @Lazy
    @Autowired private LegendApi legendApi;
    @Autowired public RedisTemplate redisTemplate;

    @Autowired private ObjectMapper objectMapper;

    private static final String JAVA_UTIL_DATE = "java.util.Date";

    /**
     * 定义切点Pointcut
     */
    @Pointcut("execution(public * com.zt.plat.module.qms..*.*Controller.*(..))")
    public void executeService() {
    }

    @Around("executeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    	long time1=System.currentTimeMillis();
        Object result = pjp.proceed();
        long time2=System.currentTimeMillis();
        log.info("获取JSON数据 耗时："+(time2-time1)+"ms");
        long start=System.currentTimeMillis();
        result=this.parseDictText(result);
        long end=System.currentTimeMillis();
        log.info("注入字典到JSON数据  耗时"+(end-start)+"ms");
        return result;
    }

    /**
     * 本方法针对返回对象为CommonResult 的 PageResult 的分页列表数据进行动态字典注入
     * 字典注入实现 通过对实体类添加注解@dict 来标识需要的字典内容,字典分为单字典code即可。
     * 同时支持table字典 code table text
     * 示例为SysUser   字段为sex 添加了注解@Dict(dicCode = "sex") 会在字典服务立马查出来对应的text 然后在请求list的时候将这个字典text，已字段名称加_dictText形式返回到前端
     * 例输入当前返回值的就会多出一个sex_dictText字段
     * {
     *      sex:1,
     *      sex_dictText:"男"
     * }
     */
    private Object parseDictText(Object result) {
        if (!(result instanceof CommonResult))
            return result;
        Object data = ((CommonResult) result).getData();
//        if (!(data instanceof PageResult<?>) && !(data instanceof ArrayList<?>))
//            return result;
        List<JSONObject> items = new ArrayList<>();

        //step.1 筛选出加了 Dict 注解的字段列表
        List<Field> dictFieldList = new ArrayList<>();
        // 字典数据列表， key = 字典code，value=数据列表
        Map<String, List<String>> dataListMap = new HashMap<>(5);
        //取出结果集
        List records = new ArrayList();
        String instanceType = "";
        boolean singleDataFlag = false;
        if(data instanceof PageResult<?>){
            records = ((PageResult) data).getList();
            instanceType = "PageResult";
        }
        else if(data instanceof ArrayList<?>){
            records = (List) data;
            instanceType = "ArrayList";
        }else{
            records.add( data);
            singleDataFlag = true;
        }

        Boolean hasDict= checkHasDict(records);
        if(!hasDict){
            return result;
        }

        log.debug(" __ 进入字典翻译切面 DictAspect —— " );
        for (Object record : records) {
            String json="{}";
            try {
                json = objectMapper.writeValueAsString(record);
            } catch (JsonProcessingException e) {
                log.error("json解析失败"+e.getMessage(),e);
            }
            JSONObject item = JSONObject.parseObject(json, Feature.OrderedField);

            // 遍历所有字段，把字典Code取出来，放到 map 里
            for (Field field : LegendConvertUtils.getAllFields(record)) {
                String value = item.getString(field.getName());
                if (LegendConvertUtils.isEmpty(value)) {
                    continue;
                }
                if (field.getAnnotation(Dict.class) == null) {
                    continue;
                }
                if (!dictFieldList.contains(field)) {
                    dictFieldList.add(field);
                }
                String code = field.getAnnotation(Dict.class).dicCode();
                String text = field.getAnnotation(Dict.class).dicText();
                String table = field.getAnnotation(Dict.class).dictTable();
                String keyOrId = field.getAnnotation(Dict.class).keyOrID();

                List<String> dataList;
                String dictCode = code;
                if (!StringUtils.isEmpty(table)) {
                    //指定table
                    dictCode = String.format("%s,%s,%s", table, text, code);
                }else{
                    dictCode = String.format("%s"+DICT_ANNOTATION_SPLIT+"%s", code, keyOrId);
                }
                dataList = dataListMap.computeIfAbsent(dictCode, k -> new ArrayList<>());
                this.listAddAllDeduplicate(dataList, Arrays.asList(value.split(",")));
            }
            items.add(item);
        }

        //step.2 调用翻译方法，一次性翻译
        Map<String, List<DictModel>> translText = this.translateAllDict(dataListMap);

        //step.3 将翻译结果填充到返回结果里
        for (JSONObject record : items) {
            for (Field field : dictFieldList) {
                String code = field.getAnnotation(Dict.class).dicCode();
                String text = field.getAnnotation(Dict.class).dicText();
                String table = field.getAnnotation(Dict.class).dictTable();
                //update-begin--Author:wxr -- Date:20230509 ----for：增加是否为业务字典

                String fieldDictCode = code;
                if (!StringUtils.isEmpty(table)) {
                    fieldDictCode = String.format("%s,%s,%s", table, text, code);
                }
                //update-end--Author:wxr -- Date:20230509 ----for：增加是否为业务字典

                String value = record.getString(field.getName());
                if (LegendConvertUtils.isNotEmpty(value)) {
                    List<DictModel> dictModels = translText.get(fieldDictCode);
                    if(dictModels==null || dictModels.size()==0){
                        continue;
                    }

                    String textValue = this.translDictText(dictModels, value);
                    log.debug(" 字典Val : " + textValue);
                    log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + "： " + textValue);

                    // TODO-sun 测试输出，待删
                    log.debug(" ---- dictCode: " + fieldDictCode);
                    log.debug(" ---- value: " + value);
                    log.debug(" ----- text: " + textValue);
                    log.debug(" ---- dictModels: " + JSON.toJSONString(dictModels));

                    record.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                }
            }
        }

        if(instanceType.equals("PageResult")){
            ((PageResult) data).setList(items);
        }
        else if(instanceType.equals("ArrayList")){
            ((ArrayList) data).clear();
            ((ArrayList) data).addAll(items);
        }
        if(singleDataFlag){
            ((CommonResult<JSONObject>) result).setData( items.get(0));
        }
        return result;
    }

    /**
     * list 去重添加
     */
    private void listAddAllDeduplicate(List<String> dataList, List<String> addList) {
        // 筛选出dataList中没有的数据
        List<String> filterList = addList.stream().filter(i -> !dataList.contains(i)).collect(Collectors.toList());
        dataList.addAll(filterList);
    }

    /**
     * 一次性把所有的字典都翻译了
     * 1.  所有的普通数据字典的所有数据只执行一次SQL
     * 2.  表字典相同的所有数据只执行一次SQL
     * @param dataListMap
     * @return
     */
    private Map<String, List<DictModel>> translateAllDict(Map<String, List<String>> dataListMap) {
        //获取当前租户
        LoginUser loginUser = getLoginUser();
        Long tenantId = loginUser.getTenantId();
        // 翻译后的字典文本，key=dictCode
        Map<String, List<DictModel>> translText = new HashMap<>(5);
        // 需要翻译的数据（有些可以从redis缓存中获取，就不走数据库查询）
        List<String> needTranslData = new ArrayList<>();
        // 需要翻译的数据 - 业务字典
        List<String> needTanslBizData = new ArrayList<>();
        //step.1 先通过redis中获取缓存字典数据
        for (String dictCode : dataListMap.keySet()) {
            List<String> dataList = dataListMap.get(dictCode);
            if (dataList.size() == 0) {
                continue;
            }
            // 表字典需要翻译的数据
            List<String> needTranslDataTable = new ArrayList<>();
            for (String s : dataList) {
                String data = s.trim();
                if (data.length() == 0) {
                    continue; //跳过循环
                }
                if (dictCode.contains(",")) {
                    String keyString = String.format(QMS_DICT_TABLE_CACHE + "::SimpleKey [%s,%s]", dictCode, data);
                    if (redisTemplate.hasKey(keyString)) {
                        try {
                            String text = LegendConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
                            List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
                            list.add(new DictModel(data, text));
                        } catch (Exception e) {
                            log.warn(e.getMessage());
                        }
                    } else if (!needTranslDataTable.contains(data)) {
                        // 去重添加
                        needTranslDataTable.add(data);
                    }
                } else if (dictCode.startsWith("biz+")) {
                    String keyString = String.format(QMS_DICT_BIZ_CACHE + "::%s:%s:%s", tenantId, dictCode.substring(4), data);
                    if (redisTemplate.hasKey(keyString)) {
                        try {
                            String text = LegendConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
                            List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
                            list.add(new DictModel(data, text));
                        } catch (Exception e) {
                            log.warn(e.getMessage());
                        }
                    } else if (!needTanslBizData.contains(data)) {
                        // 去重添加
                        needTanslBizData.add(data);
                    }
                } else {
                    String keyString = String.format(QMS_DICT_BIZ_CACHE + "::%s:%s", dictCode, data);
                    if (redisTemplate.hasKey(keyString)) {
                        try {
                            String text = LegendConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
                            List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
                            list.add(new DictModel(data, text));
                        } catch (Exception e) {
                            log.warn(e.getMessage());
                        }
                    } else if (!needTranslData.contains(data)) {
                        // 去重添加
                        needTranslData.add(data);
                    }
                }

            }
            //step.2 调用数据库翻译表字典
            if (needTranslDataTable.size() > 0) {
                String[] arr = dictCode.split(",");
                String table = arr[0], text = arr[1], code = arr[2];
                String values = String.join(",", needTranslDataTable);
                log.debug("translateDictFromTableByKeys.dictCode:" + dictCode);
                log.debug("translateDictFromTableByKeys.values:" + values);
                List<DictModel> texts = legendApi.translateDictFromTableByKeys(table, text, code, values);
                log.debug("translateDictFromTableByKeys.result:" + texts);
                List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
                list.addAll(texts);

                // 做 redis 缓存
                String strTemplate = QMS_DICT_TABLE_CACHE + "::SimpleKey [%s,%s]";
                for (DictModel dict : texts) {
                    String redisKey = String.format(strTemplate, dictCode, dict.getValue());
                    try {
                        // 保留1分钟
                        redisTemplate.opsForValue().set(redisKey, dict.getText(), 60, TimeUnit.SECONDS);
                    } catch (Exception e) {
                        log.warn(e.getMessage(), e);
                    }
                }
            }
        }

        //step.3 调用数据库进行翻译业务字典
        if (needTanslBizData.size() > 0) {
            List<String> dictCodeList = Arrays.asList(dataListMap.keySet().toArray(new String[]{}));
            // 将业务字典的key筛选出来
            List<String> filterDictCodes = dictCodeList.stream().filter(key -> key.startsWith("biz+")).map(key -> key.substring(4)).collect(Collectors.toList());
            String dictCodes = String.join(",", filterDictCodes);
            String values = String.join(",", needTanslBizData);
            log.debug("translateManyDictBiz.dictCodes:" + dictCodes);
            log.debug("translateManyDictBiz.values:" + values);

            Map<String, List<DictModel>> manyDict = legendApi.translateManyDictBiz(dictCodes, values);

            log.debug("translateManyDictBiz.result:" + manyDict);
            String strTemplate = QMS_DICT_BIZ_CACHE + "::%s:%s:%s";
            for (String dictCode : manyDict.keySet()) {
                List<DictModel> list = translText.computeIfAbsent("biz+" + dictCode, k -> new ArrayList<>());
                List<DictModel> newList = manyDict.get(dictCode);
                list.addAll(newList);
                // 做 redis 缓存
                for (DictModel dict : newList) {
                    String redisKey = String.format(strTemplate, tenantId, dictCode, dict.getValue());
                    try {
                        redisTemplate.opsForValue().set(redisKey, dict.getText());
                    } catch (Exception e) {
                        log.warn(e.getMessage(), e);
                    }
                }
            }
        }

        //step.4 调用数据库进行翻译普通字典
        if (needTranslData.size() > 0) {
            List<String> dictCodeList = Arrays.asList(dataListMap.keySet().toArray(new String[]{}));
            // 将不包含逗号的字典code筛选出来，因为带逗号的是表字典，而不是普通的数据字典
            List<String> filterDictCodes = dictCodeList.stream().filter(key -> !key.contains(",")).collect(Collectors.toList());
            String dictCodes = String.join(",", filterDictCodes);
            String values = String.join(",", needTranslData);
            log.debug("translateManyDict.dictCodes:" + dictCodes);
            log.debug("translateManyDict.values:" + values);

            Map<String, List<DictModel>> manyDict = legendApi.translateManyDict(dictCodes, values);
            String strTemplate = QMS_DICT_BIZ_CACHE + "::%s:%s";
            log.debug("translateManyDict.result:" + manyDict);
            for (String dictCode : manyDict.keySet()) {
                List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
                List<DictModel> newList = manyDict.get(dictCode);
                list.addAll(newList);

                // 做 redis 缓存
                for (DictModel dict : newList) {
                    String redisKey = String.format(strTemplate, dictCode, dict.getValue());
                    try {
                        redisTemplate.opsForValue().set(redisKey, dict.getText());
                    } catch (Exception e) {
                        log.warn(e.getMessage(), e);
                    }
                }
            }
        }
        return translText;
    }

    /**
     * 字典值替换文本
     *
     * @param dictModels
     * @param values
     * @return
     */
    private String translDictText(List<DictModel> dictModels, String values) {
        List<String> result = new ArrayList<>();

        // 允许多个逗号分隔，允许传数组对象
        String[] splitVal = values.split(",");
        for (String val : splitVal) {
            String dictText = val;
            for (DictModel dict : dictModels) {
                if (val.equals(dict.getValue())) {
                    dictText = dict.getText();
                    break;
                }
            }
            result.add(dictText);
        }
        return String.join(",", result);
    }

    /**
     * 检测返回结果集中是否包含Dict注解
     * @param records
     * @return
     */
    private Boolean checkHasDict(List<Object> records){
        if(LegendConvertUtils.isNotEmpty(records) && records.size()>0){
            // 添加对第一个元素的空值检查
            Object firstRecord = records.get(0);
            if (firstRecord == null) {
                return false;
            }
            for (Field field : LegendConvertUtils.getAllFields(records.get(0))) {
                if (LegendConvertUtils.isNotEmpty(field.getAnnotation(Dict.class))) {
                    return true;
                }
            }
        }
        return false;
    }

}
