package com.yd.dal.service.customer.impl;

import com.yd.dal.entity.customer.AclCustomerFortuneWithdraw;
import com.yd.dal.mapper.customer.AclCustomerFortuneWithdrawMapper;
import com.yd.dal.service.customer.AclCustomerFortuneWithdrawDALService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author xxy
 */
@Service("aclCustomerFortuneWithdrawDALService")
public class AclCustomerFortuneWithdrawDALServiceImpl implements AclCustomerFortuneWithdrawDALService {

    @Autowired
    private AclCustomerFortuneWithdrawMapper customerFortuneWithdrawMapper;

    @Override
    public Map<Long, Long> findFinalWithdrawNoPayByCustomerIds(Set<Long> customerIds, Long payoutBatchId) {
        List<Long> customerIdList = new ArrayList<>(customerIds);
        List<Map<String,Object>> customerWithdrawList = customerFortuneWithdrawMapper.findFinalWithdrawNoPayByCustomerIds(customerIdList, payoutBatchId);
        return changeCustomerWithdrawMap(customerWithdrawList);
    }

    @Override
    public List<AclCustomerFortuneWithdraw> findByIds(List<Long> withdrawUpdateIds) {
        return customerFortuneWithdrawMapper.findByIds(withdrawUpdateIds);
    }

    @Override
    public void updateAll(List<AclCustomerFortuneWithdraw> withdraws) {
        customerFortuneWithdrawMapper.updateBatch(withdraws);
    }

    @Override
    public Map<Long, Long> findFinalWithdrawPayByCustomerIds(Set<Long> customerIds) {
        List<Long> customerIdList = new ArrayList<>(customerIds);
        List<Map<String,Object>> customerWithdrawList = customerFortuneWithdrawMapper.findFinalWithdrawPayByCustomerIds(customerIdList);
        return changeCustomerWithdrawMap(customerWithdrawList);
    }

    @Override
    public Long save(AclCustomerFortuneWithdraw withdraw) {
        return (long) customerFortuneWithdrawMapper.insert(withdraw);
    }

    @Override
    public List<AclCustomerFortuneWithdraw> findByFortuneIds(Long[] fortuneIds) {
        return customerFortuneWithdrawMapper.findByFortuneIds(fortuneIds);
    }

    private Map<Long, Long> changeCustomerWithdrawMap(List<Map<String, Object>> customerWithdrawList) {
        Map<Long, Long> customerWithdrawMap = new HashMap<>(16);
        for (Map<String, Object> customerWithdraw : customerWithdrawList) {
            Long customerId = (Long) customerWithdraw.get("customerId");
            String withdrawIds = (String) customerWithdraw.get("withdrawIds");
            //查询接口中以进行排序,转为数组,取最后一个
            List<String> withdrawList = Arrays.asList(withdrawIds.split(","));
            Long withdrawId = Long.valueOf(withdrawList.get(withdrawList.size()-1));
            customerWithdrawMap.put(customerId,withdrawId);
        }
        return customerWithdrawMap;
    }
}
