package com.seer.teach.mall.aspect;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.seer.teach.mall.annotation.OrderLog;
import com.seer.teach.mall.context.OrderLogContextHolder;
import com.seer.teach.mall.entity.OrderLogEntity;
import com.seer.teach.mall.service.IOrderLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

import static java.util.Collections.emptyMap;

/**
 * 订单操作日志切面
 *
 * @author Captain
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
@Order(1)
public class OrderLogAspect {

    private final IOrderLogService orderLogService;

    @Around("@annotation(orderLog)")
    public Object recordOrderLog(ProceedingJoinPoint joinPoint, OrderLog orderLog) throws Throwable {
        Object result;
        boolean proceedSuccess = false;

        try {
            result = joinPoint.proceed();
            proceedSuccess = true;
            return result;
        } finally {
            try {
                if (proceedSuccess) {
                    saveOrderLogs(orderLog);
                }
            } catch (Exception e) {
                log.error("记录订单日志时发生异常", e);
            } finally {
                // 清除上下文
                OrderLogContextHolder.clear();
            }
        }
    }

    /**
     * 保存订单日志
     */
    private void saveOrderLogs(OrderLog orderLog) {
        List<OrderLogContextHolder.OrderLogInfo> logInfoList = OrderLogContextHolder.getOrderLogInfoList();
        if (logInfoList == null || logInfoList.isEmpty()) {
            log.debug("订单日志信息列表为空，跳过日志记录");
            return;
        }

        for (OrderLogContextHolder.OrderLogInfo logInfo : logInfoList) {
            if (logInfo.getOrderId() == null) {
                log.debug("订单日志信息中订单ID为空，跳过该条日志记录");
                continue;
            }

            try {
                OrderLogEntity orderLogEntity = new OrderLogEntity();
                orderLogEntity.setOrderId(logInfo.getOrderId());
                orderLogEntity.setChildOrderId(logInfo.getChildOrderId());
                orderLogEntity.setUserId(logInfo.getUserId() != null ? logInfo.getUserId() : 0);
                orderLogEntity.setOperateType(logInfo.getOperateType() != null ? logInfo.getOperateType() : orderLog.operateType().getCode());
                orderLogEntity.setMerchantId(logInfo.getMerchantId());

                Map<String, Object> extendMap = ObjectUtil.defaultIfNull(logInfo.getExtendMap(), emptyMap());
                String content = "";
                if (StringUtils.hasText(logInfo.getContent())) {
                    content = StrUtil.format(logInfo.getContent(), extendMap);
                } else {
                    content = StrUtil.format(orderLog.content(), extendMap);
                }
                orderLogEntity.setContent(content);
                orderLogEntity.setUserType(logInfo.getUserType() != null ? logInfo.getUserType() : 1);
                orderLogEntity.setAfterStatus(logInfo.getAfterStatus());
                orderLogEntity.setShippingStatus(logInfo.getShippingStatus() != null ? logInfo.getShippingStatus() : 0);
                orderLogEntity.setCommentStatus(logInfo.getCommentStatus() != null ? logInfo.getCommentStatus() : 0);
                orderLogEntity.setBeforeStatus(logInfo.getBeforeStatus());
                
                orderLogService.save(orderLogEntity);
                log.debug("订单日志记录成功，订单ID: {}", logInfo.getOrderId());
            } catch (Exception e) {
                log.error("保存订单日志失败，订单ID: {}", logInfo.getOrderId(), e);
            }
        }
    }
}