package com.hxhq.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import javax.validation.Validator;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hxhq.business.domain.SystemLog;
import com.hxhq.business.dto.select.BzListDto;
import com.hxhq.business.dto.select.DeptUserTreeDto;
import com.hxhq.business.form.common.SignForm;
import com.hxhq.business.service.IRoleChangeService;
import com.hxhq.business.service.ISystemLogService;
import com.hxhq.business.utils.ObjectCompareUtil;
import com.hxhq.system.api.domain.SysDept;
import com.hxhq.system.domain.SysMenu;
import com.hxhq.system.domain.SysPost;
import com.hxhq.system.domain.SysUserPost;
import com.hxhq.system.domain.SysUserRole;
import com.hxhq.system.form.UserSaveForm;
import com.hxhq.system.service.ISysConfigService;
import com.hxhq.system.service.ISysDeptService;
import com.hxhq.system.service.ISysUserService;
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 org.springframework.util.CollectionUtils;
import com.hxhq.common.core.constant.UserConstants;
import com.hxhq.common.core.exception.ServiceException;
import com.hxhq.common.core.utils.SpringUtils;
import com.hxhq.common.core.utils.StringUtils;
import com.hxhq.common.core.utils.bean.BeanValidators;
import com.hxhq.common.datascope.annotation.DataScope;
import com.hxhq.common.security.utils.SecurityUtils;
import com.hxhq.system.api.domain.SysRole;
import com.hxhq.system.api.domain.SysUser;
import com.hxhq.system.mapper.SysPostMapper;
import com.hxhq.system.mapper.SysRoleMapper;
import com.hxhq.system.mapper.SysUserMapper;
import com.hxhq.system.mapper.SysUserPostMapper;
import com.hxhq.system.mapper.SysUserRoleMapper;

/**
 * 用户 业务层处理
 * 
 * @author hxhq
 */
