package com.fjhx.purchase.service.purchase.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.common.utils.Assert;
import com.fjhx.purchase.entity.purchase.dto.PurchasePayRecordDto;
import com.fjhx.purchase.entity.purchase.po.Purchase;
import com.fjhx.purchase.entity.purchase.po.PurchasePayRecord;
import com.fjhx.purchase.entity.purchase.po.PurchasePayRecordDetail;
import com.fjhx.purchase.mapper.purchase.PurchasePayRecordMapper;
import com.fjhx.purchase.service.purchase.PurchasePayRecordDetailService;
import com.fjhx.purchase.service.purchase.PurchasePayRecordService;
import com.fjhx.purchase.service.purchase.PurchaseService;
import com.obs.services.internal.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


/**
 * <p>
 * 采购付款记录 服务实现类
 * </p>
 *
 * @author
 * @since 2023-05-24
 */
@Service
public class PurchasePayRecordServiceImpl extends ServiceImpl<PurchasePayRecordMapper, PurchasePayRecord> implements PurchasePayRecordService {

    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private PurchasePayRecordDetailService purchasePayRecordDetailService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(PurchasePayRecordDto purchasePayRecordDto) {
        //保存付款记录
        this.save(purchasePayRecordDto);

        //创建付款记录
        List<PurchasePayRecordDetail> purchasePayRecordList = purchasePayRecordDto.getPurchasePayRecordDetailList();
        Assert.notEmpty(purchasePayRecordList, "付款列表为空");
        List<Long> purchaseIds = purchasePayRecordList.stream().map(PurchasePayRecordDetail::getPurchaseId).collect(Collectors.toList());

        Map<Long, Purchase> purchaseMap = purchaseService.mapKEntity(Purchase::getId, q -> q.in(Purchase::getId, purchaseIds));
        Map<Long, List<PurchasePayRecordDetail>> PayRecordMap = purchasePayRecordDetailService.mapKGroup(PurchasePayRecordDetail::getPurchaseId,
                q -> q.in(PurchasePayRecordDetail::getPurchaseId, purchaseIds));


        //创建付款明细
        for (PurchasePayRecordDetail payRecord : purchasePayRecordList) {
            //检查付款金额+已付款金额是否大于采购金额
            Purchase purchase = purchaseMap.get(payRecord.getPurchaseId());
            List<PurchasePayRecordDetail> oldPurchasePayRecords = PayRecordMap.get(payRecord.getPurchaseId());
            //求和已付款
            BigDecimal paidAmount = BigDecimal.ZERO;
            if(ObjectUtil.isNotEmpty(oldPurchasePayRecords)){
                paidAmount = oldPurchasePayRecords.stream().map(PurchasePayRecordDetail::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            }
            BigDecimal add = paidAmount.add(payRecord.getAmount());

            if (purchase.getAmount().compareTo(add) < 0) {
                throw new ServiceException("付款金额不能大于采购金额");
            }
            if (purchase.getAmount().compareTo(add) > 0) {
                //部分付款
                purchase.setPayStatus(10);
            } else {
                //完全付款
                purchase.setPayStatus(20);
            }

            //赋值已付款金额
            String victoriatouristJson = purchase.getVictoriatouristJson();
            JSONObject json = ObjectUtil.isEmpty(victoriatouristJson) ? new JSONObject() : JSONObject.parseObject(victoriatouristJson);
            json.put("paidAmount", add);
            purchase.setVictoriatouristJson(JSONObject.toJSONString(json,JSONWriter.Feature.WriteLongAsString));

            purchaseService.updateById(purchase);

            //获取付款记录并赋值付款时间
            payRecord.setPayDate(purchasePayRecordDto.getPayDate());
            payRecord.setPurchasePayRecordId(purchasePayRecordDto.getId());
        }
        purchasePayRecordDetailService.saveBatch(purchasePayRecordList);
    }

}
