package com.hzs.ground.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.SaOrderFieldConstants;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.enums.EOrderStatus;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.domain.sale.order.SaOrderItems;
import com.hzs.ground.order.mapper.SupplierOrderMapper;
import com.hzs.ground.order.param.OrderItemsParam;
import com.hzs.ground.order.param.OrderQueryParam;
import com.hzs.ground.order.service.ISaOrderSettleService;
import com.hzs.ground.order.service.ISupplierOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * @description: 供应商查询订单
 * @author: sui q
 * @time: 2024/3/23 13:59
 * @classname: SupplierOrderServiceImpl
 * @package_name: com.hzs.ground.order.service.impl
 * version 1.0.0
 */
@Service
public class SupplierOrderServiceImpl extends ServiceImpl<SupplierOrderMapper, SaOrderItems> implements ISupplierOrderService {

    @Autowired
    private ISaOrderSettleService saOrderSettleService;

    @Override
    public List<SaOrderExt> querySaOrderByCondition(OrderQueryParam orderQueryParam) {
        if (orderQueryParam.getEndTime() != null) {
            orderQueryParam.setEndTime(DateUtils.afterDate(1, ChronoUnit.DAYS, orderQueryParam.getEndTime()));
        }
        return baseMapper.querySaOrderByCondition(orderQueryParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendGood(OrderQueryParam orderQueryParam , List<OrderItemsParam> orderItemsParamList, List<SaOrderExt> orderList) {
        for (OrderItemsParam orderItemsParam : orderItemsParamList) {
            UpdateWrapper<SaOrderItems> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(SystemFieldConstants.PK_ID, orderItemsParam.getPkId());
            updateWrapper.eq(SaOrderFieldConstants.ORDER_STATUS, EOrderStatus.PAY.getValue());
            updateWrapper.set("LOGISTICS_CODE", orderItemsParam.getLogisticsCode());
            updateWrapper.set("LOGISTICS_COMPANY", orderItemsParam.getLogisticsCompany());
            updateWrapper.set(SaOrderFieldConstants.ORDER_STATUS, EOrderStatus.DELIVERED.getValue());
            update(updateWrapper);
        }
        // 发货完成自动生成待结算单据
        saOrderSettleService.saveOrderSettleByOrder(orderQueryParam, orderList);
    }
}
