
package com.tmerclub.cloud.auth.service.impl;

import com.tmerclub.cloud.api.auth.bo.UidInfoBO;
import com.tmerclub.cloud.api.payment.allinpay.member.resp.PersonalMemberInfo;
import com.tmerclub.cloud.api.payment.constant.PaySysType;
import com.tmerclub.cloud.api.payment.feign.AllinpayFeignClient;
import com.tmerclub.cloud.api.platform.feign.ConfigFeignClient;
import com.tmerclub.cloud.auth.mapper.AuthSocialMapper;
import com.tmerclub.cloud.auth.model.AuthSocial;
import com.tmerclub.cloud.auth.service.AuthSocialService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author tmerclub
 * @date 2020/7/2
 */
@Service
public class AuthSocialServiceImpl implements AuthSocialService {

    @Autowired
    private AuthSocialMapper authSocialMapper;

    @DubboReference
    private ConfigFeignClient configFeignClient;

    @DubboReference
    private AllinpayFeignClient allinpayFeignClient;

    @Override
    public AuthSocial getByBizUserId(String bizUserId, Integer socialType) {
        return authSocialMapper.getByBizUserIdAndType(bizUserId, socialType);
    }

    @Override
    public void saveOrUpdate(AuthSocial authSocial) {
        if (authSocial.getId() == null) {
            authSocialMapper.save(authSocial);
        } else {
            authSocialMapper.update(authSocial);
        }
    }

    @Override
    public AuthSocial getByTempUid(String tempUid) {
        return authSocialMapper.getByTempUid(tempUid);
    }

    @Override
    public int countByUidAndSocialType(Long uid, Integer socialType) {
        return authSocialMapper.countByUidAndSocialType(uid, socialType);
    }

    @Override
    public void bindSocial(AuthSocial authSocial, UidInfoBO uidInfoBO) {
        authSocial.setUid(uidInfoBO.getAccountUid());
        authSocialMapper.update(authSocial);
        // 是否开启通联支付，是则为账号绑定支付标识（若用户已绑定手机则不需要）
        Integer paySysType = configFeignClient.getPaySysType().getData();
        if (Objects.equals(paySysType, PaySysType.ALLINPAY.value())) {
            PersonalMemberInfo memberInfo = allinpayFeignClient.getPersonalMemberInfo(uidInfoBO.getUserId().toString()).getData();
            if (Objects.nonNull(memberInfo)
                    && !memberInfo.getPhoneChecked()) {
                allinpayFeignClient.bindPayAcct(uidInfoBO.getUserId(), authSocial.getBizUserId(), authSocial.getSocialType());
            }
        }
    }

}
