package com.inspect.system.service.impl;

import com.inspect.base.core.constant.CacheConstants;
import com.inspect.base.core.exception.ServiceException;
import com.inspect.base.core.utils.SpringUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.bean.BeanValidators;
import com.inspect.common.aspect.annotation.DataScope;
import com.inspect.base.redis.service.RedisService;
import com.inspect.common.security.utils.SecurityUtils;
import com.inspect.system.base.domain.SysRole;
import com.inspect.system.base.domain.SysUser;
import com.inspect.system.domain.SysPost;
import com.inspect.system.domain.SysUserPost;
import com.inspect.system.domain.SysUserRole;
import com.inspect.system.mapper.SysPostMapper;
import com.inspect.system.mapper.SysRoleMapper;
import com.inspect.system.mapper.SysUserMapper;
import com.inspect.system.mapper.SysUserPostMapper;
import com.inspect.system.mapper.SysUserRoleMapper;
import com.inspect.system.service.ISysConfigService;
import com.inspect.system.service.ISysUserService;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.validation.Validator;

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;

@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
    private final SysUserMapper userMapper;
    private final SysRoleMapper roleMapper;
    private final SysPostMapper postMapper;
    private final SysUserRoleMapper userRoleMapper;
    private final SysUserPostMapper userPostMapper;
    private final ISysConfigService configService;
    protected final Validator validator;
    @Resource
    private RedisService redisService;

    public SysUserServiceImpl(SysUserMapper userMapper, SysRoleMapper roleMapper, SysPostMapper postMapper, SysUserRoleMapper userRoleMapper, SysUserPostMapper userPostMapper, ISysConfigService configService, Validator validator) {
        this.userMapper = userMapper;
        this.roleMapper = roleMapper;
        this.postMapper = postMapper;
        this.userRoleMapper = userRoleMapper;
        this.userPostMapper = userPostMapper;
        this.configService = configService;
        this.validator = validator;
    }

    @DataScope(
            deptAlias = "d",
            userAlias = "u"
    )
    public List<SysUser> selectUserList(SysUser user) {
        return this.userMapper.selectUserList(user);
    }

    @DataScope(
            deptAlias = "d",
            userAlias = "u"
    )
    public List<SysUser> selectAllocatedList(SysUser user) {
        return this.userMapper.selectAllocatedList(user);
    }

    @DataScope(
            deptAlias = "d",
            userAlias = "u"
    )
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return this.userMapper.selectUnallocatedList(user);
    }

    public SysUser selectUserByUserName(String userName) {
        return this.userMapper.selectUserByUserName(userName);
    }

    public SysUser selectUserById(Long userId) {
        return this.userMapper.selectUserById(userId);
    }

    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = this.roleMapper.selectRolesByUserName(userName);
        return CollectionUtils.isEmpty(list) ? "" : (String) list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    public String selectUserPostGroup(String userName) {
        List<SysPost> list = this.postMapper.selectPostsByUserName(userName);
        return CollectionUtils.isEmpty(list) ? "" : (String) list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    public String checkUserNameUnique(String userName) {
        int count = this.userMapper.checkUserNameUnique(userName);
        return count > 0 ? "1" : "0";
    }

    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = this.userMapper.checkPhoneUnique(user.getPhonenumber());
        return StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue() ? "1" : "0";
    }

    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = this.userMapper.checkEmailUnique(user.getEmail());
        return StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue() ? "1" : "0";
    }

    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    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("没有权限访问用户数据！");
            }
        }

    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public int insertUser(SysUser user) {
        int rows = this.userMapper.insertUser(user);
        this.insertUserPost(user);
        this.insertUserRole(user);
        return rows;
    }

    public boolean registerUser(SysUser user) {
        return this.userMapper.insertUser(user) > 0;
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        this.userRoleMapper.deleteUserRoleByUserId(userId);
        this.insertUserRole(user);
        this.userPostMapper.deleteUserPostByUserId(userId);
        this.insertUserPost(user);
        return this.userMapper.updateUser(user);
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public void insertUserAuth(Long userId, Long[] roleIds) {
        this.userRoleMapper.deleteUserRoleByUserId(userId);
        this.insertUserRole(userId, roleIds);
    }

    public int updateUserStatus(SysUser user) {
        return this.userMapper.updateUser(user);
    }

    public int updateUserProfile(SysUser user) {
        return this.userMapper.updateUser(user);
    }

    public boolean updateUserAvatar(String userName, String avatar) {
        return this.userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    public int resetPwd(SysUser user) {
        return this.userMapper.updateUser(user);
    }

    public int resetUserPwd(String userName, String password) {
        return this.userMapper.resetUserPwd(userName, password);
    }

    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            List<SysUserRole> list = new ArrayList<>();

            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }

            if (!list.isEmpty()) {
                this.userRoleMapper.batchUserRole(list);
            }
        }

    }

    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            List<SysUserPost> list = new ArrayList<>();

            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }

            if (!list.isEmpty()) {
                this.userPostMapper.batchUserPost(list);
            }
        }

    }

    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotNull(roleIds)) {
            List<SysUserRole> list = new ArrayList<>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }

            if (!list.isEmpty()) {
                this.userRoleMapper.batchUserRole(list);
            }
        }

    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public int deleteUserById(Long userId) {
        this.userRoleMapper.deleteUserRoleByUserId(userId);
        this.userPostMapper.deleteUserPostByUserId(userId);
        return this.userMapper.deleteUserById(userId);
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            this.checkUserAllowed(new SysUser(userId));
            this.checkUserDataScope(userId);
        }

        this.userRoleMapper.deleteUserRole(userIds);
        this.userPostMapper.deleteUserPost(userIds);
        return this.userMapper.deleteUserByIds(userIds);
    }

    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operateName) {
        if (!StringUtils.isNull(userList) && !userList.isEmpty()) {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder successMsg = new StringBuilder();
            StringBuilder failureMsg = new StringBuilder();
            String password = this.configService.selectConfigByKey("sys.user.initPassword");

            for (SysUser user : userList) {
                try {
                    SysUser u = this.userMapper.selectUserByUserName(user.getUserName());
                    if (StringUtils.isNull(u)) {
                        BeanValidators.validateWithException(this.validator, user);
                        user.setPassword(SecurityUtils.encryptPassword(password));
                        user.setCreateBy(operateName);
                        this.insertUser(user);
                        ++successNum;
                        successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                    } else if (isUpdateSupport.booleanValue()) {
                        BeanValidators.validateWithException(this.validator, user, new Class[0]);
                        user.setUpdateBy(operateName);
                        this.updateUser(user);
                        ++successNum;
                        successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                    } else {
                        ++failureNum;
                        failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                    }
                } catch (Exception var13) {
                    ++failureNum;
                    String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                    failureMsg.append(msg + var13.getMessage());
                    log.error(msg, var13);
                }
            }

            if (failureNum > 0) {
                failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                throw new ServiceException(failureMsg.toString());
            } else {
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                return successMsg.toString();
            }
        } else {
            throw new ServiceException("导入用户数据不能为空！");
        }
    }

    public HashMap<String, Object> verifyUserUpdatePassTime(Long userId) {
        HashMap<String, Object> error = new HashMap<>();
        error.put("updatePashFlag", 0);
        SysUser sysUser = this.selectUserById(userId);
        if (sysUser == null) {
            log.error("用户ID：{},对应的用户未查询到", userId);
            return error;
        } else {
            Date passUpdateTime = sysUser.getPassUpdateTime();
            if (null == passUpdateTime) {
                error.put("msg", "初次登录，请修改密码后登录");
                error.put("updatePashFlag", 1);
                return error;
            } else {
                long currTime = System.currentTimeMillis();
                long updateTime = passUpdateTime.getTime();
                String cacheObject = this.redisService.getCacheObject("sys_config:user_pass_update_interval_time");
                long limitTime = 50L;
                if (StringUtils.isNotBlank(cacheObject)) {
                    limitTime = Long.parseLong(cacheObject);
                }

                long limitTimeMills = limitTime * CacheConstants.DAY_MILLIS_TIMES;
//                if (currTime > updateTime && currTime - updateTime >= limitTimeMills) {
//                    error.put("msg", "密码已过期，请修改密码");
//                    error.put("updatePashFlag", 1);
//                    return error;
//                } else {
//                    return error;
//                }
                return error;
            }
        }
    }
}
