package com.ruoyi.web.modules.order.service.impl;

import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.account.facade.IMemberFacade;
import com.ruoyi.web.modules.finance.service.IShopFundService;
import com.ruoyi.web.modules.order.constant.OrderAppConstants;
import com.ruoyi.web.modules.order.constant.OrderConstants;
import com.ruoyi.web.modules.order.domain.BizOrder;
import com.ruoyi.web.modules.order.domain.BizOrderLogisticsTrace;
import com.ruoyi.web.modules.order.mapper.BizOrderLogisticsTraceMapper;
import com.ruoyi.web.modules.order.mapper.BizOrderMapper;
import com.ruoyi.web.modules.order.service.IOrderCompletionService;

/**
 * 订单确认收货完结
 */
@Service
public class OrderCompletionServiceImpl implements IOrderCompletionService
{
    @Autowired
    private BizOrderMapper orderMapper;

    @Autowired
    private BizOrderLogisticsTraceMapper traceMapper;

    @Autowired
    private IShopFundService shopFundService;

    @Autowired
    private IMemberFacade memberFacade;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void completeOrder(BizOrder order, Date finishTime, String operator, String traceContent)
    {
        if (order == null || order.getOrderId() == null || order.getMemberId() == null)
        {
            throw new ServiceException("订单不存在");
        }
        if (!OrderConstants.STATUS_SHIPPED.equals(order.getOrderStatus()))
        {
            throw new ServiceException(OrderAppConstants.MSG_CANNOT_CONFIRM_RECEIVE);
        }
        int rows = orderMapper.updateForConfirmReceive(order.getOrderId(), order.getMemberId(), finishTime);
        if (rows == 0)
        {
            throw new ServiceException(OrderAppConstants.MSG_CONFIRM_RECEIVE_STATE_CHANGED);
        }
        BizOrderLogisticsTrace trace = new BizOrderLogisticsTrace();
        trace.setOrderId(order.getOrderId());
        trace.setTraceType(OrderConstants.TRACE_CONFIRM);
        trace.setTraceTime(finishTime);
        trace.setContent(traceContent);
        trace.setCreateBy(operator);
        traceMapper.insertTrace(trace);
        order.setOrderStatus(OrderConstants.STATUS_COMPLETED);
        order.setFinishTime(finishTime);
        shopFundService.settleOrder(order);
        memberFacade.refreshConsumption(order.getMemberId());
    }
}
