package com.xingxi.api.configuration.security;

import com.xingxi.common.core.domain.entity.SysUser;
import com.xingxi.common.enums.EUserType;
import com.xingxi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

@Slf4j
@RequiredArgsConstructor
@Component("WxLoginAuthenticationManager")
@Primary
public class WxLoginAuthenticationManager implements AuthenticationManager {
    private final SysUserMapper sysUserMapper;
//    private final SysConfigMapper configMapper;
//    private final WxaStoreMerchantMapper wxaStoreMerchantMapper;

    @Transactional
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        log.debug("WxLoginAuthenticationManager.authenticate()....");

        SysUser loginSysUser = (SysUser) authentication.getPrincipal();
        String wxOpenId = loginSysUser.getWxOpenId();
        String wxSessionKey = loginSysUser.getWxSessionKey();

        SysUser dbUser = sysUserMapper.selectUserByOpenId(wxOpenId);
        if (ObjectUtils.isEmpty(dbUser)) {

            dbUser = new SysUser();
            dbUser.setLoginName("wx_user");
            dbUser.setDeptId(100L);
            dbUser.setWxOpenId(wxOpenId);
            dbUser.setWxSessionKey(wxSessionKey);
            dbUser.setUserType(EUserType.WECHAT.getVal());
            dbUser.setLoginDate(getLoginDate());
            dbUser.setCreateUser(wxOpenId);
            dbUser.setCreateTime(new Date());
            sysUserMapper.insertUser(dbUser);

        } else {
            SysUser updateSysUser = new SysUser();
            updateSysUser.setUserId(dbUser.getUserId());
            updateSysUser.setWxSessionKey(wxSessionKey);
            updateSysUser.setLoginDate(getLoginDate());
            updateSysUser.setUpdateUser(wxOpenId);
            updateSysUser.setUpdateTime(new Date());
            sysUserMapper.updateUser(updateSysUser);

            // 后续使用
            dbUser.setLoginDate(updateSysUser.getLoginDate());
        }

        return new UsernamePasswordAuthenticationToken(dbUser, null, new ArrayList<>());
    }

    private Date getLoginDate() {
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.MILLISECOND, 0);
        return instance.getTime();
    }

}
