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.ApiAgentTutoringRelationService;
import com.yd.csf.feign.dto.tutor.ApiTutorDTO;
import com.yd.csf.service.model.AgentTutoringRelation;
import com.yd.csf.service.service.IAgentTutoringRelationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApiAgentTutoringRelationServiceImpl implements ApiAgentTutoringRelationService {

    @Resource
    private IAgentTutoringRelationService iAgentTutoringRelationService;

    /**
     * 保存辅导关系列表
     * @param tutorDTOList
     * @param clientUserBizId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveAgentTutoringRelationList(List<ApiTutorDTO> tutorDTOList, String clientUserBizId) {
        //根据用户唯一业务ID删除记录
        iAgentTutoringRelationService.del(clientUserBizId);

        List<String> tutorIdList = tutorDTOList.stream()
                .filter(d -> StringUtils.isNotBlank(d.getClientUserBizId()))
                .map(ApiTutorDTO::getClientUserBizId)
                .collect(Collectors.toList());
        //新增辅导关系列表
        if (CollectionUtils.isEmpty(tutorIdList)) {
            return Result.success();
        }

        List<AgentTutoringRelation> saveList = tutorIdList.stream().map(id -> {
            AgentTutoringRelation relation = new AgentTutoringRelation();
            relation.setAgentId(clientUserBizId);
            relation.setIsActive(1);
            //辅导人ID
            relation.setTutorId(id);
            relation.setTutoringBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_AGENT_TUTORING_RELATION.getCode()));
            return relation;
        }).collect(Collectors.toList());
        iAgentTutoringRelationService.saveOrUpdateBatch(saveList);
        return Result.success();
    }
}
