
package com.tmerclub.cloud.supplier.feign;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.tmerclub.cloud.api.supplier.feign.SupplierWalletLogOperationFeignClient;
import com.tmerclub.cloud.common.order.bo.EsOrderBO;
import com.tmerclub.cloud.supplier.constant.SupplierWalletChangeReason;
import com.tmerclub.cloud.supplier.mapper.SupplierWalletMapper;
import com.tmerclub.cloud.supplier.mongo.MongoSupplierWalletLogBO;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author chiley
 * @date 2022/6/30 16:55
 */
@DubboService
public class SupplierWalletLogOperationFeignController implements SupplierWalletLogOperationFeignClient {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private SupplierWalletMapper supplierWalletMapper;


    @Override
    public void deleteSupplierLog(String orderStr) {
        List<EsOrderBO> orderBOList = JSON.parseArray(orderStr, EsOrderBO.class);
        List<Long> orderIds = orderBOList.stream().map(EsOrderBO::getOrderId).collect(Collectors.toList());
        Criteria criteria = Criteria.where("orderId").in(orderIds).and("reason").is(SupplierWalletChangeReason.PAY.value());
        List<MongoSupplierWalletLogBO> mongoSupplierWalletLogBOList = mongoTemplate.find(new Query(criteria), MongoSupplierWalletLogBO.class);
        if (CollUtil.isNotEmpty(mongoSupplierWalletLogBOList)) {
            // 删除记录
            mongoTemplate.remove(new Query(criteria), MongoSupplierWalletLogBO.class);
            // 退还未结算金额-插入记录的时候增加了未结算金额，这里删除时要减去
            for (MongoSupplierWalletLogBO mongoSupplierWalletLogBO : mongoSupplierWalletLogBOList) {
                supplierWalletMapper.subUnsettledAmount(mongoSupplierWalletLogBO.getSupplierId(), mongoSupplierWalletLogBO.getChangeAmount(), mongoSupplierWalletLogBO.getPaySysType());
            }
        }
    }


}
