package cn.newfeifan.mall.module.distri.service.shopsettlement;

import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;
import cn.newfeifan.mall.module.distri.constant.DistriConstants;
import cn.newfeifan.mall.module.distri.controller.admin.shopsettlement.vo.ShopSettlementPageReqVO;
import cn.newfeifan.mall.module.distri.controller.admin.shopsettlement.vo.ShopSettlementRespVO;
import cn.newfeifan.mall.module.distri.controller.admin.shopsettlement.vo.ShopSettlementSaveReqVO;
import cn.newfeifan.mall.module.distri.dal.dataobject.shopsettlement.ShopSettlementDO;
import cn.newfeifan.mall.module.distri.dal.mysql.shopsettlement.ShopSettlementMapper;
import cn.newfeifan.mall.module.system.controller.admin.user.vo.user.UserShopDetailsVO;
import cn.newfeifan.mall.module.system.service.user.AdminUserService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.module.distri.enums.ErrorCodeConstants.SHOP_SETTLEMENT_NOT_EXISTS;

/**
 * 订单结算信息表，记录店铺的结算信息 Service 实现类
 *
 * @author 非繁人
 */
@Service
@Validated
public class ShopSettlementServiceImpl implements ShopSettlementService {

    @Resource
    private ShopSettlementMapper shopSettlementMapper;

    @Resource
    private AdminUserService userService;

    @Override
    public Long createShopSettlement(ShopSettlementSaveReqVO createReqVO) {
        // 插入
        ShopSettlementDO shopSettlement = BeanUtils.toBean(createReqVO, ShopSettlementDO.class);
        shopSettlementMapper.insert(shopSettlement);
        // 返回
        return shopSettlement.getId();
    }

    @Override
    public void updateShopSettlement(ShopSettlementSaveReqVO updateReqVO) {
        // 校验存在
        validateShopSettlementExists(updateReqVO.getId());
        // 更新
        ShopSettlementDO updateObj = BeanUtils.toBean(updateReqVO, ShopSettlementDO.class);
        shopSettlementMapper.updateById(updateObj);
    }

    @Override
    public void deleteShopSettlement(Long id) {
        // 校验存在
        validateShopSettlementExists(id);
        // 删除
        shopSettlementMapper.deleteById(id);
    }

    private void validateShopSettlementExists(Long id) {
        if (shopSettlementMapper.selectById(id) == null) {
            throw exception(SHOP_SETTLEMENT_NOT_EXISTS);
        }
    }

    @Override
    public ShopSettlementDO getShopSettlement(Long id) {
        return shopSettlementMapper.selectById(id);
    }

    @Override
    public PageResult<ShopSettlementRespVO> getShopSettlementPage(ShopSettlementPageReqVO pageReqVO) {

        UserShopDetailsVO userShopDetails = userService.getUserShopDetails();

        pageReqVO.setMerchantId(userShopDetails.getMerId());
        pageReqVO.setShopId(userShopDetails.getShopId());

        PageResult<ShopSettlementDO> shopSettlementDOPageResult = shopSettlementMapper.selectPage(pageReqVO);
        PageResult<ShopSettlementRespVO> result = BeanUtils.toBean(shopSettlementDOPageResult, ShopSettlementRespVO.class);
        for (ShopSettlementRespVO shopSettlementRespVO : result.getList()) {
            shopSettlementRespVO.setShopName(shopSettlementMapper.getShopName(shopSettlementRespVO.getShopId()));
            shopSettlementRespVO.setCreateTime(shopSettlementRespVO.getCreateTime().minusDays(1));
        }
        return result;
    }

