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

import cn.hutool.core.collection.CollectionUtil;
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.EYesNo;
import com.hzs.common.domain.system.sys.SysMenuColumn;
import com.hzs.system.sys.mapper.SysMenuColumnMapper;
import com.hzs.system.sys.service.ISysMenuColumnService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 菜单字段表 服务实现类
 *
 * @author hzs
 * @since 2023-06-07
 */
@Service
public class SysMenuColumnServiceImpl extends ServiceImpl<SysMenuColumnMapper, SysMenuColumn> implements ISysMenuColumnService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveData(Long menuId, List<SysMenuColumn> paramList, Long userId) {
        // 获取之前已经存在的数据ID
        List<Integer> pkIdList = paramList.stream().map(SysMenuColumn::getPkId).filter(Objects::nonNull).collect(Collectors.toList());

        // 删除旧菜单字段数据
        UpdateWrapper<SysMenuColumn> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PK_MENU", menuId);
        if (CollectionUtil.isNotEmpty(pkIdList)) {
            updateWrapper.notIn(SystemFieldConstants.PK_ID, pkIdList);
        }
        updateWrapper.eq(SystemFieldConstants.DEL_FLAG, EYesNo.YES.getIntValue());
        updateWrapper.set(SystemFieldConstants.DEL_FLAG, EYesNo.NO.getIntValue());
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, new Date());
        this.update(updateWrapper);

        // 插入或更新数据
        baseMapper.insertOrUpdateBatch(menuId, paramList, userId);
    }

}
