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

import com.yd.common.enums.CommonEnum;
import com.yd.common.result.Result;
import com.yd.common.utils.RandomStringGenerator;
import com.yd.csf.api.service.ApiAgentReferralRelationService;
import com.yd.csf.feign.request.agentreferralrelation.ApiAgentReferralRelationSaveRequest;
import com.yd.csf.service.model.AgentReferralRelation;
import com.yd.csf.service.service.IAgentReferralRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class ApiAgentReferralRelationServiceImpl implements ApiAgentReferralRelationService {

    @Autowired
    private IAgentReferralRelationService iAgentReferralRelationService;

    /**
     * 保存-推荐关系信息
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result save(ApiAgentReferralRelationSaveRequest request) {
        //先删后新增
        iAgentReferralRelationService.del(request.getAgentIdList(), request.getReferrerId());

        List<AgentReferralRelation> saveList = request.getAgentIdList().stream().map(agentId -> {
            //新增
            AgentReferralRelation relation = new AgentReferralRelation();
            //被推荐人ID
            relation.setAgentId(agentId);
            //推荐人ID（客户端用户表唯一业务ID，如果是PC，这里就是sys_user的用户ID）
            relation.setReferrerId(request.getReferrerId());
            //推荐来源（PC、小程序等，字典，PC就是中台加入申请的）
            relation.setSource(request.getSource());
            //推荐路径(用于快速查询关系链) TODO
//            relation.setReferralPath();
            //推荐关系表唯一业务ID
            relation.setReferralBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_AGENT_REFERRAL_RELATION.getCode()));
            relation.setReferrerAccount(request.getReferrerAccount());
            return relation;
        }).collect(Collectors.toList());

        iAgentReferralRelationService.saveOrUpdateBatch(saveList);
        return Result.success();
    }


}
