package com.persagy.dmp.rwd.version.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.persagy.dmp.common.constant.ValidEnum;
import com.persagy.dmp.common.exception.BusinessException;
import com.persagy.dmp.rwd.version.dao.ObjectInfoHistoryMapper;
import com.persagy.dmp.rwd.version.entity.ObjectInfoHistory;
import com.persagy.dmp.rwd.version.service.IObjectInfoHistoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 信息点历史 实现类
 * @author Charlie Yu
 * @date 2021-06-23
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ObjectInfoHistoryServiceImpl implements IObjectInfoHistoryService {

    @Resource
    private ObjectInfoHistoryMapper dao;

    @Override
    public ObjectInfoHistory insert(ObjectInfoHistory history) {
        dao.insert(history);
        return history;
    }

    @Override
    public void copyByVersion(String srcVersion, String version) {
        dao.copyByVersion(srcVersion, version);
    }

    @Override
    public ObjectInfoHistory update(ObjectInfoHistory history) {
        dao.updateById(history);
        return history;
    }

    @Override
    public void delete(String id) {
        ObjectInfoHistory vo = dao.selectById(id);
        vo.setValid(ValidEnum.FALSE.getType());
        dao.updateById(vo);
    }

    @Override
    public void validateOnVersionDelete(String version) {
        // 查询
        LambdaQueryWrapper<ObjectInfoHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ObjectInfoHistory::getVersion, version);
        queryWrapper.eq(ObjectInfoHistory::getValid, ValidEnum.TRUE.getType());
        queryWrapper.isNotNull(ObjectInfoHistory::getOperator);
        Integer count = dao.selectCount(queryWrapper);
        if(count != null && count > 0) {
            throw new BusinessException("该版本有信息点变更记录不可直接删除!");
        }
    }
}
