package com.njzscloud.dispose.wh.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.common.sn.support.SnUtil;
import com.njzscloud.dispose.cst.order.mapper.OrderTransMapper;
import com.njzscloud.dispose.cst.order.mapper.OrderPaymentRecordMapper;
import com.njzscloud.dispose.cst.order.pojo.entity.OrderPaymentRecordEntity;
import com.njzscloud.dispose.cst.order.pojo.result.OrderTransResult;
import com.njzscloud.dispose.wh.constant.PurchaseOrderStatus;
import com.njzscloud.dispose.wh.mapper.PurchaseOrderMapper;
import com.njzscloud.dispose.wh.pojo.entity.PurchaseOrderEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

/**
 * 采购单
 *
 * @author ljw
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PurchaseOrderService extends ServiceImpl<PurchaseOrderMapper, PurchaseOrderEntity> {

    private final OrderTransMapper orderTransMapper;
    private final OrderPaymentRecordMapper orderPaymentRecordMapper;

    /**
     * 新增
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(PurchaseOrderEntity orderEntity) {
        orderEntity.setSn(this.generateSn());
        orderEntity.setPurchaseOrderStatus(PurchaseOrderStatus.JinXingZhong);
        this.save(orderEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(Long transOrderId) {
        OrderTransResult orderTrans = orderTransMapper.getById(transOrderId);
        // 通过transOrderId查询付费记录表，计算settle_money的总和
        BigDecimal totalMoney = orderPaymentRecordMapper.selectList(
                Wrappers.<OrderPaymentRecordEntity>lambdaQuery()
                    .eq(OrderPaymentRecordEntity::getTransId, transOrderId)
            ).stream()
            .map(OrderPaymentRecordEntity::getSettleMoney)
            .filter(Objects::nonNull)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        this.add(BeanUtil.copyProperties(orderTrans, PurchaseOrderEntity.class)
            .setOrderTransId(transOrderId)
            .setSn(this.generateSn())
            .setPurchaseOrderStatus(PurchaseOrderStatus.YiDaoHuo)
            .setPurchaseDate(orderTrans.getOrderTime().toLocalDate())
            .setArrivalDate(LocalDate.now())
            .setQuantity(orderTrans.getEstimatedQuantity())
            .setTotalMoney(totalMoney)
            .setMemo("回收预约单自动添加"));
    }

    /**
     * 修改
     */
    public void modify(PurchaseOrderEntity purchaseOrderEntity) {
        this.updateById(purchaseOrderEntity);
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 详情
     */
    public PurchaseOrderEntity detail(Long id) {
        return this.getById(id);
    }

    /**
     * 分页查询
     */
    public PageResult<PurchaseOrderEntity> paging(PageParam pageParam, PurchaseOrderEntity entity) {
        return PageResult.of(this.page(pageParam.toPage(), Wrappers.query(entity)
            .eq("deleted", Boolean.FALSE)
            .like(StrUtil.isNotBlank(entity.getSn()), "sn", entity.getSn())
            .eq(entity.getPurchaseOrderStatus() != null, "purchase_order_status", entity.getPurchaseOrderStatus())));
    }

    /**
     * 生成订单号
     *
     * @return sn 订单号
     */
    public String generateSn() {
        String sn = SnUtil.next("Purchase-SN");
        if (this.exists(Wrappers.<PurchaseOrderEntity>lambdaQuery().eq(PurchaseOrderEntity::getSn, sn)
            .eq(PurchaseOrderEntity::getDeleted, Boolean.FALSE))) {
            this.generateSn();
        }
        return sn;
    }

}
