package com.pannk.mms.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pannk.mms.common.base.Constant;
import com.pannk.mms.common.base.PageData;
import com.pannk.mms.common.base.Query;
import com.pannk.mms.common.base.Result;
import com.pannk.mms.common.utils.RedisUtil;
import com.pannk.mms.common.utils.TokenUtil;
import com.pannk.mms.modules.sys.dao.SysUserMapper;
import com.pannk.mms.modules.sys.entity.SysRoleEntity;
import com.pannk.mms.modules.sys.entity.SysUserEntity;
import com.pannk.mms.modules.sys.entity.SysUserRoleEntity;
import com.pannk.mms.modules.sys.service.SysRoleService;
import com.pannk.mms.modules.sys.service.SysUserRoleService;
import com.pannk.mms.modules.sys.service.SysUserService;
import com.pannk.mms.modules.sys.vo.LoginForm;
import com.pannk.mms.modules.sys.vo.SysUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
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.List;
import java.util.Map;

/**
 * 系统用户服务
 * Created by wolf on 20-11-2.
 */
@Slf4j
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;


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

    @Override
    public Result login(LoginForm loginForm) {
        SysUserEntity sysUserEntity = queryByUserName(loginForm.getUserName());
        if (sysUserEntity == null || !sysUserEntity.getPassword().equals(loginForm.getPassword())) {
            return Result.error("账号或密码不正确");
        }
        if (sysUserEntity.getStatus() == 1) {
            return Result.error("账号被锁定,请联系管理员处理");
        }
        String token = TokenUtil.generateToken();
        redisUtil.set(Constant.USER_CACHE + token, sysUserEntity, Constant.EXPIRE);
        return Result.success(token);
    }

    @Override
    public SysUserInfo queryUserInfo(Long id) {
        SysUserEntity sysUserEntity = getById(id);
        SysUserInfo sysUserInfo = new SysUserInfo();
        if (sysUserEntity == null) {
            return null;
        }
        List<SysRoleEntity> roles = sysRoleService.queryUserRole(sysUserEntity.getId());
        BeanUtils.copyProperties(sysUserEntity, sysUserInfo);
        sysUserInfo.setRoles(roles);
        List<Long> roleIdList = new ArrayList<>();
        for (SysRoleEntity sre : roles) {
            roleIdList.add(sre.getId());
        }
        sysUserInfo.setRoleIdList(roleIdList);
        return sysUserInfo;
    }

    @Override
    public void logout(Long userId, String token) {
        redisUtil.del(Constant.USER_CACHE + token);
        redisUtil.del(Constant.PERMS_CAHCE + userId);
    }


    @Override
    public PageData<SysUserEntity> queryPage(Map<String, Object> params) {
        String userName = (String) params.get("userName");
        IPage<SysUserEntity> page = this.page(new Query<SysUserEntity>().getPage(params), new
                QueryWrapper<SysUserEntity>().like(StringUtils.isNotEmpty(userName), "user_name", userName));
        return new PageData<>(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUserInfo(SysUserInfo sysUserInfo) {
        this.updateById(sysUserInfo);
        sysUserRoleService.remove(new QueryWrapper<SysUserRoleEntity>().eq("user_id", sysUserInfo.getId()));
        saveUserRole(sysUserInfo);
    }

    /**
     * 保存用户角色
     *
     * @param sysUserInfo 用户信息
     */
    private void saveUserRole(SysUserInfo sysUserInfo) {
        List<Long> sysUserRoleIdList = sysUserInfo.getRoleIdList();
        if (sysUserRoleIdList.size() > 0) {
            List<SysUserRoleEntity> list = new ArrayList<>(sysUserRoleIdList.size());
            for (Long roleId : sysUserRoleIdList) {
                SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
                sysUserRoleEntity.setUserId(sysUserInfo.getId());
                sysUserRoleEntity.setRoleId(roleId);
                list.add(sysUserRoleEntity);
            }
            sysUserRoleService.saveBatch(list);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveUserInfo(SysUserInfo sysUserInfo) {
        sysUserInfo.setPassword(Constant.INIT_PASSWORD);
        save(sysUserInfo);
        saveUserRole(sysUserInfo);
    }
}
