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 com.alibaba.fastjson.JSON;
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, rollbackFor = Exception.class)
    public void addLoginInfo(User user, Integer tenantId) {
        log.info("=addLoginInfo -> user={}, tenetId={}", JSON.toJSONString(user), 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 findProductLoginEntity = productLoginRepository.findByInstitutionIdAndProductIdAndExtensionAccountId(institutionId, productId, userId);
            ProductLoginEntity findProductLoginByPhoneEntity = productLoginRepository.findFirstByInstitutionIdAndProductIdAndPhoneNo(institutionId, productId, phoneNo);
            log.info("=findProductLoginEntity -> {}", JSON.toJSONString(findProductLoginEntity));
            log.info("=findProductLoginPhoneEntity -> {}", JSON.toJSONString(findProductLoginByPhoneEntity));
            long uuid = 0L;
            // 如果找不到该用户就创建
            if (findProductLoginEntity == null && findProductLoginByPhoneEntity == 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 productLoginEntity = EntityBuilder.productLogin(productId, institutionId, phoneNo, customerId, customerName, partitionKey, id);
                productLoginEntity.setExtensionAccountId(userId);
                log.info("=addLoginInfo=save begin productLoginRepository={}", JSON.toJSONString(productLoginEntity));
                productLoginRepository.save(productLoginEntity);
                log.info("=addLoginInfo=save end productLoginRepository={}", JSON.toJSONString(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("");
                log.info("=addLoginInfo=save begin customerLoginRepository={}", JSON.toJSONString(customerLogin));
                customerLoginRepository.save(customerLogin);
                log.info("=addLoginInfo=save end customerLoginRepository={}", JSON.toJSONString(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("");
                log.info("=addLoginInfo=save begin customerInfoRepository={}", JSON.toJSONString(customerInfo));
                customerInfoRepository.save(customerInfo);
                log.info("=addLoginInfo=save end customerInfoRepository={}", JSON.toJSONString(customerInfo));
            }
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void addRegisterInfo(User user, AppletParamEntry appletParamEntry) {
        log.info("=addRegisterInfo= -> User={}, AppletParamEntry={}", JSON.toJSONString(user), 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);
                log.info("=addRegisterInfo=save begin productLoginRepository= {}", JSON.toJSONString(productLoginEntity));
                productLoginRepository.save(productLoginEntity);
                log.info("=addRegisterInfo=save end productLoginRepository= {}", JSON.toJSONString(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("");
                log.info("=addRegisterInfo=save begin customerLoginRepository= {}", JSON.toJSONString(customerLogin));
                customerLoginRepository.save(customerLogin);
                log.info("=addRegisterInfo=save end customerLoginRepository= {}", JSON.toJSONString(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("");
                log.info("=addRegisterInfo=save begin customerInfoRepository= {}", JSON.toJSONString(customerInfo));
                customerInfoRepository.save(customerInfo);
                log.info("=addRegisterInfo=save end customerInfoRepository= {}", JSON.toJSONString(customerInfo));
            } else {
                // 如果产品登陆表有信息，查询用户信息表
                CustomerInfoEntity customerInfo = customerInfoRepository.findByCustomerId(productLoginEntity.getCustomerId());
                customerInfo = (customerInfo == null ? new CustomerInfoEntity() : customerInfo);
                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.setCreatedDate(new Date());
                customerInfo.setModifiedDate(new Date());
                customerInfo.setCreatedBy("");
                customerInfo.setModifiedBy("");
                customerInfoRepository.save(customerInfo);
            }

        }
    }

}
