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

import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.entity.middleoffice.AppletParamEntry;
import cn.quantgroup.xyqb.repository.ICustomerInfoRepository;
import cn.quantgroup.xyqb.repository.ICustomerLoginRepository;
import cn.quantgroup.xyqb.repository.IOauthClientDetailsRepository;
import cn.quantgroup.xyqb.repository.IProductLoginRepository;
import cn.quantgroup.xyqb.service.user.IOauthLoginInfoService;
import cn.quantgroup.xyqb.util.AtomicSequencer;
import cn.quantgroup.xyqb.util.RandomSequencer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by 11 on 2016/12/29.
 */
@Slf4j
@Service
public class OauthLoginInfoServiceImpl implements IOauthLoginInfoService {
    @Autowired
    private IOauthClientDetailsRepository oauthClientDetailsRepository;

    @Autowired
    private IProductLoginRepository productLoginRepository;

    @Autowired
    private ICustomerInfoRepository customerInfoRepository;

    @Autowired
    private ICustomerLoginRepository customerLoginRepository;

    @Autowired
    private AtomicSequencer atomicSequencer;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void addLoginInfo(User user, Integer tenantId) {
        OauthClientDetailsEntity oauthClientDetailsEntity = oauthClientDetailsRepository.findFirstByClientId(tenantId);
        if (oauthClientDetailsEntity != null) {
            String institutionId = oauthClientDetailsEntity.getInstitutionId();
            String productId = oauthClientDetailsEntity.getProductId();
            String phoneNo = user.getPhoneNo();
            Long userId = user.getId();
            ProductLoginEntity productLoginEntity = productLoginRepository.findFirstByInstitutionIdAndProductIdAndPhoneNo(institutionId, productId, phoneNo);
            long uuid = 0L;
            // 如果找不到该用户就创建
            if ("".equals(productLoginEntity) || productLoginEntity == null) {
                // 添加用户到产品登录表
                long customerId = atomicSequencer.nextId();
//            long id = session.nextId();
                long id = atomicSequencer.nextId();
                String customerName = customerId + "";
                uuid = RandomSequencer.randomUUID(customerId);
                ProductLoginEntity entity = new ProductLoginEntity();
                Integer partitionKey = atomicSequencer.partitionKey(customerId);
                productLoginEntity = EntityBuilder.productLogin(productId, institutionId, phoneNo, customerId, customerName, partitionKey, id);
                productLoginEntity.setExtensionAccountId(userId);
                productLoginRepository.save(productLoginEntity);
                // 根据customerId 获取uuid
                CustomerLoginEntity customerLoginEntity = customerLoginRepository.findFirstByCustomerId(productLoginEntity.getCustomerId());
                if (null != customerLoginEntity) {
                    uuid = customerLoginEntity.getUuid();
                }

                // 添加用户到登录表
                CustomerLoginEntity customerLogin = new CustomerLoginEntity();
//                customerLogin.setId(atomicSequencer.nextId());
                customerLogin.setInstitutionId(institutionId);
                customerLogin.setProductId(productId);
                customerLogin.setCustomerId(customerId);
                customerLogin.setUuid(uuid);
                customerLogin.setPartitionKey(partitionKey);
                customerLogin.setCreatedDate(new Date());
                customerLogin.setModifiedDate(new Date());
                customerLogin.setCreatedBy("");
                customerLogin.setModifiedBy("");
                customerLoginRepository.save(customerLogin);

                // 添加用户信息表
                CustomerInfoEntity customerInfo = new CustomerInfoEntity();
//                customerInfo.setId(atomicSequencer.nextId());
                customerInfo.setCustomerId(customerId);
                customerInfo.setInstitutionId(institutionId);
                customerInfo.setProductId(productId);
                customerInfo.setPartitionKey(partitionKey);
                customerInfo.setCreatedDate(new Date());
                customerInfo.setModifiedDate(new Date());
                customerInfo.setCreatedBy("");
                customerInfo.setModifiedBy("");
                customerInfoRepository.save(customerInfo);

            }
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void addRegisterInfo(User user, AppletParamEntry appletParamEntry) {
        OauthClientDetailsEntity oauthClientDetailsEntity = oauthClientDetailsRepository.findFirstByClientId(appletParamEntry.getTenantId());
        if (oauthClientDetailsEntity != null) {
            String institutionId = oauthClientDetailsEntity.getInstitutionId();
            String productId = oauthClientDetailsEntity.getProductId();
            String phoneNo = user.getPhoneNo();
            Long userId = user.getId();
            ProductLoginEntity productLoginEntity = productLoginRepository.findFirstByInstitutionIdAndProductIdAndPhoneNo(institutionId, productId, phoneNo);
            long uuid = 0L;
            // 如果找不到该用户就创建
            if ("".equals(productLoginEntity) || productLoginEntity == null) {
                // 添加用户到产品登录表
                long customerId = atomicSequencer.nextId();
                long id = atomicSequencer.nextId();
                String customerName = customerId + "";
                uuid = RandomSequencer.randomUUID(customerId);
                ProductLoginEntity entity = new ProductLoginEntity();
                Integer partitionKey = atomicSequencer.partitionKey(customerId);
                productLoginEntity = EntityBuilder.productLogin(productId, institutionId, phoneNo, customerId, customerName, partitionKey, id);
                productLoginEntity.setExtensionAccountId(userId);
                productLoginRepository.save(productLoginEntity);
                // 根据customerId 获取uuid
                CustomerLoginEntity customerLoginEntity = customerLoginRepository.findFirstByCustomerId(productLoginEntity.getCustomerId());
                if (null != customerLoginEntity) {
                    uuid = customerLoginEntity.getUuid();
                }

                // 添加用户到登录表
                CustomerLoginEntity customerLogin = new CustomerLoginEntity();
                customerLogin.setId(atomicSequencer.nextId());
                customerLogin.setInstitutionId(institutionId);
                customerLogin.setProductId(productId);
                customerLogin.setCustomerId(customerId);
                customerLogin.setUuid(uuid);
                customerLogin.setPartitionKey(partitionKey);
                customerLogin.setCreatedDate(new Date());
                customerLogin.setModifiedDate(new Date());
                customerLogin.setCreatedBy("");
                customerLogin.setModifiedBy("");
                customerLoginRepository.save(customerLogin);

                // 添加用户信息表
                CustomerInfoEntity customerInfo = new CustomerInfoEntity();
                customerInfo.setId(atomicSequencer.nextId());
                customerInfo.setCustomerId(customerId);
                customerInfo.setInstitutionId(institutionId);
                customerInfo.setAvatarUrl(appletParamEntry.getAvatarUrl());
                customerInfo.setNickName(appletParamEntry.getNickName());
                customerInfo.setAppName(appletParamEntry.getAppName());
                customerInfo.setCity(appletParamEntry.getCity());
                customerInfo.setCountry(appletParamEntry.getCountry());
                customerInfo.setProvince(appletParamEntry.getProvince());
                customerInfo.setLanguage(appletParamEntry.getLanguage());
                customerInfo.setSourceOpenId(appletParamEntry.getOpenId());
                customerInfo.setSex(cn.quantgroup.xyqb.model.Gender.class.getEnumConstants()[appletParamEntry.getGender()]);
                customerInfo.setUnionId(appletParamEntry.getUnionId());
                customerInfo.setUtmSource(appletParamEntry.getUtmSource());
                customerInfo.setProductId(productId);
                customerInfo.setPartitionKey(partitionKey);
                customerInfo.setCreatedDate(new Date());
                customerInfo.setModifiedDate(new Date());
                customerInfo.setCreatedBy("");
                customerInfo.setModifiedBy("");
                customerInfoRepository.save(customerInfo);

            }
        }
    }

}
