package com.jeequan.jeepay.mch.secruity;

import com.jeequan.jeepay.converter.BaseConverter;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.SysUser;
import com.jeequan.jeepay.core.exception.JeepayAuthenticationException;
import com.jeequan.jeepay.core.model.security.JeeUserDetails;
import com.jeequan.jeepay.core.utils.RegKit;
import com.jeequan.jeepay.db.entity.SysUserAuth;
import com.jeequan.jeepay.db.entity.SysUserEntity;
import com.jeequan.jeepay.db.entity.SysUserMchStoreRela;
import com.jeequan.jeepay.service.impl.SysUserAuthService;
import com.jeequan.jeepay.service.impl.SysUserMchStoreRelaService;
import com.jeequan.jeepay.service.impl.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * UserDetailsService实现类
 *
 * @author terrfly
 * @modify zhuxiao
 *
 * @date 2021-04-27 15:50
 */
@Service
public class JeeUserDetailsServiceImpl implements UserDetailsService {

    @Autowired private SysUserService sysUserService;
    @Autowired private SysUserAuthService sysUserAuthService;
    @Autowired private SysUserMchStoreRelaService mchStoreRelaService;
    @Autowired private BaseConverter baseConverter;

    /**
     *
     * 此函数为： authenticationManager.authenticate(upToken) 内部调用 ;
     * 需返回 用户信息载体 / 用户密码  。
     * 用户角色+权限的封装集合 (暂时不查询， 在验证通过后再次查询，避免用户名密码输入有误导致查询资源浪费)
     *
     * **/
    @Override
    public UserDetails loadUserByUsername(String loginUsernameStr) throws UsernameNotFoundException {

        //登录方式， 默认为账号密码登录
        byte identityType = CS.AUTH_TYPE.LOGIN_USER_NAME;
        if(RegKit.isMobile(loginUsernameStr)){
            identityType = CS.AUTH_TYPE.TELPHONE; //手机号登录
        }

        //首先根据登录类型 + 用户名得到 信息
        SysUserAuth auth = sysUserAuthService.selectByLogin(loginUsernameStr, identityType, CS.SYS_ROLE_TYPE.MCH);
//        SysUserAuth auth = sysUserAuthService.getUserByLogin(loginUsernameStr, identityType);

        if(auth == null){ //没有该用户信息
            throw JeepayAuthenticationException.build("用户名/密码错误！");
        }

        //用户ID
        Long userId = auth.getUserId();

        SysUserEntity sysUserEntity = sysUserService.getById(userId);

        if (sysUserEntity == null) {
            throw JeepayAuthenticationException.build("用户名/密码错误！");
        }

        if(CS.PUB_USABLE != sysUserEntity.getState()){ //状态不合法
            throw JeepayAuthenticationException.build("用户状态不可登录，请联系管理员！");
        }

        // 判断用户状态 查询是绑定的门店信息 [如果当前用户为店长/店员类型]
        if (sysUserEntity.getUserType() == SysUser.UEST_TYPE_DIRECTOR || sysUserEntity.getUserType() == SysUser.UEST_TYPE_CASHIER) {
            // 查询当前用户绑定的门店信息
            List<SysUserMchStoreRela> relaList = mchStoreRelaService.list(SysUserMchStoreRela.gw().eq(SysUserMchStoreRela::getSysUserId, sysUserEntity.getSysUserId()));
            // 绑定信息不为空
            if (!ObjectUtils.isEmpty(relaList)) {
                List<String> storeIdList = new ArrayList<>();
                relaList.forEach(item -> {
                    storeIdList.add(item.getStoreId());
                });

                return new JeeUserDetails(baseConverter.toModel(sysUserEntity), auth.getCredential(), storeIdList);
            }else {
                throw JeepayAuthenticationException.build("当前用户未绑定门店，请先联系商户绑定门店！");
            }

        }

        return new JeeUserDetails(baseConverter.toModel(sysUserEntity), auth.getCredential());

    }
}
