package com.ruoyi.web.modules.order.support;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.order.constant.OrderAppConstants;
import com.ruoyi.web.modules.order.constant.OrderConstants;
import com.ruoyi.web.modules.order.domain.BizGoodsReview;
import com.ruoyi.web.modules.order.domain.BizOrder;
import com.ruoyi.web.modules.order.domain.BizOrderItem;
import com.ruoyi.web.modules.order.domain.BizOrderLogisticsTrace;
import com.ruoyi.web.modules.order.mapper.BizOrderAftersaleMapper;
import com.ruoyi.web.modules.order.vo.OrderAppItemSummaryVO;
import com.ruoyi.web.modules.order.vo.OrderAppLogisticsTraceVO;
import com.ruoyi.web.modules.mall.facade.IMallConfigFacade;

/**
 * C 端订单列表/详情辅助
 */
@Component
public class OrderAppSupport
{
    @Autowired
    private BizOrderAftersaleMapper aftersaleMapper;

    @Autowired
    private IMallConfigFacade mallConfigFacade;

    public String toStatusText(String orderStatus)
    {
        if (OrderConstants.STATUS_PENDING_PAY.equals(orderStatus))
        {
            return "待付款";
        }
        if (OrderConstants.STATUS_PENDING_SHIP.equals(orderStatus))
        {
            return "待发货";
        }
        if (OrderConstants.STATUS_SHIPPED.equals(orderStatus))
        {
            return "待收货";
        }
        if (OrderConstants.STATUS_COMPLETED.equals(orderStatus))
        {
            return "交易成功";
        }
        if (OrderConstants.STATUS_CLOSED.equals(orderStatus))
        {
            return "已关闭";
        }
        return toStatusText(orderStatus);
    }

    public String toCloseTypeText(String closeType)
    {
        return dictLabel(OrderConstants.DICT_CLOSE_TYPE, closeType);
    }

    public String toPayTypeText(String payType)
    {
        if (OrderConstants.PAY_TYPE_WECHAT.equals(payType))
        {
            return "微信支付";
        }
        return payType;
    }

    public String resolveReviewStatus(BizOrder order, List<BizOrderItem> items, Map<Long, BizGoodsReview> reviewByItemId)
    {
        if (order == null || !OrderConstants.STATUS_COMPLETED.equals(order.getOrderStatus()))
        {
            return OrderAppConstants.REVIEW_STATUS_NONE;
        }
        if (items == null || items.isEmpty())
        {
            return OrderAppConstants.REVIEW_STATUS_NONE;
        }
        Map<Long, BizGoodsReview> map = reviewByItemId != null ? reviewByItemId : Collections.emptyMap();
        for (BizOrderItem item : items)
        {
            if (!map.containsKey(item.getItemId()))
            {
                return OrderAppConstants.REVIEW_STATUS_PENDING;
            }
        }
        return OrderAppConstants.REVIEW_STATUS_DONE;
    }

    public Map<Long, BizGoodsReview> indexReviewsByItemId(List<BizOrderItem> items, List<BizGoodsReview> reviews)
    {
        Map<Long, BizGoodsReview> map = new HashMap<>();
        if (reviews == null || reviews.isEmpty())
        {
            return map;
        }
        for (BizGoodsReview review : reviews)
        {
            if (review.getOrderItemId() != null)
            {
                map.put(review.getOrderItemId(), review);
            }
        }
        if (items != null && !items.isEmpty())
        {
            for (BizGoodsReview review : reviews)
            {
                if (review.getOrderItemId() == null)
                {
                    map.putIfAbsent(items.get(0).getItemId(), review);
                }
            }
        }
        return map;
    }

    public void enrichItemReview(OrderAppItemSummaryVO vo, BizOrder order, BizOrderItem item,
            Map<Long, BizGoodsReview> reviewByItemId)
    {
        if (vo == null || item == null)
        {
            return;
        }
        if (order == null || !OrderConstants.STATUS_COMPLETED.equals(order.getOrderStatus()))
        {
            vo.setReviewStatus(OrderAppConstants.REVIEW_STATUS_NONE);
            return;
        }
        BizGoodsReview review = reviewByItemId != null ? reviewByItemId.get(item.getItemId()) : null;
        if (review != null)
        {
            vo.setReviewStatus(OrderAppConstants.REVIEW_STATUS_DONE);
            vo.setReviewId(review.getReviewId());
        }
        else
        {
            vo.setReviewStatus(OrderAppConstants.REVIEW_STATUS_PENDING);
        }
    }

    public List<String> resolveActions(BizOrder order)
    {
        if (order == null)
        {
            return Collections.emptyList();
        }
        List<String> actions = new ArrayList<>();
        String status = order.getOrderStatus();
        if (OrderConstants.STATUS_PENDING_PAY.equals(status))
        {
            actions.add(OrderAppConstants.ACTION_PAY);
            return actions;
        }
        if (OrderConstants.STATUS_SHIPPED.equals(status))
        {
            actions.add(OrderAppConstants.ACTION_CONFIRM_RECEIVE);
        }
        if (OrderConstants.STATUS_COMPLETED.equals(status))
        {
            actions.add(OrderAppConstants.ACTION_BUY_AGAIN);
        }
        if (OrderConstants.STATUS_PENDING_SHIP.equals(status)
                || OrderConstants.STATUS_SHIPPED.equals(status))
        {
            actions.add(OrderAppConstants.ACTION_AFTERSALE);
        }
        else if (OrderConstants.STATUS_COMPLETED.equals(status) && !isAftersaleExpired(order))
        {
            actions.add(OrderAppConstants.ACTION_AFTERSALE);
        }
        if (OrderConstants.STATUS_CLOSED.equals(status))
        {
            actions.add(OrderAppConstants.ACTION_BUY_AGAIN);
        }
        return actions;
    }