@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 SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    protected Validator validator;

    @Autowired
    private ISystemLogService systemLogService;

    @Autowired
    private IRoleChangeService roleChangeService;

    /**
     * 根据条件分页查询用户列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息//    @DataScope(deptAlias = "d", userAlias = "u")
     */
    @Override

    public List<SysUser> selectUserList(SysUser user)
    {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息//    @DataScope(deptAlias = "d", userAlias = "u")
     */
    @Override

    public List<SysUser> selectAllocatedList(SysUser user)
    {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息//    @DataScope(deptAlias = "d", userAlias = "u")
     */
    @Override

    public List<SysUser> selectUnallocatedList(SysUser user)
    {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName)
    {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户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);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     * 
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName)
    {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

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

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean 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 boolean 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 = userMapper.selectUserList(user);
            if (StringUtils.isEmpty(users))
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     * 
     * @param form 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(UserSaveForm form)
    {
        checkPassword(SecurityUtils.getLoginUser().getSysUser(),form.getSign().getQmrmm(),false);
        SysUser user = form.getUser();
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);

        systemLogService.saveInfo(user.getNickName(),null,"新增用户","Create User",null,null,SecurityUtils.getUserId(),SecurityUtils.getNickName(),SecurityUtils.getUsername(),form.getSign().getRemark());
        return rows;
    }

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

    /**
     * 修改保存用户信息
     * 
     * @param form 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(UserSaveForm form)
    {
        SysUser user = form.getUser();
        SignForm sign = form.getSign();
        checkPassword(SecurityUtils.getLoginUser().getSysUser(),sign.getQmrmm(),false);

        List<SystemLog> logList = getModifyLogList(user, sign);
        if(logList.size()>0){
            systemLogService.saveBatch(logList);
        }

        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);

        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(Long userId, Long[] roleIds)
    {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     * 
     * @param form 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(UserSaveForm form)
    {
        checkPassword(SecurityUtils.getLoginUser().getSysUser(),form.getSign().getQmrmm(),false);
        SysUser user = form.getUser();
        SysUser info = selectUserById(user.getUserId());

        int row = userMapper.updateUserStatus(user.getUserId(), user.getStatus());
        systemLogService.saveInfo(info.getNickName(),null,"0".equals(user.getStatus())?"启用用户":"禁用用户","0".equals(user.getStatus())?"Enable User":"Disable User",null,null,SecurityUtils.getUserId(),SecurityUtils.getNickName(),SecurityUtils.getUsername(),form.getSign().getRemark());
        return row;
    }

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

    /**
     * 修改用户头像
     * 
     * @param userId 用户ID
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(Long userId, String avatar)
    {
        return userMapper.updateUserAvatar(userId, avatar) > 0;
    }

    /**
     * 更新用户登录信息（IP和登录时间）
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean updateLoginInfo(SysUser user)
    {
        return userMapper.updateLoginInfo(user) > 0;
    }

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

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

    /**
     * 新增用户角色信息
     * 
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     * 
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(Long userId)
    {
        SysUser sysUser =selectUserById(userId);
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        int row = userMapper.deleteUserById(userId);
        systemLogService.saveInfo(sysUser.getNickName(),null,"删除用户","Remove User",null,null,SecurityUtils.getUserId(),SecurityUtils.getNickName(),SecurityUtils.getUsername(),null);
        return row;
    }

    /**
     * 批量删除用户信息
     * 
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long[] userIds)
    {
        for (Long userId : userIds)
        {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     * 
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, user);
                    deptService.checkDeptDataScope(user.getDeptId());
                    String password = configService.selectConfigByKey("sys.user.initPassword");
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    deptService.checkDeptDataScope(user.getDeptId());
                    user.setUserId(u.getUserId());
                    user.setDeptId(u.getDeptId());
                    user.setUpdateBy(operName);
                    userMapper.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();
    }

    @Override
    public List<Long> selectAllocatedListSimple(Long roleId) {
        return userMapper.selectAllocatedListSimple(roleId);
    }

    @Override
    public List<SysUser> selectTransferAllList() {
        return userMapper.selectTransferAllList();
    }

    @Override
    public List<DeptUserTreeDto> selectDeptAndUser() {
        return userMapper.selectDeptAndUser();
    }

    @Override
    public List<DeptUserTreeDto> selectStudyUser(Long studyId, Long studySubjectId, Long deptId, String permit) {
        return userMapper.selectStudyUser(studyId,studySubjectId,deptId,permit);
    }

    @Override
    public Boolean checkPassword(Long userId, String password, Boolean needName) {
        SysUser sysUser = selectUserById(userId);
        if(sysUser==null){
            throw new ServiceException("用户不存在");
        }
        return checkPassword(sysUser,password,needName);
    }

    @Override
    public Boolean checkPassword(SysUser user, String password, Boolean needName) {
        if(SecurityUtils.matchesPassword(password,user.getPassword())){
            return true;
        }
        throw new ServiceException((needName?user.getNickName():"")+"密码错误");
    }

    @Override
    public List<BzListDto> selectBzList() {
        return userMapper.selectBzList();
    }

    @Override
    public List<String> selectNamesByIdList(List<Long> idList) {
        return userMapper.selectNamesByIdList(idList);
    }

    private List<SystemLog> getModifyLogList(SysUser info, SignForm sign){
        SysUser old = selectUserById(info.getUserId());
        List<Long> oldRoleIdList = roleMapper.selectRoleListByUserId(info.getUserId());
        List<SystemLog> list = new ArrayList<>();
        List<ObjectCompareUtil.FieldChange> fieldChanges = ObjectCompareUtil.compareObjects(old, info);
        for (ObjectCompareUtil.FieldChange fieldChange : fieldChanges) {
            SystemLog log = getLogInfo(old,sign);
            log.setJcnr(fieldChange.toString());
            log.setJcnrEn(fieldChange.toEnString());
            list.add(log);
        }
        if(!info.getStatus().equals(old.getStatus())){
            SystemLog log = getLogInfo(old,sign);
            log.setJcnr("[{\"name\":\"字段名\",\"value\":\"状态\"},{\"name\":\"原值\",\"value\":\""+("0".equals(old.getStatus())?"启用":"禁用")+"\"},{\"name\":\"新值\",\"value\":\""+("0".equals(info.getStatus())?"启用":"禁用")+"\"}]");
            log.setJcnrEn("[{\"name\":\"Field\",\"value\":\"Status\"},{\"name\":\"Old Value\",\"value\":\""+("0".equals(old.getStatus())?"Enabled":"Disabled")+"\"},{\"name\":\"New Value\",\"value\":\""+("0".equals(info.getStatus())?"Enabled":"Disabled")+"\"}]");
            list.add(log);
        }
        if(!info.getDeptId().equals(old.getDeptId())){
            SysDept oldDept = deptService.selectDeptById(old.getDeptId());
            SysDept newDept = deptService.selectDeptById(info.getDeptId());

            SystemLog log = getLogInfo(old,sign);
            log.setJcnr("[{\"name\":\"字段名\",\"value\":\"所属部门/学科\"},{\"name\":\"原值\",\"value\":\""+oldDept.getDeptName()+"\"},{\"name\":\"新值\",\"value\":\""+newDept.getDeptName()+"\"}]");
            log.setJcnrEn("[{\"name\":\"Field\",\"value\":\"Department\"},{\"name\":\"Old Value\",\"value\":\""+oldDept.getDeptName()+"\"},{\"name\":\"New Value\",\"value\":\""+newDept.getDeptName()+"\"}]");
            list.add(log);
        }
        //判断菜单修改
        Boolean updateRole = false;
        if(info.getRoleIds().length!=oldRoleIdList.size()){
            updateRole = true;
        }else{
            for(Long newMenuId : info.getRoleIds()){
                if(!oldRoleIdList.contains(newMenuId)){
                    updateRole = true;
                    break;
                }
            }
        }
        if(updateRole){
            List<SysRole> allRoleList = roleMapper.selectRoleList(new SysRole());
            List<SysRole> oldRoleList = new ArrayList<>();
            List<SysRole> newRoleList = new ArrayList<>();
            if(info.getRoleIds()!=null && info.getRoleIds().length>0){
                for(Long newRoleId : info.getRoleIds()){
                    newRoleList.add(allRoleList.stream().filter(o->o.getRoleId().equals(newRoleId)).collect(Collectors.toList()).get(0));
                }
            }
            if(oldRoleIdList.size()>0){
                for(Long oldRoleId : oldRoleIdList){
                    oldRoleList.add(allRoleList.stream().filter(o->o.getRoleId().equals(oldRoleId)).collect(Collectors.toList()).get(0));
                }
            }
            List<String> oldRoleNameList = oldRoleList.stream().map(o->o.getRoleName()).collect(Collectors.toList());
            List<String> bghList = oldRoleList.stream().map(o->o.getRoleName()).collect(Collectors.toList());
            List<String> addNameList = new ArrayList<>();
            List<String> deleteNameList = new ArrayList<>();
            for(SysRole newRole : newRoleList){
                if(!oldRoleIdList.contains(newRole.getRoleId())){
                    addNameList.add(newRole.getRoleName());
                    bghList.add(newRole.getRoleName());
                }
            }
            List<Long> newMenuIdList = Arrays.asList(info.getRoleIds());
            for(SysRole oldRole : oldRoleList){
                if(!newMenuIdList.contains(oldRole.getRoleId())){
                    deleteNameList.add(oldRole.getRoleName());
                    bghList.remove(oldRole.getRoleName());
                }
            }
            if(addNameList.size()>0 || deleteNameList.size()>0){
                SystemLog log = getLogInfo(old,sign);
                log.setJcnr((addNameList.size()>0?("新增角色："+String.join(",",addNameList)):"")+(deleteNameList.size()>0?("；删除角色："+String.join(",",deleteNameList)):"")+(StringUtils.isBlank(sign.getRemark())?"":"；备注："+sign.getRemark()));
                log.setJcnrEn((addNameList.size()>0?("Add Role："+String.join(",",addNameList)):"")+(deleteNameList.size()>0?("；Remove Role："+String.join(",",deleteNameList)):"")+(StringUtils.isBlank(sign.getRemark())?"":"；Comment："+sign.getRemark()));
                list.add(log);
            }
            roleChangeService.saveInfo(info.getUserId(),String.join(",",oldRoleNameList),String.join(",",bghList),sign.getRemark());
        }
        return list;
    }

    /**
     * 获取日志基础信息
     * @return
     */
    private SystemLog getLogInfo(SysUser sysUser,SignForm signForm){
        SystemLog log = new SystemLog();
        log.setName(sysUser.getNickName());
        log.setNameEn(sysUser.getNickName());
        log.setJcmc("编辑用户");
        log.setJcmcEn("Edit User");
        log.setQmrId(SecurityUtils.getUserId());
        log.setQmrMc(SecurityUtils.getNickName());
        log.setQmrMcEn(SecurityUtils.getUsername());
        log.setRemark(signForm.getRemark());
        return log;
    }
}
