package com.younike.system.service.impl;

import com.younike.common.core.domain.AjaxResult;
import com.younike.common.exception.ServiceException;
import com.younike.system.domain.PersonalMerchantSettle;
import com.younike.system.domain.PersonalMerchantSettleResource;
import com.younike.system.domain.vo.PersonalMerchantSettleAmountVO;
import com.younike.system.domain.vo.PersonalMerchantSettleVO;
import com.younike.system.enums.PersonalSettleStatusEnum;
import com.younike.system.mapper.PersonalMerchantSettleMapper;
import com.younike.system.mapper.PersonalMerchantSettleResourceMapper;
import com.younike.system.param.PersonalMerchantOrderSettleParam;
import com.younike.system.param.PersonalMerchantSettleQueryParam;
import com.younike.system.service.IPersonalMerchantSettleService;
import org.apache.commons.collections4.CollectionUtils;
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.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 个体户账单结算Service实现类
 * @Author dail
 * @Date 2022/3/3
 */
@Service
public class PersonalMerchantSettleServiceImpl implements IPersonalMerchantSettleService {

    @Autowired
    private PersonalMerchantSettleMapper personalMerchantSettleMapper;

    @Autowired
    private PersonalMerchantSettleResourceMapper personalMerchantSettleResourceMapper;



    /**
     * 个体户账单结算分页列表
     *
     * @param queryParam
     * @return
     */
    @Override
    public List<PersonalMerchantSettleVO> listPersonalMerchantSettle(PersonalMerchantSettleQueryParam queryParam) {
        List<PersonalMerchantSettleVO> personalMerchantSettleVOList = personalMerchantSettleMapper.listPersonalMerchantSettle(queryParam);
        if (CollectionUtils.isNotEmpty(personalMerchantSettleVOList)) {
            // 处理结算状态名称
            for (PersonalMerchantSettleVO personalMerchantSettleVO : personalMerchantSettleVOList) {
                personalMerchantSettleVO.setSettleStatusName(PersonalSettleStatusEnum.getDescription(personalMerchantSettleVO.getSettleStatus()));
            }
        }
        return personalMerchantSettleVOList;
    }

    /**
     * 个体户账单结算金额信息
     *
     * @return
     */
    @Override
    public PersonalMerchantSettleAmountVO getPersonalMerchantSettleAmountInfo() {
        PersonalMerchantSettleAmountVO personalMerchantSettleAmountVO = new PersonalMerchantSettleAmountVO();
        // 查询结算信息列表
        List<PersonalMerchantSettle> personalMerchantSettleList = personalMerchantSettleMapper.selectPersonalMerchantSettleList(new PersonalMerchantSettle());
        if (CollectionUtils.isNotEmpty(personalMerchantSettleList)) {
            // 统计待结算金额
            BigDecimal pendingSettlementAmount = personalMerchantSettleList.stream()
                    .filter(item -> (PersonalSettleStatusEnum.PENDING_SETTLEMENT.getCode().equals(item.getSettleStatus()) && item.getActualIncome() != null))
                    .map(item -> item.getActualIncome())
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            personalMerchantSettleAmountVO.setPendingSettlementAmount(pendingSettlementAmount);
            // 统计已支付金额
            BigDecimal paidAmount = personalMerchantSettleList.stream()
                    .filter(item -> (PersonalSettleStatusEnum.PAID.getCode().equals(item.getSettleStatus()) && item.getActualIncome() != null))
                    .map(item -> item.getActualIncome())
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            personalMerchantSettleAmountVO.setPaidAmount(paidAmount);
        } else {
            personalMerchantSettleAmountVO.setPendingSettlementAmount(BigDecimal.ZERO);
            personalMerchantSettleAmountVO.setPaidAmount(BigDecimal.ZERO);
        }
        return personalMerchantSettleAmountVO;
    }

