package org.springblade.modules.finance.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.enums.OrderStateEnum;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.modules.finance.entity.Order;
import org.springblade.modules.finance.entity.OrderException;
import org.springblade.modules.finance.mapper.OrderExceptionMapper;
import org.springblade.modules.finance.pay.entity.WxPayV3Bean;
import org.springblade.modules.finance.service.IOrderExceptionService;
import org.springblade.modules.finance.service.IOrderService;
import org.springblade.modules.finance.vo.OrderExceptionVO;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 异常订单表 服务实现类
 *
 * @author BladeX
 * @since 2022-11-15
 */
@Slf4j
@Service
public class OrderExceptionServiceImpl extends ServiceImpl<OrderExceptionMapper, OrderException> implements IOrderExceptionService {

	@Lazy
	@Resource
	private IOrderService orderService;
	@Resource
	private WxPayV3Bean wxPayV3Bean;
	@Resource
	private BladeLogger bladeLogger;
	@Lazy

	@Override
	public IPage<OrderExceptionVO> selectOrderExceptionPage(IPage<OrderExceptionVO> page, OrderExceptionVO orderException) {
		return page.setRecords(baseMapper.selectOrderExceptionPage(page, orderException));
	}

	@Async
	@Override
	public void saveExceptionOrder(Order order, String errMessage, String payCode, Throwable throwable) {
		try {
			if (order != null && order.getId() != null) {
				if (OrderStateEnum.WAIT_PAY.getValue().equals(order.getOrderState())) {
					// 异常订单单独更新订单支付类型，方便查询
					this.updateOrder(order.getId(), payCode);
				}
				OrderException orderException = new OrderException();
				orderException.setErrorMessage(ExceptionUtils.getStackTrace(throwable));
				orderException.setOrderId(order.getId());
				orderException.setIsProcess(0);
				int errorType = 0;
				if (StrUtil.isNotBlank(errMessage)) {
					if (errMessage.contains("创建订单错误10000,请联系管理员")) {
						errorType = 1;//余额不足
					} else if (errMessage.contains("此区域不发货")) {
						errorType = 2;
					}
				}
				orderException.setErrorType(errorType);
				this.save(orderException);
			}
		} catch (Exception e) {
			log.error("保存异常订单信息失败_" + e.getMessage(), e);
		}
	}

	/**
	 * 异常订单单独更新订单支付类型和状态
	 * @param orderId
	 * @param payCode
	 */
	public void updateOrder(Long orderId, String payCode) {
		String settlementAccount = "";
		if (CommonConstant.WX_PAY.equals(payCode)) {
			settlementAccount = wxPayV3Bean.getMchId();
		} else if(CommonConstant.ALI_PAY.equals(payCode)) {
//			settlementAccount = aliService.getPayeeUserId();
		}
		Date currDate = new Date();
		// 异常订单单独更新订单支付类型，方便查询
		orderService.lambdaUpdate().set(Order::getOrderState, OrderStateEnum.WAIT_DELIVERY.getValue())
			.set(Order::getSettlementAccount, settlementAccount)
			.set(Order::getPaymentTime, currDate)
			.set(Order::getUpdateTime, currDate)
			.set(Order::getPaymentMode, payCode).set(Order::getUpdateTime, currDate).eq(Order::getId, orderId).update();
	}

	@Override
	public void replacementOrder(String orderNo, String payCode) {
		Order order = orderService.lambdaQuery().eq(Order::getOrderNo, orderNo).one();
		Assert.notNull(order, "订单数据不存在");
		if (order.getOrderState() > OrderStateEnum.WAIT_DELIVERY.getValue()) {
			throw new ServiceException("当前订单不支持补单");
		}
		orderService.orderPaySuccess(order, payCode);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void reSubmitOrder(String oldOrderNo, String payCode) {

	}
}
