package com.miaxis.framework.web.service;

import com.miaxis.common.core.domain.entity.SysUser;
import com.miaxis.common.core.domain.entity.UserInfo;
import com.miaxis.common.core.domain.model.LoginUser;
import com.miaxis.common.enums.StudentLoginTypeEnum;
import com.miaxis.common.enums.UserStatusEnum;
import com.miaxis.common.exception.BaseException;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.utils.RandomNameUtils;
import com.miaxis.common.utils.ServletUtils;
import com.miaxis.common.utils.StringUtils;
import com.miaxis.system.service.ISysConfigService;
import com.miaxis.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.transaction.annotation.Transactional;

/**
 * 用户验证处理
 *
 * @author miaxis
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;


    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysConfigService configService;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String identification) throws UsernameNotFoundException {
        //获取登录类型
        String loginType = (String) ServletUtils.getRequest().getAttribute("loginType");
        if (StringUtils.isEmpty(loginType)){
            SysUser user = userService.selectUserByUserName(identification);
            if (StringUtils.isNull(user))
            {
                log.info("登录用户：{} 不存在.", identification);
                throw new UsernameNotFoundException("登录用户：" + identification + " 不存在");
            }
            else if (UserStatusEnum.DELETED.getCode().equals(user.getDelFlag()))
            {
                log.info("登录用户：{} 已被删除.", identification);
                throw new BaseException("对不起，您的账号：" + identification + " 已被删除");
            }
            else if (UserStatusEnum.DISABLE.getCode().equals(user.getStatus()))
            {
                log.info("登录用户：{} 已被停用.", identification);
                throw new BaseException("对不起，您的账号：" + identification + " 已停用");
            }
            return createLoginUser(user);
        } else if (StudentLoginTypeEnum.AUTHORIZATION_CODE_LOGIN.getCode().equals(loginType)){
            {
                //由于之前没有保存用户unionid,只有openid，所以这里判定两个都不存在才不存在用户
                UserInfo userInfoGetByUnionId = userService.getStudentByUnionId(identification);
                String openid = (String)ServletUtils.getRequest().getAttribute("openid");
                UserInfo userInfoGetByOpenId = userService.getStudentByOpenId(openid);
                String third = (String)ServletUtils.getRequest().getAttribute("third");
                if (userInfoGetByUnionId == null && userInfoGetByOpenId == null) {
                    UserInfo userInfo = new UserInfo();
                    userInfo.setHeadImage((String) ServletUtils.getRequest().getAttribute("headImage"));
                    userInfo.setNickName((String) ServletUtils.getRequest().getAttribute("nickName"));
                    userInfo.setThirdPlatform(third);
                    userInfo.setAppOpenid(openid);
                    userInfo.setUnionId(identification);
                    userInfo.setIsVip(0);
                    userService.saveUserInfo(userInfo);
                    return createLoginUser(userService.getStudentByUnionId(identification));
                }else {
                    UserInfo userInfo = userInfoGetByUnionId != null ? userInfoGetByUnionId:userInfoGetByOpenId;
                    userInfo.setHeadImage((String) ServletUtils.getRequest().getAttribute("headImage"));
                    userInfo.setNickName((String) ServletUtils.getRequest().getAttribute("nickName"));
                    userInfo.setThirdPlatform(third);
                    userInfo.setUnionId(identification);
                    userService.updateStudent(userInfo);
                    return createLoginUser(userService.getStudentByUnionId(identification));
                }

            }
        }
        else if (StudentLoginTypeEnum.AUTHORIZATION_CODE_DY_LOGIN.getCode().equals(loginType)){
                UserInfo userInfoGetByUnionId = userService.getStudentByUnionId(identification);
                String openid = (String)ServletUtils.getRequest().getAttribute("openid");;
                String third = (String)ServletUtils.getRequest().getAttribute("third");
                if (userInfoGetByUnionId == null ) {
                    UserInfo userInfo = new UserInfo();
                    userInfo.setHeadImage((String) ServletUtils.getRequest().getAttribute("headImage"));
                    userInfo.setNickName((String) ServletUtils.getRequest().getAttribute("nickName"));
                    userInfo.setThirdPlatform(third);
                    userInfo.setAppOpenid(openid);
                    userInfo.setUnionId(identification);
                    userInfo.setIsVip(0);
                    userService.saveUserInfo(userInfo);
                    return createLoginUser(userService.getStudentByUnionId(identification));
                }else {
                    UserInfo userInfo = userInfoGetByUnionId;
                    userInfo.setHeadImage((String) ServletUtils.getRequest().getAttribute("headImage"));
                    userInfo.setNickName((String) ServletUtils.getRequest().getAttribute("nickName"));
                    userInfo.setAppOpenid(openid);
                    userService.updateStudent(userInfo);
                    return createLoginUser(userService.getStudentByUnionId(identification));
                }


        }
        else if (StudentLoginTypeEnum.AUTHORIZATION_CODE_TT_LOGIN.getCode().equals(loginType)){
            UserInfo userInfoGetByUnionId = userService.getStudentByUnionId(identification);
            String openid = (String)ServletUtils.getRequest().getAttribute("openid");;
            String third = (String)ServletUtils.getRequest().getAttribute("third");
            if (userInfoGetByUnionId == null ) {
                UserInfo userInfo = new UserInfo();
//                userInfo.setHeadImage((String) ServletUtils.getRequest().getAttribute("headImage"));
//                userInfo.setNickName((String) ServletUtils.getRequest().getAttribute("nickName"));
                userInfo.setThirdPlatform(third);
                userInfo.setXcxOpenid(openid);
                userInfo.setUnionId(identification);
                userInfo.setIsVip(0);
                userService.saveUserInfo(userInfo);
                return createLoginUser(userService.getStudentByUnionId(identification));
            }else {
                UserInfo userInfo = userInfoGetByUnionId;
                userInfo.setXcxOpenid(openid);
//                userInfo.setHeadImage((String) ServletUtils.getRequest().getAttribute("headImage"));
//                userInfo.setNickName((String) ServletUtils.getRequest().getAttribute("nickName"));
                userService.updateStudent(userInfo);
                return createLoginUser(userService.getStudentByUnionId(identification));
            }


        }
        else if (StudentLoginTypeEnum.IOS_CODE_LOGIN.getCode().equals(loginType)){
            {
                UserInfo userInfo = userService.getStudentByOpenId(identification);
                if (userInfo == null) {
                    userInfo = new UserInfo();
                    userInfo.setAppOpenid(identification);
                    userService.saveUserInfo(userInfo);
                }
                return createLoginUser(userService.getStudentByOpenId(identification));
            }
        }
        else{
            throw new CustomException("登录类型不存在");
        }



    }

    private UserDetails createLoginUser(UserInfo student) {
        return new LoginUser(student);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user, permissionService.getMenuPermission(user));
    }
}
