package cn.com.poc.user.service.impl;

import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.utils.Assert;
import cn.com.poc.user.constants.Member3rdPartyRelationConstants;
import cn.com.poc.user.convert.Member3rdPartyRelationConvert;
import cn.com.poc.user.entity.Member3rdPartyRelationEntity;
import cn.com.poc.user.model.BizMember3rdPartyRelationModel;
import cn.com.poc.user.repository.BizMember3rdPartyRelationRepository;
import cn.com.poc.user.service.BizMember3rdPartyRelationService;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import cn.com.yict.framemax.core.service.impl.BaseServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BizMember3rdPartyRelationServiceImpl extends BaseServiceImpl
        implements BizMember3rdPartyRelationService {

    @Resource
    private BizMember3rdPartyRelationRepository repository;


    @Override
    public void createOrUpdateRelation(Member3rdPartyRelationEntity member3rdPartyRelationEntity) throws Exception {
        BizMember3rdPartyRelationModel model = new BizMember3rdPartyRelationModel();
        if (member3rdPartyRelationEntity.getId() != null) {
            BizMember3rdPartyRelationModel bizMember3rdPartyRelationModel = repository.get(member3rdPartyRelationEntity.getId());
            if (bizMember3rdPartyRelationModel == null) {
                throw new I18nMessageException("exception/unable.find.user.association.relationship");
            }
            model = bizMember3rdPartyRelationModel;
            model.setRelationKey(member3rdPartyRelationEntity.getRelationKey());
        } else {
            model.setMemberId(member3rdPartyRelationEntity.getMemberId());
            model.setRelationKey(member3rdPartyRelationEntity.getRelationKey());
            model.setRelationPlatform(member3rdPartyRelationEntity.getRelationPlatform());
        }
        repository.save(model);
    }

    /**
     * @param memberId
     * @return
     * @throws Exception
     */
    @Override
    public Member3rdPartyRelationEntity getPwRelationByMemberId(Integer memberId) throws Exception {
        Assert.notNull(memberId);
        BizMember3rdPartyRelationModel example = new BizMember3rdPartyRelationModel();
        example.setMemberId(memberId);
        example.setRelationPlatform(Member3rdPartyRelationConstants.RelationType.PW);
        example.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizMember3rdPartyRelationModel> bizMember3rdPartyRelationModelList = repository.findByExample(example);
        if (CollectionUtils.isEmpty(bizMember3rdPartyRelationModelList)) {
            return null;
        }
        return Member3rdPartyRelationConvert.convertModel2Entity(bizMember3rdPartyRelationModelList.get(0));
    }
}