package cn.quantgroup.xyqb.controller.middleoffice.login;

import cn.quantgroup.xyqb.controller.middleoffice.common.VerifyStrategyFactory;
import cn.quantgroup.xyqb.controller.middleoffice.common.VerifyTypeEnum;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.exception.DataException;
import cn.quantgroup.xyqb.model.AuthBean;
import cn.quantgroup.xyqb.model.LoginProperties;
import cn.quantgroup.xyqb.service.register.IUserRegisterService;
import cn.quantgroup.xyqb.service.session.ISessionService;
import cn.quantgroup.xyqb.service.user.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 面向服务的聚合模块。
 */
@Slf4j
@Service
public class LoginModule implements ILoginModule {

    @Resource
    private IUserService userService;

    @Resource
    private IUserRegisterService userRegisterService;


    @Resource
    private ISessionService sessionService;

    @Override
    public LoginVo login(VerifyTypeEnum type, Boolean reg, Long channelId, String appChannel, String wechatOpenId, String phoneNo, String verify) {
        User user = userService.findByPhoneInDb(phoneNo);
        boolean autoReg = reg && type != VerifyTypeEnum.pwd;
        //auto reg
        if (user == null) {
            if (autoReg) {
                log.info("用户自动注册:{}", phoneNo);
                user = userRegisterService.register(channelId, phoneNo);
            } else {
                //todo 自定义异常
                throw new DataException("用户名或密码不正确");
            }
        }
        if (!user.getEnable()) {
            //用户不存在
            log.info("用户尝试登录，已注销:{}", phoneNo);
            //todo 自定义异常
            throw new DataException("用户名或密码不正确");
        }

        //验证
        VerifyStrategyFactory.get(type).verify(user, verify);

        LoginProperties loginProperties = LoginProperties.builder()
                .createdFrom(1L)
                .appChannel(appChannel)
                .channelId(channelId)
                .merchantName("xyqb")
                .build();
        AuthBean session = sessionService.createSession(user, loginProperties);
        return LoginVo.builder()
                .hasPassword(user.getHasPassword())
                .phoneNo(phoneNo)
                .token(session.getToken())
                .userId(user.getId())
                .uuid(user.getUuid()).build();
    }

    @Override
    public Boolean modifyPwd(VerifyTypeEnum type, String phoneNo, String password, String verify) {
        User user = userService.findByPhoneInDb(phoneNo);
        if (user == null) {
            //todo 自定义异常
            throw new DataException("用户不存在");
        }
        VerifyStrategyFactory.get(type).verify(user, verify);
        userService.resetPassword(phoneNo, password);
        return true;
    }

    @Override
    public LoginVo loginByUserId(Long channelId, String appChannel, Long userId, Integer tenantId) {
        User user = userService.findById(userId);
        if(null == user){
          throw new DataException("未找到此用户");
        }
        LoginProperties loginProperties = LoginProperties.builder()
                .createdFrom(user.getRegisteredFrom())
                .appChannel(appChannel == null ? "" : appChannel)
                .channelId(channelId)
                .tenantId(tenantId)
                .build();
        AuthBean session = sessionService.createSession(user, loginProperties);
        return LoginVo.builder()
                .hasPassword(user.getHasPassword())
                .phoneNo(user.getPhoneNo())
                .token(session.getToken())
                .userId(user.getId())
                .uuid(user.getUuid())
                .build();
    }


}
