/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.security.multishop.service.impl;

import com.yami.shop.bean.enums.ShopStatus;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.dao.ShopDetailMapper;
import com.yami.shop.security.comment.exception.UsernameNotFoundException;
import com.yami.shop.security.multishop.model.YamiShopUser;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户详细信息
 *
 * @author
 */
@Slf4j
@Primary
@Service
@AllArgsConstructor
public class YamiShopUserDetailsServiceImpl implements UserDetailsService {

    private final ShopDetailMapper shopDetailMapper;

    /**
     * 用户密码登录
     *
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    @SneakyThrows
    public YamiShopUser loadUserByUsername(String username) {
        ShopDetail shopDetail = shopDetailMapper.getShopByMobile(username);
        if (shopDetail == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        YamiShopUser shopUser = new YamiShopUser();
        shopUser.setEnabled(
                !(Objects.equals(shopDetail.getShopStatus(), ShopStatus.NOTOPEN.value())
                || Objects.equals(shopDetail.getShopStatus(), ShopStatus.OFFLINE.value())));
        shopUser.setPassword(shopDetail.getPassword());
        shopUser.setUserId(shopDetail.getUserId());
        shopUser.setShopId(shopDetail.getShopId());
        shopUser.setUsername(shopDetail.getMobile());
        return shopUser;
    }
}