    /** @deprecated 使用 {@link #resolveActions(BizOrder)}，评价按钮改在商品行展示 */
    @Deprecated
    public List<String> resolveActions(BizOrder order, BizGoodsReview review)
    {
        return resolveActions(order);
    }

    /** @deprecated 使用 {@link #resolveReviewStatus(BizOrder, List, Map)} */
    @Deprecated
    public String resolveReviewStatus(BizOrder order, BizGoodsReview review)
    {
        if (order == null || !OrderConstants.STATUS_COMPLETED.equals(order.getOrderStatus()))
        {
            return OrderAppConstants.REVIEW_STATUS_NONE;
        }
        if (review != null)
        {
            return OrderAppConstants.REVIEW_STATUS_DONE;
        }
        return OrderAppConstants.REVIEW_STATUS_PENDING;
    }

    public Long calcPayRemainSeconds(BizOrder order)
    {
        if (order == null || !OrderConstants.STATUS_PENDING_PAY.equals(order.getOrderStatus())
                || order.getPayExpireTime() == null)
        {
            return null;
        }
        long remainMs = order.getPayExpireTime().getTime() - System.currentTimeMillis();
        return Math.max(0L, remainMs / 1000L);
    }

    public OrderAppItemSummaryVO toItemSummary(BizOrderItem item)
    {
        if (item == null)
        {
            return null;
        }
        OrderAppItemSummaryVO vo = new OrderAppItemSummaryVO();
        vo.setItemId(item.getItemId());
        vo.setGoodsId(item.getGoodsId());
        vo.setGoodsName(item.getGoodsName());
        vo.setGoodsImage(item.getGoodsImage());
        vo.setGoodsSpec(item.getGoodsSpec());
        vo.setQuantity(item.getQuantity());
        vo.setUnitPrice(item.getUnitPrice());
        return vo;
    }

    public OrderAppLogisticsTraceVO toLatestTrace(BizOrderLogisticsTrace trace)
    {
        if (trace == null)
        {
            return null;
        }
        OrderAppLogisticsTraceVO vo = new OrderAppLogisticsTraceVO();
        vo.setTraceType(trace.getTraceType());
        vo.setTraceTime(trace.getTraceTime());
        vo.setContent(trace.getContent());
        return vo;
    }

    public List<String> splitPics(String joined)
    {
        if (StringUtils.isEmpty(joined))
        {
            return new ArrayList<>();
        }
        return new ArrayList<>(Arrays.asList(joined.split(",")));
    }

    public String joinPics(List<String> pics)
    {
        if (pics == null || pics.isEmpty())
        {
            return null;
        }
        return String.join(",", pics);
    }

    public String nextAftersaleNo()
    {
        String prefix = "AS" + new SimpleDateFormat("yyyyMMdd").format(new Date());
        String max = aftersaleMapper.selectMaxAftersaleNoByPrefix(prefix);
        int seq = 1;
        if (StringUtils.isNotEmpty(max) && max.length() > prefix.length())
        {
            try
            {
                seq = Integer.parseInt(max.substring(prefix.length())) + 1;
            }
            catch (NumberFormatException ignored)
            {
                seq = 1;
            }
        }
        return prefix + String.format("%06d", seq);
    }

    public String aftersaleProgressStage(String aftersaleStatus)
    {
        if (OrderAppConstants.AFTERSALE_STATUS_FINISHED.equals(aftersaleStatus))
        {
            return "FINISHED";
        }
        return "MERCHANT_PROCESS";
    }

    public String aftersaleApplyTypeText(String applyType)
    {
        if (OrderAppConstants.AFTERSALE_TYPE_REFUND_UNSHIPPED.equals(applyType))
        {
            return "仅退款-未发货";
        }
        if (OrderAppConstants.AFTERSALE_TYPE_REFUND_SHIPPED.equals(applyType))
        {
            return "仅退款-已发货";
        }
        if (OrderAppConstants.AFTERSALE_TYPE_RETURN_REFUND.equals(applyType))
        {
            return "退货退款";
        }
        return applyType;
    }

    public String aftersaleStatusText(String aftersaleStatus)
    {
        if (OrderAppConstants.AFTERSALE_STATUS_FINISHED.equals(aftersaleStatus))
        {
            return "已完结";
        }
        if (OrderAppConstants.AFTERSALE_STATUS_IN_PROGRESS.equals(aftersaleStatus))
        {
            return "进行中";
        }
        return aftersaleStatus;
    }

    /**
     * 已完成订单是否已超过售后申请期限（自确认收货起算）
     */
    public boolean isAftersaleExpired(BizOrder order)
    {
        if (order == null || !OrderConstants.STATUS_COMPLETED.equals(order.getOrderStatus())
                || order.getFinishTime() == null)
        {
            return false;
        }
        LocalDate finishDate = order.getFinishTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        long days = ChronoUnit.DAYS.between(finishDate, LocalDate.now());
        return days > mallConfigFacade.getAftersaleLimitDays();
    }

    private String dictLabel(String dictType, String value)
    {
        if (StringUtils.isEmpty(value))
        {
            return null;
        }
        try
        {
            return DictUtils.getDictLabel(dictType, value);
        }
        catch (Exception ex)
        {
            return value;
        }
    }
}