    /**
     * 把数据库的积分转换为数据库的钱
     *
     * @param integral 积分
     * @return 钱
     */
    public static Integer integral2Money(Long integral) {
        Long l = (integral / DistriConstants.MONEY2INTEGRAL);
        return l.intValue();
    }

//    @Override
//    public void settlementOrder() {
//        //先获取所用的商户，再获取旗下的店铺，再获取店铺的订单，再计算
//        List<MerchantDTO> merchantDTOS = dailyBillMapper.getMerchantDTO();
//
//        // 订单项ids
//        Map<Long, List<Long>> shopOrderIds = new HashMap<>();
//        Map<Long, List<Long>> shopOrderItemIds = new HashMap<>();
//        List<ShopSettlementDO> shopSettlementDOS = new ArrayList<>();
//
//        Integer ptPlatformCollectionAmount = 0;
//        // 代收积分
//        Long ptPayIntegral = 0L;
//        // 店铺应得金额（成本 * 数量）
//        Integer ptShopAmount = 0;
//        BigDecimal ptShopHighAmount = BigDecimal.ZERO;
//
//        for (MerchantDTO merchant : merchantDTOS) {
//            for (Long shopId : merchant.getShopIds()) {
//                List<OrderDTO> orders = shopSettlementMapper.getOrderByMerchantIdWithsShopId(shopId, merchant.getMerchantId());
//                // 当前店铺没有订单，则跳过
//                if (orders.isEmpty()) {
//                    continue;
//                }
//
//                List<Long> orderIds = new ArrayList<>();
//                List<Long> orderItemIds = new ArrayList<>();
//
//                // pt代收金额
//                Integer platformCollectionAmount = 0;
//                // 代收积分
//                Long payIntegral = 0L;
//                // 店铺应得金额（成本 * 数量）
//                Integer shopAmount = 0;
//                BigDecimal shopHighAmount = BigDecimal.ZERO;
//
//                //获取该店铺下的订单
//                for (OrderDTO order : orders) {
//                    // 获取所有的订单id
//                    orderIds.add(order.getId());
//                    for (OrderItemDTO item : order.getItems()) {
//
//                        if(order.getId() == 246){
//                            System.out.println("1");
//                        }
//
//                        //拿到该店铺下的所有订单项id
//                        orderItemIds.add(item.getId());
//                        //计算订单的收入金额(pt)
//                        platformCollectionAmount += item.getPayRmb();
//                        ptPlatformCollectionAmount += item.getPayRmb();
//                        //计算订单的收入积分（pt）
//                        payIntegral += item.getPayIntegral();
//                        ptPayIntegral += item.getPayIntegral();
//                        // 商品的成本价（成本 * 数量）
//                        shopAmount += item.getCostPrice() * item.getCount();
//                        ptShopAmount += item.getCostPrice() * item.getCount();
//                        // 商品的高精度成本价（成本 * 数量）
//                        shopHighAmount = shopHighAmount.add(BigDecimal.valueOf(item.getHighPrecisionPrice().doubleValue() * item.getCount()));
//                        ptShopHighAmount = ptShopHighAmount.add(BigDecimal.valueOf(item.getHighPrecisionPrice().doubleValue() * item.getCount()));
//
//                    }
//                }
//
//                shopOrderIds.put(shopId, orderIds);
//                shopOrderItemIds.put(shopId, orderItemIds);
//
//                /*
//                  积分也是pt代收
//                  积分要转换才能变为钱
//                 */
//                platformCollectionAmount += integral2Money(payIntegral);
//
//
//                // 店铺共计成本金额
//                BigDecimal totalHighAmount = shopHighAmount.add(BigDecimal.valueOf(shopAmount));
//
//                // 插入店铺结算信息
//                ShopSettlementDO shopSett = ShopSettlementDO.builder()
//                        .shopId(shopId)
//                        .merchantId(merchant.getMerchantId())
//                        .platformCollectionAmount(platformCollectionAmount)
//                        .shopAmount(payIntegral)
//                        .shopTotalHighAmount(totalHighAmount.setScale(6, RoundingMode.HALF_UP))
//                        .build();
//                shopSettlementDOS.add(shopSett);
//            }
//        }
//
//        ptPlatformCollectionAmount += integral2Money(ptPayIntegral);
//        // 平台共计成本金额
//        BigDecimal totalHighAmount = ptShopHighAmount.add(BigDecimal.valueOf(ptShopAmount));
//
//        // 平台每日记录
//        PtSettlementDO ptSettlementDO = PtSettlementDO.builder()
//                .platformCollectionAmount(ptPlatformCollectionAmount)
//                .shopAmount(ptPayIntegral)
//                .shopTotalHighAmount(totalHighAmount.setScale(6, RoundingMode.HALF_UP))
//                .build();
//        ptSettlementMapper.insert(ptSettlementDO);
//
//        shopSettlementDOS.forEach(shopSett -> {
//            shopSett.setPtSettlementId(ptSettlementDO.getId());
//            shopSettlementMapper.insert(shopSett);
//
//            // 插入订单结算信息（订单二级）
//            List<Long> orderIds = shopOrderIds.get(shopSett.getShopId());
//            orderIds.forEach(orderId -> {
//                orderSettlementMapper.insert(OrderSettlementDO.builder()
//                        .tradeShopSettlementId(shopSett.getId())
//                        .tradeOrderId(orderId)
//                        .build());
//            });
//
//            // 插入订单项结算信息（订单项二级）
//            List<Long> orderItemIds = shopOrderItemIds.get(shopSett.getShopId());
//            orderItemIds.forEach(orderItemId -> {
//                orderItemSettlementMapper.insert(OrderItemSettlementDO.builder()
//                        .tradeShopSettlementId(shopSett.getId())
//                        .tradeOrderItemId(orderItemId)
//                        .build());
//            });
//            // 更新订单项的结算时间
//            shopSettlementMapper.setOrderItemById(orderItemIds);
//        });
//
//    }
}