package com.hxhq.business.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.hxhq.common.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author tanfei
 */
public class ObjectCompareUtil {
    private static final Logger LOG = LoggerFactory.getLogger(ObjectCompareUtil.class.getName());

    public static void main(String[] args) {

    }

    /**
     * 对比两个对象的差异
     *
     * @param oldObj 原始对象
     * @param newObj 新对象
     * @return 字段变化列表
     */
    public static List<FieldChange> compareObjects(Object oldObj, Object newObj) {
        List<FieldChange> changes = new ArrayList<>();

//        if (oldObj == null || newObj == null) {
//            return changes;
//        }

        // 获取所有字段
        Field[] fields = oldObj.getClass().getDeclaredFields();

        for (Field field : fields) {
            try {
                field.setAccessible(true);

                // 如果没有excel注解，跳过字段
                if (StringUtils.isBlank(getFieldLabel(field))) {
                    continue;
                }
                String name = field.getName();
                Object oldValue = field.get(oldObj);
                String oldValueStr = "";
                String newValueStr = "";
                String date="java.util.Date";
                if(oldValue == null) {
                    oldValueStr = "";
                } else {
                    if (field.getType().getName().equals(date)) {
                        JsonFormat annotation = field.getAnnotation(JsonFormat.class);
                        if(annotation != null && StringUtils.isNotEmpty(annotation.pattern())) {
                            oldValueStr = autoConvert(oldValue, annotation.pattern());
                        } else {
                            oldValueStr = autoConvert(oldValue, "yyyy-MM-dd HH:mm:ss");
                        }
                    } else {
                        oldValueStr = oldValue.toString();
                    }
                }

                try {
                    Object newValue = JSONObject.parseObject(JSONObject.toJSONString(newObj)).get(name);
                    if(newValue == null) {
                        newValueStr = "";
                    } else {
                        if (field.getType().getName().equals(date))  {
                            JsonFormat annotation = field.getAnnotation(JsonFormat.class);
                            if(annotation != null && StringUtils.isNotEmpty(annotation.pattern())) {
                                newValueStr = autoConvert(newValue, annotation.pattern());
                            } else {
                                newValueStr = autoConvert(newValue, "yyyy-MM-dd HH:mm:ss");
                            }
                        } else {
                            newValueStr = newValue.toString();
                        }
                    }

//                    if (StringUtils.isNoneBlank(oldValueStr) && StringUtils.isNoneBlank(newValueStr)) {
                        // 对比字段值
                        if (!Objects.equals(oldValue, newValue)) {
                            FieldChange change = new FieldChange();
                            change.setFieldName(field.getName());
                            change.setFieldLabel(getFieldLabel(field));
                            change.setFieldLabelEn(getFieldLabelEn(field));
                            change.setOldValue(oldValueStr);
                            change.setNewValue(newValueStr);
                            change.setFieldType(field.getType().getSimpleName());
                            changes.add(change);
                        }
//                    }

                } catch (Exception ex) {
                    // 忽略没有的字段
                }

            } catch (IllegalAccessException e) {
                // 忽略无法访问的字段
            }
        }

        return changes;
    }

    /**
     * 对比两个对象的差异
     *
     * @param oldObj 原始对象
     * @param newObj 新对象
     * @return 字段变化列表
     */
    public static List<FieldChange> compareObjectsNotNULL(Object oldObj, Object newObj) {
        List<FieldChange> changes = new ArrayList<>();

//        if (oldObj == null || newObj == null) {
//            return changes;
//        }

        // 获取所有字段
        Field[] fields = oldObj.getClass().getDeclaredFields();

        for (Field field : fields) {
            try {
                field.setAccessible(true);

                // 如果没有excel注解，跳过字段
                if (StringUtils.isBlank(getFieldLabel(field))) {
                    continue;
                }
                String name = field.getName();
                Object oldValue = field.get(oldObj);
                String oldValueStr = "";
                String newValueStr = "";
                String date="java.util.Date";
                if(oldValue == null) {
                    oldValueStr = "";
                } else {
                    if (field.getType().getName().equals(date)) {
                        JsonFormat annotation = field.getAnnotation(JsonFormat.class);
                        if(annotation != null && StringUtils.isNotEmpty(annotation.pattern())) {
                            oldValueStr = autoConvert(oldValue, annotation.pattern());
                        } else {
                            oldValueStr = autoConvert(oldValue, "yyyy-MM-dd HH:mm:ss");
                        }
                    } else {
                        oldValueStr = oldValue.toString();
                    }
                }

                try {
                    Object newValue = JSONObject.parseObject(JSONObject.toJSONString(newObj)).get(name);
                    if(newValue == null) {
                        newValueStr = "";
                    } else {
                        if (field.getType().getName().equals(date))  {
                            JsonFormat annotation = field.getAnnotation(JsonFormat.class);
                            if(annotation != null && StringUtils.isNotEmpty(annotation.pattern())) {
                                newValueStr = autoConvert(newValue, annotation.pattern());
                            } else {
                                newValueStr = autoConvert(newValue, "yyyy-MM-dd HH:mm:ss");
                            }
                        } else {
                            newValueStr = newValue.toString();
                        }
                    }

                   if (StringUtils.isNoneBlank(oldValueStr) && StringUtils.isNoneBlank(newValueStr)) {
                    // 对比字段值
                    if (!Objects.equals(oldValue, newValue)) {
                        FieldChange change = new FieldChange();
                        change.setFieldName(field.getName());
                        change.setFieldLabel(getFieldLabel(field));
                        change.setFieldLabelEn(getFieldLabelEn(field));
                        change.setOldValue(oldValueStr);
                        change.setNewValue(newValueStr);
                        change.setFieldType(field.getType().getSimpleName());
                        changes.add(change);
                    }
                    }

                } catch (Exception ex) {
                    // 忽略没有的字段
                }

            } catch (IllegalAccessException e) {
                // 忽略无法访问的字段
            }
        }

        return changes;
    }


