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.middleoffice.AppletParamEntry;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.WechatUserInfo;
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.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;
import org.springframework.util.ObjectUtils;

/**
 * @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
    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) {

        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());
            }
            wechatUserInfo.setUserId(user.getId());
        }

        //如果存在就更新在微信表里
        iWeChatUserRepository.save(wechatUserInfo);
        return wechatUserInfo.getUserId();
    }

    @Override
    public LoginVo login(String appName, String openId, Integer tenantId, String utmSource) {
        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 user = userService.findById(wechatUserInfo.getUserId());
        if (null == user) {
            log.warn("未找到此用户,appName:{} ,openId:{}", appName, openId);
            throw new AppletException("未找到此用户","0401");
        }
        //校验租户ID tenantId
        if (TenantUtil.TENANT_DEFAULT != null && TenantUtil.TENANT_DEFAULT !=0 && !TenantUtil.TENANT_DEFAULT.equals(tenantId)) {
            iOauthLoginInfoService.addLoginInfo(user, tenantId);
        }
        LoginVo loginVo = loginModule.loginByUserId(user.getRegisteredFrom(),
                utmSource == null ? "" : utmSource, user.getId(), tenantId);
        return loginVo;
    }


}
