package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawFirm;
import shop.alien.entity.store.LawFirmPayment;
import shop.alien.entity.store.vo.LawFirmPaymentVO;
import shop.alien.mapper.LawFirmMapper;
import shop.alien.mapper.LawFirmPaymentMapper;
import shop.alien.store.service.StoreLawFirmPaymentService;
import shop.alien.store.service.StoreLawFirmService;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 律所表 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Transactional
@Service
@RequiredArgsConstructor
public class StoreLawFirmServiceImpl extends ServiceImpl<LawFirmMapper, LawFirm> implements StoreLawFirmService {

    private final LawFirmPaymentMapper lawFirmPaymentMapper;
    private final StoreLawFirmPaymentService storeLawFirmPaymentService;

    @Override
    public R<IPage<LawFirm>> getLawFirmList(int pageNum, int pageSize, String firmName, Integer status) {
        log.info("LawFirmServiceImpl.getLawFirmList?pageNum={},pageSize={},firmName={},status={}", pageNum, pageSize, firmName, status);
        Page<LawFirm> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<LawFirm> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawFirm::getDeleteFlag, 0);
        if (StringUtils.hasText(firmName)) {
            queryWrapper.like(LawFirm::getFirmName, firmName);
        }
        if (status != null) {
            queryWrapper.eq(LawFirm::getStatus, status);
        }
        queryWrapper.orderByDesc(LawFirm::getCreatedTime);
        IPage<LawFirm> pageResult = this.page(page, queryWrapper);
        return R.data(pageResult);
    }

    /**
     * 批量填充律所的收款账号列表
     *
     * @param lawFirmList 律所列表
     */
    @Override
    public void fillPaymentList(List<LawFirm> lawFirmList) {
        if (lawFirmList == null || lawFirmList.isEmpty()) {
            return;
        }

        // 收集所有律所ID
        List<Integer> firmIds = lawFirmList.stream()
                .map(LawFirm::getId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        if (firmIds.isEmpty()) {
            return;
        }

        // 批量查询所有收款账号
        LambdaQueryWrapper<LawFirmPayment> paymentWrapper = new LambdaQueryWrapper<>();
        paymentWrapper.in(LawFirmPayment::getFirmId, firmIds);
        paymentWrapper.eq(LawFirmPayment::getDeleteFlag, 0);
        List<LawFirmPayment> allPayments = storeLawFirmPaymentService.list(paymentWrapper);

        // 按律所ID分组
        Map<Integer, List<LawFirmPayment>> paymentMap = allPayments.stream()
                .collect(Collectors.groupingBy(LawFirmPayment::getFirmId));

        // 为每个律所设置收款账号列表
        lawFirmList.forEach(lawFirm -> {
            List<LawFirmPayment> paymentList = paymentMap.getOrDefault(lawFirm.getId(), Collections.emptyList());
            lawFirm.setPaymentList(paymentList);
        });
    }

    @Override
    public R<IPage<LawFirmPaymentVO>> getPaymentPageWithFirm(int pageNum, int pageSize, Integer firmId, String paymentAccount, String firmName, String creditCode, Integer status, Integer certificationStatus, String directorName, String createdTimeStart, String createdTimeEnd) {
        log.info("LawFirmServiceImpl.getPaymentPageWithFirm?pageNum={},pageSize={},firmId={},paymentAccount={},firmName={},creditCode={},status={},certificationStatus={},directorName={},createdTimeStart={},createdTimeEnd={}",
                pageNum, pageSize, firmId, paymentAccount, firmName, creditCode, status, certificationStatus, directorName, createdTimeStart, createdTimeEnd);

        Page<LawFirmPaymentVO> page = new Page<>(pageNum, pageSize);
        IPage<LawFirmPaymentVO> pageResult = lawFirmPaymentMapper.selectPaymentPageWithFirm(
                page, firmId, paymentAccount, firmName, creditCode, status, certificationStatus, directorName, createdTimeStart, createdTimeEnd
        );
        return R.data(pageResult);
    }

}