    /**
     * 自动识别时间戳类型并转换
     *
     * @param timestamp 时间戳（支持Long, Integer, String）
     * @param pattern   日期格式
     * @return 格式化后的日期字符串
     */
    public static String autoConvert(Object timestamp, String pattern) {
        if (timestamp == null) {
            return null;
        }
        if (timestamp instanceof Date) {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            return sdf.format(timestamp);
        }

        long millis = 0L;

        if (timestamp instanceof Long) {
            Long ts = (Long) timestamp;
            Long hm=1000000000000L;
            if (ts >hm ) {
                millis = ts;
            } else {
                millis = ts * 1000L;
            }
        } else if (timestamp instanceof Integer) {
            millis = ((Integer) timestamp) * 1000L;
        } else if (timestamp instanceof String) {
            try {
                String tsStr = (String) timestamp;
                Integer a=10;
                Integer b=13;
                if (tsStr.length() == a) {
                    millis = Long.parseLong(tsStr) * 1000L;
                } else if (tsStr.length() == b) {
                    millis = Long.parseLong(tsStr);
                } else {
                    throw new IllegalArgumentException("不支持的时间戳格式: " + tsStr);
                }
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("时间戳格式错误: " + timestamp, e);
            }
        } else {
            throw new IllegalArgumentException("不支持的时间戳类型: " + timestamp.getClass());
        }

        Date date = new Date(millis);
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }


    /**
     * 获取字段的中文描述（如果有@Compare注解）
     */
    private static String getFieldLabel(Field field) {
        // 若依的@Excel注解，可以获取name属性
        if (field.isAnnotationPresent(com.hxhq.common.core.annotation.Compare.class)) {
            com.hxhq.common.core.annotation.Compare excel = field.getAnnotation(com.hxhq.common.core.annotation.Compare.class);
            return excel.name();
        }

        return null;
    }

    /**
     * 获取字段的中文描述（如果有@Compare注解）
     */
    private static String getFieldLabelEn(Field field) {
        // 若依的@Excel注解，可以获取name属性
        if (field.isAnnotationPresent(com.hxhq.common.core.annotation.Compare.class)) {
            com.hxhq.common.core.annotation.Compare excel = field.getAnnotation(com.hxhq.common.core.annotation.Compare.class);
            return excel.nameEn();
        }

        return null;
    }

    /**
     * 字段变化实体类
     */
    public static class FieldChange {
        private String fieldName;      // 字段名
        private String fieldLabel;     // 字段描述
        private String fieldLabelEn;     // 字段描述-英文
        private String oldValue;       // 旧值
        private String newValue;       // 新值
        private String fieldType;      // 字段类型

        // getter和setter
        public String getFieldName() {
            return fieldName;
        }

        public void setFieldName(String fieldName) {
            this.fieldName = fieldName;
        }

        public String getFieldLabel() {
            return fieldLabel;
        }

        public void setFieldLabel(String fieldLabel) {
            this.fieldLabel = fieldLabel;
        }

        public String getFieldLabelEn() {
            return fieldLabelEn;
        }

        public void setFieldLabelEn(String fieldLabelEn) {
            this.fieldLabelEn = fieldLabelEn;
        }

        public Object getOldValue() {
            return oldValue;
        }

        public void setOldValue(String oldValue) {
            this.oldValue = oldValue;
        }

        public String getNewValue() {
            return newValue;
        }

        public void setNewValue(String newValue) {
            this.newValue = newValue;
        }

        public String getFieldType() {
            return fieldType;
        }

        public void setFieldType(String fieldType) {
            this.fieldType = fieldType;
        }

        @Override
        public String toString() {
            Map<String, String> map = new LinkedHashMap<>();
            map.put("字段名", fieldLabel);
            map.put("原值", oldValue);
            map.put("新值", newValue);
            return JctUtil.formatStr(map);
        }

        public String toEnString(){
            Map<String, String> map = new LinkedHashMap<>();
            map.put("Field", fieldLabelEn);
            map.put("Old Value", oldValue);
            map.put("New Value", newValue);
            return JctUtil.formatStr(map);
        }
    }

}
