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

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springblade.common.enums.YesOrNoEnum;
import org.springblade.modules.api.request.SubmitOrderRequest;
import org.springblade.modules.api.service.SubmitOrderService;
import org.springblade.modules.business.entity.FacilityCargoWay;
import org.springblade.modules.business.entity.Shop;
import org.springblade.modules.business.service.IFacilityCargoWayService;
import org.springblade.modules.business.service.IShopService;
import org.springblade.modules.finance.entity.AfterSales;
import org.springblade.modules.finance.entity.Order;
import org.springblade.modules.finance.entity.OrderGoods;
import org.springblade.modules.finance.mapper.OrderGoodsMapper;
import org.springblade.modules.finance.service.IAfterSalesService;
import org.springblade.modules.finance.service.IOrderGoodsService;
import org.springblade.modules.finance.service.IOrderService;
import org.springblade.modules.finance.vo.MerchantPageOrderVO;
import org.springblade.modules.finance.vo.OrderGoodsVO;
import org.springblade.modules.mall.entity.GoodsInfo;
import org.springblade.modules.mall.service.IGoodsInfoService;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 商品订单表 服务实现类
 *
 * @author BladeX
 * @since 2024-07-17
 */
@AllArgsConstructor
@Service("orderGoodsServiceImpl")
public class OrderGoodsServiceImpl extends ServiceImpl<OrderGoodsMapper, OrderGoods> implements IOrderGoodsService, SubmitOrderService {

	private final IOrderService iOrderService;
	private final IGoodsInfoService iGoodsInfoService;
	private final IFacilityCargoWayService iFacilityCargoWayService;
	private final IShopService iShopService;
	private final IUserService iUserService;
	private final IAfterSalesService afterSalesService;

	@Override
	public IPage<OrderGoodsVO> selectOrderGoodsPage(IPage<OrderGoodsVO> page, OrderGoodsVO orderGoods) {
		return page.setRecords(baseMapper.selectOrderGoodsPage(page, orderGoods));
	}

	@Override
	public IPage<OrderGoodsVO> selectUserOrder(IPage<OrderGoodsVO> page, OrderGoodsVO orderGoods) {
		List<OrderGoodsVO> orderGoodsVOS = baseMapper.selectUserOrder(page, orderGoods);
		for (OrderGoodsVO order : orderGoodsVOS) {
			if (YesOrNoEnum.YES.getValue().equals(order.getIsAfterSales())){
				LambdaQueryWrapper<AfterSales> q = new LambdaQueryWrapper<>();
				q.eq(AfterSales::getOrderId,order.getOrderId());
				AfterSales afterSales = afterSalesService.getOne(q);
				order.setAfterSales(afterSales);
			}
		}
		return page.setRecords(orderGoodsVOS);
	}

	@Override
	public IPage<MerchantPageOrderVO> getMerchantOrder(IPage page, MerchantPageOrderVO merchantPageOrderVO){
		return page.setRecords(baseMapper.getMerchantOrder(page, merchantPageOrderVO));
	}

	@Override
	public String getMerchantOrderNum(Long merchantId){
		return baseMapper.getMerchantOrderNum(merchantId);
	}

	@Transactional
	@Override
	public String submitOrder(SubmitOrderRequest request) {
		GoodsInfo goods = iGoodsInfoService.getById(request.getGoodsInfoId());
		Assert.notNull(goods, "商品信息不存在");
		FacilityCargoWay cargoWay = iFacilityCargoWayService.getById(request.getCargoWayId());
		Assert.notNull(cargoWay, "货道信息不存在");
		Shop shop = iShopService.getById(request.getShopId());
		Assert.notNull(shop, "门店信息不存在");
		User user = iUserService.getById(request.getUserId());

		// 订单初始化
		Order order = iOrderService.init();
		order.setOrderType(request.getOrderType());
		order.setOrderType(request.getOrderType());
		order.setSource(request.getOrderSource());
		order.setUserId(request.getUserId());
		// 订单总金额
		order.setTotalAmount(cargoWay.getSalePrice().multiply(BigDecimal.valueOf(request.getGoodsNum())));
		order.setDiscountAmount(BigDecimal.valueOf(cargoWay.getDiscount()).multiply(BigDecimal.valueOf(request.getGoodsNum())));
		// 实付金额
		order.setPaymentAmount(order.getTotalAmount().subtract(order.getDiscountAmount()));
		order.setConsignee(user.getName());
		order.setConsigneePhoneNumber(user.getPhone());
		order.setImage(goods.getGoodsCover());
		iOrderService.save(order);

		OrderGoods orderGoods = new OrderGoods();
		orderGoods.setOrderId(order.getId());
		orderGoods.setGoodsNum(request.getGoodsNum());
		orderGoods.setShipmentNum(0);
		orderGoods.setDeviceId(request.getDeviceId());
		orderGoods.setGoodsName(goods.getGoodsName());
		orderGoods.setCargoWayId(request.getCargoWayId());
		orderGoods.setCargoWayNo(request.getCargoWayNo());
		//orderGoods.setShippingTime(LocalDateTime.now());
		orderGoods.setGoodsNo(goods.getGoodsNo());
		orderGoods.setGoodsImage(goods.getGoodsCover());
		orderGoods.setGoodsId(request.getGoodsInfoId());
		orderGoods.setGoodsPrice(cargoWay.getSalePrice().subtract(BigDecimal.valueOf(cargoWay.getDiscount())));
		orderGoods.setMerchantId(shop.getMerchantId());
		orderGoods.setShopId(request.getShopId());
		orderGoods.setUserId(request.getUserId());
		orderGoods.setStoreName(shop.getStoreName());
		baseMapper.insert(orderGoods);

		// 扣减货道库存
		cargoWay.setGoodsStore(cargoWay.getGoodsStore() - request.getGoodsNum());
		iFacilityCargoWayService.updateById(cargoWay);
		return order.getOrderNo();
	}


	@Override
	public void releaseGoodsStock(Order order) {
		OrderGoods orderGoods = baseMapper.selectOne(Wrappers.lambdaQuery(OrderGoods.class).eq(OrderGoods::getOrderId, order.getId()));
		// 更新货道库存
		FacilityCargoWay cargoWay = iFacilityCargoWayService.getById(orderGoods.getCargoWayId());
		cargoWay.setGoodsStore(cargoWay.getGoodsStore() + orderGoods.getGoodsNum());
		iFacilityCargoWayService.updateById(cargoWay);
	}

	@Override
	public void paySuccessAfter(Order order) {
		OrderGoods orderGoods = baseMapper.selectOne(Wrappers.lambdaQuery(OrderGoods.class).eq(OrderGoods::getOrderId, order.getId()));
		// 更新货道销售信息
		FacilityCargoWay cargoWay = iFacilityCargoWayService.getById(orderGoods.getCargoWayId());
		cargoWay.setTotalTrade(cargoWay.getTotalTrade() + orderGoods.getGoodsNum());
		cargoWay.setTotalAmount(cargoWay.getTotalAmount().add(order.getPaymentAmount()));
		iFacilityCargoWayService.updateById(cargoWay);
	}

    public List<OrderGoods> getMerchantOrder(Long userId, Date startDate, Date endDate){
       return this.lambdaQuery()
               .eq(OrderGoods::getMerchantId,userId)
               .eq(OrderGoods::getIsDelete,0)
               .between(OrderGoods::getCreateTime,startDate,endDate)
               .list();
    }

}
