package com.fjhx.sale.service.after.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.sale.entity.after.dto.AfterSalesDto;
import com.fjhx.sale.entity.after.po.AfterSales;
import com.fjhx.sale.entity.after.po.AfterSalesDetail;
import com.fjhx.sale.entity.contract.po.ContractProduct;
import com.fjhx.sale.mapper.after.AfterSalesMapper;
import com.fjhx.sale.service.after.AfterSalesDetailService;
import com.fjhx.sale.service.after.AfterSalesService;
import com.fjhx.sale.service.contract.ContractProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 售后管理 服务实现类
 * </p>
 *
 * @author
 * @since 2023-07-20
 */
@Service
public class AfterSalesServiceImpl extends ServiceImpl<AfterSalesMapper, AfterSales> implements AfterSalesService {
    @Autowired
    private AfterSalesDetailService afterSalesDetailService;

    @Autowired
    private ContractProductService contractProductService;

    @DSTransactional
    @Override
    public void add(AfterSalesDto afterSalesDto) {
        this.save(afterSalesDto);
        List<AfterSalesDetail> afterSalesDetailList = afterSalesDto.getAfterSalesDetailList();
        afterSalesDetailList.forEach(item -> item.setAfterSalesId(afterSalesDto.getId()));
        //赋值单价信息
        List<Long> contractProductIds = afterSalesDetailList.stream().distinct().map(AfterSalesDetail::getContractProductId).collect(Collectors.toList());
        Map<Long, ContractProduct> longContractProductMap = new HashMap<>();
        if (ObjectUtil.isNotEmpty(contractProductIds)) {
            longContractProductMap = contractProductService.mapKEntity(ContractProduct::getId, q -> q.in(ContractProduct::getId, contractProductIds));
        }
        for (AfterSalesDetail afterSalesDetail : afterSalesDetailList) {
            //赋值单价信息
            ContractProduct oldContractProduct = longContractProductMap.get(afterSalesDetail.getContractProductId());
            afterSalesDetail.setPrice(BigDecimal.ZERO);
            if (ObjectUtil.isNotEmpty(oldContractProduct)) {
                afterSalesDetail.setPrice(oldContractProduct.getPrice());
            }
            afterSalesDetail.setAmount(afterSalesDetail.getQuantity().multiply(afterSalesDetail.getPrice()));
        }
        afterSalesDetailService.saveBatch(afterSalesDetailList);
    }

}
