package com.ruoyi.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdGenerator;
import com.ruoyi.system.domain.AppUser;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.columns.SysTeacher;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.YjAppUserService;
import com.ruoyi.system.service.columns.ISysTeacherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;


    @Autowired
    private SysUserRoleMapper userRoleMapper;



    @Autowired
    private ISysConfigService configService;

    @Autowired
    private YjAppUserService appUserService;

    @Autowired
    private ISysTeacherService teacherService;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user)
    {
       if (! SecurityUtils.isAdmin(SecurityUtils.getUserId())){
           user.setTenantId(SecurityUtils.getLoginUser().getNowTenantId());
       }

        return userMapper.selectUserList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName)
    {
        return userMapper.selectUserByUserName(userName);
    }
    @Override
    public List<SysUser> selectUserByIds(Long[] ids)
    {
        return userMapper.selectUserByIds(ids);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId)
    {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName)
    {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }



    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName)
    {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user)
    {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users))
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user)
    {
        user.setUserId(IdGenerator.nextId());
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户与角色管理
        insertUserRole(user);
        //新增app用户
        insertAppUser(user);
        //关联teacher表
        Long[] roles = user.getRoleIds();
        if (Arrays.stream(roles)
                .anyMatch(new Long(104)::equals)){
            SysTeacher teacher=new SysTeacher();
            teacher.setUserId(user.getUserId());
            teacher.setTeacherName(user.getNickName());
            teacherService.insertSysTeacher(teacher);
        }
        return rows;
    }



    //关联app账号
    public void insertAppUser(SysUser user){
        AppUser appUser=appUserService.getOne(new QueryWrapper<AppUser>().eq("phone_number",user.getPhonenumber()));

        if (ObjectUtil.isEmpty(appUser)){
            appUser=new AppUser();
            appUser.setNickName(user.getNickName());
            appUser.setPhoneNumber(user.getPhonenumber());
            appUser.setPassword(user.getPassword());
            appUser.setStatus(1);
            appUser.setManageAccountId(user.getStatus().equals("0")?user.getUserId():null);
            appUser.setVisitStore(user.getDeptId());
            appUserService.save(appUser);
        }else {
            if (user.getStatus().equals("0"))
            appUserService.update(new UpdateWrapper<AppUser>().eq("phone_number",user.getPhonenumber()).set("manage_account_id",user.getUserId()));
        }
    }

    //修改关联app账号
    public void removeAppUserManager(Long sysUserId){
        AppUser appUser=appUserService.getOne(new QueryWrapper<AppUser>().eq("manage_account_id",sysUserId));
        if (ObjectUtil.isNotEmpty(appUser)){
            appUser.setManageAccountId(null);
            appUserService.updateById(appUser);
        }
    }
    //修改关联app账号
    public void addAppUserManager(Long sysUserId){
        SysUser sysUser=selectUserById(sysUserId);
        appUserService.update(new UpdateWrapper<AppUser>().eq("phone_number",sysUser.getPhonenumber()).set("manage_account_id",sysUser.getUserId()));
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user)
    {
        user.setUserId(IdGenerator.nextId());
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user)
    {
        Long userId = user.getUserId();
        // 修改用户与教练表关联
        // 1.是否原为教练
        int dbHasTeacherRole= userRoleMapper.countRoleAndUserId(new Long(104),userId);
        Long[] roles = user.getRoleIds();
        //2.新权限中是否含有教练角色
        if (Arrays.stream(roles)
            .anyMatch(new Long(104)::equals)){
            //3.新增有教练角色，判断原有角色是否包含教练
            if (dbHasTeacherRole<1){
                //3.1.原来没有，则新增教练表数据
                SysTeacher teacher=new SysTeacher();
                teacher.setUserId(userId);
                teacher.setTeacherName(user.getNickName());
                teacherService.insertSysTeacher(teacher);
            }
        }else {
            //4.新增无教练角色，判断原有角色是否包含教练
            if (dbHasTeacherRole>0 ){
                //4.1原来有，则判断教练表数据是否被使用
                if (teacherService.isUsed(Arrays.asList(userId))){
                    throw new RuntimeException("该员工作为教练已经排课，或在会员卡项中被单独定义，无法删除教练角色！");
                }else {
                    teacherService.deleteSysTeacherByUserId(userId);
                }
            }
        }
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        //如果账号停用【帐号状态（0正常 1停用）】取消与app登录用户的关联
        if (user.getStatus().equals("1")){
            removeAppUserManager(userId);
        }
        //如果手机号有变化，则更新关联的app账号
        if (StrUtil.isNotEmpty(user.getPhonenumber())){
            SysUser dbUser=this.selectUserById(userId);
            if (!dbUser.getPhonenumber().equals(user.getPhonenumber())){
               user.setPassword(dbUser.getPassword());
               removeAppUserManager(userId);
               insertAppUser(user);
            }
        }
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds)
    {
        // 1.是否原为教练  2.是 校验是否被使用
        int dbHasTeacherRole= userRoleMapper.countRoleAndUserId(new Long(104),userId);
        if (Arrays.stream(roleIds)
                .anyMatch(new Long(104)::equals)){
            //关联teacher表 新增的教练权限
            if (dbHasTeacherRole<1){
                SysTeacher teacher=new SysTeacher();
                teacher.setUserId(userId);
                teacher.setTeacherName(this.selectUserById(userId).getNickName());
                teacherService.insertSysTeacher(teacher);
            }
        }else {
            if (dbHasTeacherRole>0 ){
                if (teacherService.isUsed(Arrays.asList(userId))){
                    throw new RuntimeException("该员工作为教练已经排课，或在会员卡项中被单独定义，无法删除教练角色！");
                }else{
                    teacherService.deleteSysTeacherByUserId(userId);
                }
            }


        }
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     * 帐号状态（0正常 1停用）
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user)
    {
        //修改关联app账号
        if (user.getStatus().equals("1")){
            removeAppUserManager(user.getUserId());
            SysTeacher teacher=new SysTeacher();
            teacher.setUserId(teacher.getUserId());
            teacher.setReleases(0);
            teacherService.updateSysTeacher(teacher);
        }else {
            addAppUserManager(user.getUserId());
        }

        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user)
    {
        return userMapper.updateUser(user);
    }


    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password)
    {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            Boolean hasTeacherRole=false;
            for (Long roleId : roles)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
                if (roleId.equals(new Long(104))){
                    hasTeacherRole=true;
                }
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
            }
            SysUser teacgerUser=new SysUser();
            teacgerUser.setUserId(user.getUserId());
            teacgerUser.setTeacher(hasTeacherRole?1:0);
            userMapper.updateUser(teacgerUser);
        }
    }




    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotNull(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            Boolean hasTeacherRole=false;
            for (Long roleId : roleIds)
            {

                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
                if (roleId.equals(new Long(104))){
                    hasTeacherRole=true;
                }
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
            }
            SysUser user=new SysUser();
            user.setUserId(userId);
            user.setTeacher(hasTeacherRole?1:0);
            userMapper.updateUser(user);
        }
    }



    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds)
    {

        for (Long userId : userIds)
        {
            // 1.是否原为教练  2.是 校验是否被使用
            int dbHasTeacherRole= userRoleMapper.countRoleAndUserId(new Long(104),userId);
            if (dbHasTeacherRole>0 ){
                if (teacherService.isUsed(Arrays.asList(userId))){
                    throw new RuntimeException("该员工作为教练已经排课，或在会员卡项中被单独定义，无法删除！");
                }
                //关联teacher 表
                if (ObjectUtil.isNotEmpty(teacherService.selectSysTeacherByUserId(userId))){
                    teacherService.deleteSysTeacherByUserId(userId);
                }
            }

            checkUserAllowed(new SysUser(userId));
            //取消与app登录用户的关联
            removeAppUserManager(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);

        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param userId 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, Long userId)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(userId);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    user.setUpdateBy(userId);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


}
