/**
 * Copyright (c) 2020 fumeiai All rights reserved.
 * <p>
 * <p>
 * <p>
 * 版权所有，侵权必究！
 */

package com.lz.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lz.common.exception.RRException;
import com.lz.common.utils.Constant;
import com.lz.common.utils.PageUtils;
import com.lz.modules.app.dao.StaffDao;
import com.lz.modules.app.dto.UserDto;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.sys.dao.SysUserDao;
import com.lz.modules.sys.entity.SysUserEntity;
import com.lz.modules.sys.service.SysRoleService;
import com.lz.modules.sys.service.SysUserRoleService;
import com.lz.modules.sys.service.SysUserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private StaffDao staffDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String realName = (String) params.get("realName");
        Long createUserId = (Long) params.get("createUserId");
        String mobile = (String) params.get("mobile");
        String roleName = (String) params.get("roleName");

        int pageSize = 20;
        int currPage = 1;
        if (params.containsKey("limit")) {
            pageSize = Integer.parseInt(params.get("limit").toString());
        }

        if (params.containsKey("page")) {
            currPage = Integer.parseInt(params.get("page").toString());
        }

        List<UserDto> users = sysUserDao.getUserInfos(realName, createUserId, mobile, roleName, pageSize, (currPage - 1) * pageSize);
        int totalCount = sysUserDao.getTotalCount(realName, createUserId, mobile, roleName);
        PageUtils pageInfo = new PageUtils(users, totalCount, pageSize, currPage);

        return pageInfo;
    }

    @Override
    public List<String> queryAllPerms(Long userId) {
        return baseMapper.queryAllPerms(userId);
    }

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    public SysUserEntity queryByUserName(String username) {
        return baseMapper.queryByUserName(username);
    }

    @Override
    @Transactional
    public void saveUser(SysUserEntity user) {
        user.setCreateTime(new Date());
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
        user.setSalt(salt);
        this.save(user);

        //检查角色是否越权
        checkRole(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    @Transactional
    public void update(SysUserEntity user) {
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        } else {
            user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
        }
        this.updateById(user);

        //检查角色是否越权
        checkRole(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    public void deleteBatch(Long[] userId) {
        this.removeByIds(Arrays.asList(userId));
    }

    @Override
    public boolean updatePassword(SysUserEntity user, String password, String newPassword) {
        if (user.getType() == 1) {
            StaffEntity staffEntity = staffDao.selectStaffById(user.getUserId());
            if (!staffEntity.getPassword().equals(password)) {
                return false;
            }
            staffEntity.setPassword(newPassword);
            staffDao.updateStaffById(staffEntity);
        } else {
            SysUserEntity userEntity = new SysUserEntity();
            userEntity.setPassword(newPassword);
            return this.update(userEntity,
                    new QueryWrapper<SysUserEntity>().eq("user_id", user.getUserId()).eq("password", password));
        }
        return true ;
    }

    @Override
    public List<Long> queryMenuIdListByRoleId(Long roleId) {
        return baseMapper.queryMenuIdListByRoleId(roleId);
    }


    @Override
    public List<Long> queryMenuIdListByRoleIds(Set<Long> roleIds) {
        return baseMapper.queryMenuIdListByRoleIds(roleIds);
    }

    /**
     * 检查角色是否越权
     */
    private void checkRole(SysUserEntity user) {
        if (user.getRoleIdList() == null || user.getRoleIdList().size() == 0) {
            return;
        }
        //如果不是超级管理员，则需要判断用户的角色是否自己创建
        if (user.getCreateUserId() == Constant.SUPER_ADMIN) {
            return;
        }

        //查询用户创建的角色列表
        List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

        //判断是否越权
        if (!roleIdList.containsAll(user.getRoleIdList())) {
            throw new RRException("新增用户所选角色，不是本人创建");
        }
    }
}
