package com.hzs.system.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.enums.EDelFlag;
import com.hzs.common.domain.system.sys.SysUserMenu;
import com.hzs.system.sys.mapper.SysUserMenuMapper;
import com.hzs.system.sys.param.SysUserMenuParam;
import com.hzs.system.sys.param.SysUserMenuQueryParam;
import com.hzs.system.sys.service.ISysUserMenuService;
import com.hzs.system.sys.vo.SysUserMenuDetailVO;
import com.hzs.system.sys.vo.SysUserMenuQueryVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户菜单关联 服务实现类
 *
 * @author hzs
 * @since 2023-01-06
 */
@Service
public class SysUserMenuServiceImpl extends ServiceImpl<SysUserMenuMapper, SysUserMenu> implements ISysUserMenuService {

    @Override
    public List<SysUserMenuQueryVO> queryList(SysUserMenuQueryParam param) {
        return baseMapper.queryList(param);
    }

    @Override
    public SysUserMenuDetailVO queryDetail(Long userId) {
        return baseMapper.queryDetail(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveSysUserMenu(SysUserMenuParam param, Long userId) {
        Date nowDate = new Date();

        // 清除管理员之前的旧数据，防止出现重复
        UpdateWrapper<SysUserMenu> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("USER_ID", param.getUserIdList());
        updateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.DELETE.getValue());
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, nowDate);
        baseMapper.update(null, updateWrapper);

        // 入库管理员菜单配置
        for (Long tmpUserId : param.getUserIdList()) {
            List<SysUserMenu> sysUserMenuList = new ArrayList<>();
            for (Long tmpMenuId : param.getMenuIdList()) {
                SysUserMenu sysUserMenu = new SysUserMenu();
                sysUserMenu.setUserId(tmpUserId);
                sysUserMenu.setMenuId(tmpMenuId);
                sysUserMenu.setPkCreator(userId);
                sysUserMenu.setCreationTime(nowDate);
                sysUserMenuList.add(sysUserMenu);
            }
            baseMapper.insertUserMenuBatch(sysUserMenuList);
        }
        return true;
    }

}
