package com.qmth.sop.business.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.qmth.sop.business.bean.result.SysLevelResult;
import com.qmth.sop.business.entity.SysLevel;
import com.qmth.sop.business.entity.SysLevelRole;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.mapper.SysLevelMapper;
import com.qmth.sop.business.service.SysLevelRoleService;
import com.qmth.sop.business.service.SysLevelService;
import com.qmth.sop.common.util.ServletUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 档位表 服务实现.
 *
 * @author: shudonghui
 * @date: 2023-08-02 14:21:11
 * @version: 1.0
 * @email: shudonghui@qmth.com.cn
 * @Company: www.qmth.com.cn
 */
@Service
public class SysLevelServiceImpl extends ServiceImpl<SysLevelMapper, SysLevel> implements SysLevelService {

    @Resource
    SysLevelRoleService sysLevelRoleService;

    /**
     * 查询列表
     *
     * @param iPage
     * @return
     */
    @Override
    public IPage<SysLevelResult> query(IPage<Map> iPage) {
        IPage<SysLevelResult> resultIPage = this.baseMapper.query(iPage);
        resultIPage.getRecords().forEach(e -> {
            e.setRoleList(sysLevelRoleService.getList(e.getId()));
        });
        return resultIPage;
    }

    /**
     * 新增档位表
     *
     * @param sysLevel
     */
    @Override
    @Transactional
    public void add(SysLevelResult sysLevel) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        sysLevel.setCreateId(sysUser.getId());
        sysLevel.setCreateTime(System.currentTimeMillis());
        this.saveOrUpdate(sysLevel);
        sysLevel.getRoleList().forEach(e->{
            e.setLevelId(sysLevel.getId());
            sysLevelRoleService.saveOrUpdate(e);
        });
    }

    /**
     * 修改档位表
     *
     * @param sysLevel
     */
    @Override
    @Transactional
    public void update(SysLevelResult sysLevel) {
        this.saveOrUpdate(sysLevel);
        sysLevelRoleService.remove(new QueryWrapper<SysLevelRole>().lambda().eq(SysLevelRole::getLevelId, sysLevel.getId()));
        sysLevel.getRoleList().forEach(e->{
            e.setLevelId(sysLevel.getId());
            sysLevelRoleService.saveOrUpdate(e);
        });

    }

    /**
     * 删除档位表
     *
     * @param id
     */
    @Override
    @Transactional
    public void delete(Long id) {
        sysLevelRoleService.remove(new QueryWrapper<SysLevelRole>().lambda().eq(SysLevelRole::getLevelId, id));
        this.removeById(id);
    }

}