package cn.quantgroup.xyqb.service.middleoffice.applet.impl;

import cn.quantgroup.xyqb.controller.middleoffice.login.ILoginModule;
import cn.quantgroup.xyqb.controller.middleoffice.login.LoginVo;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.WechatUserInfo;
import cn.quantgroup.xyqb.entity.middleoffice.AppletParamEntry;
import cn.quantgroup.xyqb.exception.AppletException;
import cn.quantgroup.xyqb.repository.IWeChatUserRepository;
import cn.quantgroup.xyqb.service.middleoffice.applet.IAppletService;
import cn.quantgroup.xyqb.service.register.IUserRegisterService;
import cn.quantgroup.xyqb.service.user.IOauthLoginInfoService;
import cn.quantgroup.xyqb.service.user.ITenantService;
import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.util.TenantUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author ：dongjianhua
 * @date ：Created in 2020/5/27 17:27
 * @description：小程序服务层
 * @modified By：
 * @version: 1.0
 */
@Slf4j
@Service
public class AppletServiceImpl implements IAppletService {


    private final IWeChatUserRepository iWeChatUserRepository;

    private final IUserRegisterService iUserRegisterService;

    private final IUserService userService;
    private ILoginModule loginModule;

    @Autowired
    private IOauthLoginInfoService iOauthLoginInfoService;

    @Autowired
    private ITenantService tenantService;

    @Autowired
    public AppletServiceImpl(IWeChatUserRepository iWeChatUserRepository,
                             IUserRegisterService iUserRegisterService,
                             IUserService userService,
                             ILoginModule loginModule) {
        this.iWeChatUserRepository = iWeChatUserRepository;
        this.iUserRegisterService = iUserRegisterService;
        this.userService = userService;
        this.loginModule = loginModule;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long relevance(AppletParamEntry appletParamEntry) {
        if (appletParamEntry.getTenantId() == null ) {
            appletParamEntry.setTenantId(TenantUtil.TENANT_DEFAULT);
        }

        if (appletParamEntry.getTenantId().equals(TenantUtil.TENANT_DEFAULT)) {
            WechatUserInfo wechatUserInfo = iWeChatUserRepository.findByOpenIdAndAppName(appletParamEntry.getOpenId(), appletParamEntry.getAppName());
            //这个接口先不考虑更换手机号的情况

            wechatUserInfo = (wechatUserInfo == null ? new WechatUserInfo() : wechatUserInfo);
            wechatUserInfo.setNickName(appletParamEntry.getNickName());
            wechatUserInfo.setCity(appletParamEntry.getCity());
            wechatUserInfo.setCountry(appletParamEntry.getCountry());
            wechatUserInfo.setProvince(appletParamEntry.getProvince());
            wechatUserInfo.setAppName(appletParamEntry.getAppName());
            wechatUserInfo.setHeadImgUrl(appletParamEntry.getAvatarUrl());
            wechatUserInfo.setLanguage(appletParamEntry.getLanguage());
            wechatUserInfo.setOpenId(appletParamEntry.getOpenId());
            wechatUserInfo.setSex(appletParamEntry.getGender());
            wechatUserInfo.setUnionId(appletParamEntry.getUnionId());
            wechatUserInfo.setPhoneNo(appletParamEntry.getMobile());
            wechatUserInfo.setUtmSource(appletParamEntry.getUtmSource());
            if (null == wechatUserInfo.getUserId()) {//只要存在userid 就说明已经在用户表里了 不考虑小程序这边换手机号了
                User user = userService.findByPhoneInDb(appletParamEntry.getMobile());
                //如果不存在就去注册一下
                if (null == user) {
                    user = iUserRegisterService.register(appletParamEntry.getChannelId(), appletParamEntry.getMobile());
                }
                iOauthLoginInfoService.addRegisterInfo(user, appletParamEntry);
                wechatUserInfo.setUserId(user.getId());
            }

            //如果存在就更新在微信表里
            iWeChatUserRepository.save(wechatUserInfo);
            return wechatUserInfo.getUserId();
        } else {
            User user = userService.findByPhoneInDb(appletParamEntry.getMobile());
            //如果不存在就去注册一下
            if (null == user) {
                user = iUserRegisterService.register(appletParamEntry.getChannelId(), appletParamEntry.getMobile(), appletParamEntry.getTenantId());
            }
            iOauthLoginInfoService.addRegisterInfo(user, appletParamEntry);
            return user.getId();
        }
    }


    @Override
    public LoginVo login(String appName, String openId, Integer tenantId, String utmSource) {
        if (tenantId == null) {
            tenantId = TenantUtil.TENANT_DEFAULT;
        }

        User user = null;

        if (TenantUtil.TENANT_DEFAULT.equals(tenantId)) {
            WechatUserInfo wechatUserInfo = iWeChatUserRepository.findByOpenIdAndAppName(openId, appName);
            if (null == wechatUserInfo) {
                log.warn("未找到此用户,appName:{} ,openId:{}", appName, openId);
                throw new AppletException("未找到此用户","0401");
            }
            if (null == wechatUserInfo.getUserId()) {
                log.warn("用户未绑定到xyqb,appName:{} ,openId:{}", appName, openId);
                throw new AppletException("未找到此用户绑定信息","0401");
            }
            user = userService.findById(wechatUserInfo.getUserId());
            if (null == user) {
                log.warn("未找到此用户,appName:{} ,openId:{}", appName, openId);
                throw new AppletException("未找到此用户","0401");
            }
            iOauthLoginInfoService.addLoginInfo(user, tenantId);

        } else {
            // 通过租户id和openId查询是否有关联
            Long userId = tenantService.getTenantCustomerInfoByOpenId(openId, tenantId);
            if (null == userId) {
                log.warn("未找到此用户,tenantId:{} ,openId:{}", tenantId, openId);
                throw new AppletException("未找到此用户","0401");
            }
            user = userService.findById(userId);
            if (null == user) {
                log.warn("未找到此用户,appName:{} ,openId:{}", appName, openId);
                throw new AppletException("未找到此用户","0401");
            }
        }

        LoginVo loginVo = loginModule.loginByUserId(user.getRegisteredFrom(),
                utmSource == null ? "" : utmSource, user.getId(), tenantId);
        return loginVo;
    }


}