    /**
     * 个体户账单结算接口
     *
     * @param orderSettleParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult settlePersonalMerchantOrder(PersonalMerchantOrderSettleParam orderSettleParam) {
        // 校验结算列表是否属于同一个商家
        List<PersonalMerchantSettle> personalMerchantSettleList = orderSettleParam.getPersonalMerchantSettleList();
        // 获取结算商家id列表
        List<Long> merchantIdList = personalMerchantSettleList.stream()
                .filter(item -> !Objects.isNull(item))
                .map(PersonalMerchantSettle::getMerchantId)
                .distinct()
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(merchantIdList) && merchantIdList.size() > 1) {
            return AjaxResult.error("批量结算只能选择同一个个体户账单信息！");
        }
        // 获取结算信息id列表
        List<Long> personalMerchantSettleIdList = personalMerchantSettleList.stream()
                .filter(item -> !Objects.isNull(item))
                .map(PersonalMerchantSettle::getPersonalMerchantSettleId)
                .distinct()
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(personalMerchantSettleIdList)) {
            return AjaxResult.error("个体户账单结算列表不能为空！");
        }

        // 处理数据
        List<PersonalMerchantSettleResource> settleResourceList = new ArrayList<>();
        for (PersonalMerchantSettle personalMerchantSettle : personalMerchantSettleList) {
            // 更新结算状态为已支付
            personalMerchantSettle.setSettleStatus(PersonalSettleStatusEnum.PAID.getCode());

            // 拆分资源url
            if (orderSettleParam.getResourceUrl().contains(",")) {
                String[] split = orderSettleParam.getResourceUrl().split(",");
                List<String> resourceUrlList = Arrays.asList(split);
                // 构建结算资源对象列表
                for (String resourceUrl : resourceUrlList) {
                    PersonalMerchantSettleResource settleResource = new PersonalMerchantSettleResource();
                    settleResource.setPersonalSettleId(personalMerchantSettle.getPersonalMerchantSettleId());
                    settleResource.setResourceUrl(resourceUrl);
                    settleResourceList.add(settleResource);
                }
            } else {
                // 构建结算资源对象列表
                PersonalMerchantSettleResource settleResource = new PersonalMerchantSettleResource();
                settleResource.setPersonalSettleId(personalMerchantSettle.getPersonalMerchantSettleId());
                settleResource.setResourceUrl(orderSettleParam.getResourceUrl());
                settleResourceList.add(settleResource);
            }
        }

        // 批量更新个体户账单结算信息
        int updateBatchById = personalMerchantSettleMapper.updateBatchById(personalMerchantSettleList);
        if (updateBatchById <= 0) {
            throw new ServiceException("结算操作失败!");
        }

        // 批量新增结算资源
        if (CollectionUtils.isNotEmpty(settleResourceList)) {
            int insertBatch = personalMerchantSettleResourceMapper.insertBatch(settleResourceList);
            if (insertBatch <= 0) {
                throw new ServiceException("结算操作失败!");
            }
        }

        return AjaxResult.success();
    }

    /**
     * 个体户账单结算资源
     *
     * @param personalMerchantSettleId
     * @return
     */
    @Override
    public AjaxResult getPersonalSettleResource(Long personalMerchantSettleId) {
        return AjaxResult.success(personalMerchantSettleResourceMapper.selectPersonalMerchantSettleResourceList(personalMerchantSettleId));
    }

    /**
     * 根据年月和商家id查询个体户账单结算记录
     *
     * @param merchantId
     * @param yearMonth
     * @return
     */
    @Override
    public PersonalMerchantSettle getByMerchantIdAndYearMonth(Long merchantId, String yearMonth) {
        return personalMerchantSettleMapper.getByMerchantIdAndYearMonth(merchantId, yearMonth);
    }

    /**
     * 批量更新个体户账单结算记录
     *
     * @param personalMerchantSettleList
     * @return
     */
    @Override
    public int updateBatchById(List<PersonalMerchantSettle> personalMerchantSettleList) {
        return personalMerchantSettleMapper.updateBatchById(personalMerchantSettleList);
    }

    /**
     * 批量新增个体户账单结算记录
     *
     * @param personalMerchantSettleList
     * @return
     */
    @Override
    public int saveBatch(List<PersonalMerchantSettle> personalMerchantSettleList) {
        return personalMerchantSettleMapper.saveBatch(personalMerchantSettleList);
    }
}
