package com.crm.ib.task.service.impl;


import com.crm.ib.task.dao.mapper.CustomInfoDao;
import com.crm.ib.task.dao.mapper.TradeCommissionDao;
import com.crm.ib.task.dao.mapper.UserInfoDao;
import com.crm.ib.task.service.CommissionCalcService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.pojo.table.TradeHistoryTable;
import com.crm.rely.backend.model.pojo.table.CustomInfoTable;
import com.crm.rely.backend.model.pojo.table.TradeCommissionTable;
import com.crm.rely.backend.util.ListSplitUtil;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
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.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by max on 2020/7/6.
 */
@SuppressWarnings("SpringJavaAutowiringInspection")
@Service
public class CommissionCalcServiceImpl implements CommissionCalcService {

    /**
     * 学员分享的提直属学员
     * 个人账户交易佣金2$/手
     */
    private final Float agentPoint = 6F;

    /**
     * 学员分享的提直属学员
     * 个人账户交易佣金2$/手
     */
    private final Float salesPoint = 6F;

    @Autowired
    private CustomInfoDao customInfoDao;
    @Autowired
    private TradeCommissionDao tradeCommissionDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void calc(List<TradeHistoryTable> tickets, Integer type) throws Exception {
        if (CollectionUtils.isEmpty(tickets)) {
            return;
        }

        Date now = new Date();
        /*
            计算代理,销售佣金
         */
        Map<Long, Float> balanceMap = Maps.newHashMap();
        List<TradeCommissionTable> commissionTables = Lists.newArrayList();
        for (TradeHistoryTable ticket : tickets) {
            if (null == ticket.getCustomId() || null == ticket.getAgentId()) {
                continue;
            }
            Float volume = ticket.getVolume() == null ? 0F : ticket.getVolume();
            Float amount = balanceMap.get(ticket.getAgentId()) == null ? 0F : balanceMap.get(ticket.getAgentId());
            amount += volume * agentPoint;
            balanceMap.put(ticket.getAgentId(), amount);
            /*
                佣金记录
             */
            TradeCommissionTable commissionTable = new TradeCommissionTable();
            commissionTable.setAmount(volume * agentPoint);
            commissionTable.setSalesCommission(volume * salesPoint);
            commissionTable.setSalesId(ticket.getSalesId());
            commissionTable.setAgentId(ticket.getAgentId());
            commissionTable.setCustomId(ticket.getCustomId());
            commissionTable.setOrder(ticket.getOrder());
            commissionTable.setAddTime(now);
            commissionTables.add(commissionTable);
        }
        /*
            保存佣金记录
         */
        if (!CollectionUtils.isEmpty(commissionTables)) {
            if (commissionTables.size() > Constants.MAX_INSERT_SIZE) {
                List<List<TradeCommissionTable>> lists = ListSplitUtil.split(commissionTables);
                for (List<TradeCommissionTable> list : lists) {
                    tradeCommissionDao.batchSave(list);
                }
            } else {
                tradeCommissionDao.batchSave(commissionTables);
            }
        }


        /*
            佣金更新到客户
         */
        Map<Long, Long> customMap = Maps.newHashMap();
        List<CustomInfoTable> customs = customInfoDao.findAllCustomAgent();
        for (CustomInfoTable custom : customs) {
            customMap.put(custom.getIbId(), custom.getId());
        }
        List<CustomInfoTable> balanceTables = Lists.newArrayList();

        balanceMap.forEach((agentId, amount) -> {
            if (amount != null && customMap.get(agentId) != null) {
                /*
                    客户佣金
                 */
                CustomInfoTable balanceTable = new CustomInfoTable();
                balanceTable.setId(customMap.get(agentId));
                balanceTable.setUsdAmount(BigDecimal.valueOf(amount));
                balanceTables.add(balanceTable);

            }
        });

        if (!CollectionUtils.isEmpty(balanceTables)) {
            if (balanceTables.size() > Constants.MAX_INSERT_SIZE) {
                List<List<CustomInfoTable>> lists = ListSplitUtil.split(balanceTables);
                for (List<CustomInfoTable> list : lists) {
                    customInfoDao.batchUpdateCustomUsdBalance(list);
                }
            } else {
                customInfoDao.batchUpdateCustomUsdBalance(balanceTables);
            }
        }
    }

}
