package com.yd.csf.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yd.csf.service.dto.QueryPolicyBrokerDto;
import com.yd.csf.service.model.Policy;
import com.yd.csf.service.model.PolicyBroker;
import com.yd.csf.service.service.PolicyBrokerService;
import com.yd.csf.service.dao.PolicyBrokerMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
* @author Zhang Jianan
* @description 针对表【policy_broker(保单转介人表)】的数据库操作Service实现
* @createDate 2025-09-18 15:06:03
*/
@Service
public class PolicyBrokerServiceImpl extends ServiceImpl<PolicyBrokerMapper, PolicyBroker>
    implements PolicyBrokerService{

    /**
     * 查询列表
     * @param dto
     * @return
     */
    @Override
    public List<PolicyBroker> queryList(QueryPolicyBrokerDto dto) {
        List<PolicyBroker> list = baseMapper.selectList(new LambdaQueryWrapper<PolicyBroker>()
                .like(StringUtils.isNotBlank(dto.getBrokerName()),PolicyBroker::getBrokerName,dto.getBrokerName())
                .in(!CollectionUtils.isEmpty(dto.getPolicyNoList()),PolicyBroker::getPolicyNo,dto.getPolicyNoList())
        );
        return list;
    }

    @Override
    public PolicyBroker queryOne(QueryPolicyBrokerDto dto) {
        return this.getOne(new LambdaQueryWrapper<PolicyBroker>()
                .eq(PolicyBroker::getBrokerBizId,dto.getBrokerBizId())
                .eq(PolicyBroker::getPolicyNo,dto.getPolicyNo())
                .last("limit 1")
        );
    }

    @Override
    public void removeByPolicyBizId(String policyBizId) {
        baseMapper.delete(new LambdaQueryWrapper<PolicyBroker>()
                .eq(PolicyBroker::getPolicyBizId, policyBizId)
        );
    }

    @Override
    public List<String> selectRelatedBrokerBizIds(String clientUserId) {
        return baseMapper.selectRelatedBrokerBizIds(clientUserId);
    }

    @Override
    public Map<String, String> queryInternalCodeMap(List<String> brokerBizIdList) {
        if (CollectionUtils.isEmpty(brokerBizIdList)) {
            return Collections.emptyMap();
        }
        List<PolicyBroker> list = baseMapper.selectList(new LambdaQueryWrapper<PolicyBroker>()
                .select(PolicyBroker::getBrokerBizId, PolicyBroker::getInternalCode)  // 只查需要的字段
                .in(PolicyBroker::getBrokerBizId, brokerBizIdList)
                .isNotNull(PolicyBroker::getInternalCode)  // 排除 internalCode 为 null 的记录（可选）
        );
        return list.stream().collect(Collectors.toMap(
                PolicyBroker::getBrokerBizId,
                PolicyBroker::getInternalCode,
                (v1, v2) -> v1  // 如果 brokerBizId 可能重复，保留其中一个
        ));
    }
}




