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.ObjectTypeHistoryMapper;
import com.persagy.dmp.rwd.version.entity.ObjectTypeHistory;
import com.persagy.dmp.rwd.version.service.IObjectTypeHistoryService;
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 ObjectTypeHistoryServiceImpl implements IObjectTypeHistoryService {

    @Resource
    private ObjectTypeHistoryMapper dao;

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

    @Override
    public void copyByVersion(String srcVersion, String version) {
        /**
         * TODO 目前是以编辑工具中数据为主体操作。应调整为从数据字典中读取当前数据
         * 这样可以避免非编辑工具触发的数据字典编辑场景，产生的数据不一致
         * 同时也可以通过调整数据字典服务源来支持为其他数据字典服务提供编辑服务
         **/
        dao.copyByVersion(srcVersion, version);
    }

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

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

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