package com.ebts.framework.web.service;

import com.ebts.common.constant.Constants;
import com.ebts.common.core.entity.entity.User;
import com.ebts.common.core.entity.model.LoginUser;
import com.ebts.common.exception.BaseException;
import com.ebts.common.exception.CustomException;
import com.ebts.common.exception.user.UserPasswordNotMatchException;
import com.ebts.common.utils.MessageUtils;
import com.ebts.common.utils.StringUtils;
import com.ebts.framework.dao.AsyncDao;
import com.ebts.framework.dao.factory.AsyncFactory;
import com.ebts.system.dao.UserDao;
import com.ebts.system.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 18209
 * @Date 2021/6/5 8:37
 * @Email clay@hchyun.com
 * @Version 1.0
 */
@Component
public class WeChatService {
    private static final Logger log = LoggerFactory.getLogger(WeChatService.class);
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private UserService userService;

    @Resource
    private AuthenticationManager authenticationManager;


    public Map<String, Object> loginWeCat(User user) {
        User userDB = userDao.selectUserByOpenId(user.getOpenId(), user.getUnionId(), user.getUserType());
        Map<String, Object> mode = new HashMap<>();
        mode.put("activate", true);
        if (null == userDB) {
            int rows = userService.insertUser(user);
            if (rows <= 0) {
                log.info("微信授权失败");
                throw new BaseException("微信授权失败!");
            }
            userDB = userDao.selectUserByOpenId(user.getOpenId(), user.getUnionId(), user.getUserType());
            mode.put("activate", false);
        } else if (StringUtils.isEmpty(userDB.getPhonenumber())) {
            mode.put("activate", false);
        }
        userDB.setPassword("");
        LoginUser loginUser = new LoginUser(userDB, permissionService.getMenuPermission(userDB));
        mode.put("token", tokenService.createToken(loginUser));
        mode.put("user", userDB);
        return mode;
    }


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public Map<String, Object> login(String username, String password, String type) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncDao.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncDao.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncDao.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        User user = loginUser.getUser();
        Map<String, Object> mode = new HashMap<>();
        if (!user.getUserType().equals(type)) {
            log.info("登录入口有误：{} 已被删除.", username);
            throw new BaseException("对不起，用户:" + username + " 您登录的入口有误");
        }
        user.setPassword("");
        mode.put("user", user);
        // 生成token
        mode.put("token", tokenService.createToken(loginUser));
        return mode;
    }

}
