package cn.quantgroup.xyqb.service.user.impl;

import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.service.user.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by 11 on 2016/12/29.
 */
@Slf4j
@Service
public class TenantServiceImpl implements ITenantService {

    @Autowired
    private IProductLoginService productLoginService;

    @Autowired
    private ICustomerInfoService customerInfoService;

    @Autowired
    private IOauthClientDetailsService oauthClientDetailsService;

    @Override
    public User getTenantUser(User user, String tenantId) {
        OauthClientDetailsEntity oauthClientDetails = oauthClientDetailsService.findFirstByClientId(tenantId);
        if (oauthClientDetails != null) {
            ProductLoginEntity productLogin = productLoginService.findSlaveByPloginInfo(oauthClientDetails.getInstitutionId(), oauthClientDetails.getProductId(), user.getId());
            if (productLogin != null) {
                if (!user.getPhoneNo().equals(productLogin.getPhoneNo())) {
                    return null;
                }
                user.setPassword(productLogin.getPassword());
                return user;
            }
        }
        return null;
    }

    @Override
    public UserDetail getTenantUserDetail(UserDetail userDetail, String tenantId) {
        OauthClientDetailsEntity oauthClientDetails = oauthClientDetailsService.findFirstByClientId(tenantId);
        if (oauthClientDetails != null) {
            ProductLoginEntity productLogin = productLoginService.findSlaveByPloginInfo(oauthClientDetails.getInstitutionId(), oauthClientDetails.getProductId(), userDetail.getUserId());
            if (productLogin != null) {
                if (!userDetail.getPhoneNo().equals(productLogin.getPhoneNo())) {
                    return null;
                }

                CustomerInfoEntity customerInfo = customerInfoService.findSlaveByCustomerId(productLogin.getCustomerId());
                if (customerInfo == null) {
                    return null;
                }

                UserDetail tenantUserDetail = new UserDetail();
                tenantUserDetail.setUserId(userDetail.getUserId());
                tenantUserDetail.setPhoneNo(userDetail.getPhoneNo());
                tenantUserDetail.setIdNo(customerInfo.getIdCardNo());
                tenantUserDetail.setName(customerInfo.getName());
                tenantUserDetail.setCreatedAt(userDetail.getCreatedAt());
                tenantUserDetail.setUpdatedAt(userDetail.getUpdatedAt());
                return tenantUserDetail;
            }
        }
        return null;
    }
}
