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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.persagy.dmp.basic.constant.DigitalMessageConstant;
import com.persagy.dmp.common.constant.ValidEnum;
import com.persagy.dmp.digital.entity.ObjectRelation;
import com.persagy.dmp.rwd.basic.utils.DigitalCommonUtils;
import com.persagy.dmp.rwd.basic.utils.DigitalMessageHelper;
import com.persagy.dmp.rwd.digital.dao.ObjectRelationMapper;
import com.persagy.dmp.rwd.digital.service.IObjectRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 关系数据 实现类
 * @author Charlie Yu
 * @date 2021-07-08
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ObjectRelationServiceImpl extends ServiceImpl<ObjectRelationMapper, ObjectRelation> implements IObjectRelationService  {

    @Resource
    private ObjectRelationMapper dao;

    @Autowired
    private DigitalMessageHelper messageSender;

    @Autowired
    private IObjectRelationService iService;

    /**
     * 查询对象关系数据
     * @param queryWrapper 查询条件
     * @return
     */
    @Override
    public List<ObjectRelation> queryByCondition(Wrapper<ObjectRelation> queryWrapper) {
        return dao.selectList(queryWrapper);
    }

    @Override
    public Integer queryCount(Wrapper<ObjectRelation> queryWrapper) {
        return dao.selectCount(queryWrapper);
    }

    @Override
    public Page queryByCondition(Page page, Wrapper<ObjectRelation> queryWrapper) {
        return dao.selectPage(page, queryWrapper);
    }

    /**
     * 新增关系数据
     * @param voList 待新增数据
     * @return
     */
    @Override
    public List<ObjectRelation> insert(List<ObjectRelation> voList) {
        //创建默认的图实例id
        createGraphId(voList);
        //数据重复性校验,若存在重复数据，填充关系ID
        checkRepeatData(voList,false);
        //新增关系数据
        iService.saveOrUpdateBatch(voList);
        //发送新增消息
        voList.forEach(vo->{
            messageSender.sendMessage(DigitalMessageConstant.OPERATE_AFTER_INSERT, null, vo, false);
        });
        return voList;
    }

    /**
     * 数据重复性校验，存在重复数据时，自动填充关系ID，作更新操作
     * @param voList
     */
    private Boolean checkRepeatData(List<ObjectRelation> voList,Boolean isUpdate){
        if(CollUtil.isEmpty(voList)){
            return true;
        }
        Boolean flag = true;
        for (ObjectRelation relation : voList) {
            //条件查询关系数据
            LambdaQueryWrapper<ObjectRelation> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ObjectRelation::getGroupCode,relation.getGroupCode());
            wrapper.eq(ObjectRelation::getProjectId,relation.getProjectId());
            wrapper.eq(ObjectRelation::getGraphCode, relation.getGraphCode());
            wrapper.eq(ObjectRelation::getRelCode,relation.getRelCode());
            wrapper.eq(ObjectRelation::getObjFrom,relation.getObjFrom());
            wrapper.eq(ObjectRelation::getObjTo,relation.getObjTo());
            wrapper.eq(ObjectRelation::getValid,true);
            List<ObjectRelation> relationList = queryByCondition(wrapper);

            if(CollUtil.isNotEmpty(relationList)){
                //新增关系时数据已存在，待添加数据填充已存在的ID
                if(!isUpdate){
                    relation.setId(relationList.get(0).getId());
                    continue;
                }
                //判断更新时关系数据是否重复
                String existId = relationList.get(0).getId();
                if(isUpdate && !relation.getId().equals(existId)){
                    flag = false;
                }
            }else{
                if(!isUpdate){
                    //新增时关系数据不存在，设置自增ID
                    relation.setId(IdUtil.simpleUUID());
                }
            }
        }
        return flag;
    }
    /**
     * 创建默认的图实例id
     * @param voList
     */
    private void createGraphId(List<ObjectRelation> voList){
        if(CollUtil.isEmpty(voList)){
            return;
        }
        for (ObjectRelation objectRelation : voList) {
            String graphCode = objectRelation.getGraphCode();
            String graphId = DigitalCommonUtils.getDefaultGraphIdByGraphCode(graphCode);
            objectRelation.setGraphId(graphId);
        }
    }

    /**
     * 修改关系数据
     * @param voList 修改条件
     * @return
     */
    @Override
    public List<ObjectRelation> update(List<ObjectRelation> voList) throws Exception{
        //数据重复性校验
        Boolean flag = checkRepeatData(voList, true);
        if(!flag){
            throw new Exception("存在重复的关系数据");
        }
        //修改关系数据
        iService.saveOrUpdateBatch(voList);
        //发送修改消息
        voList.forEach(vo->{
            messageSender.sendMessage(DigitalMessageConstant.OPERATE_AFTER_UPDATE, null, vo, false);
        });
        return voList;
    }

    /**
     * 删除关系数据
     * @param wrapper 删除条件
     * @return
     */
    @Override
    public List<ObjectRelation> delete(QueryWrapper wrapper) {
        //根据条件查询有效关系数据
        wrapper.eq("valid",ValidEnum.TRUE.getType());
        List<ObjectRelation> list = dao.selectList(wrapper);
        if(list == null || list.size()<=0){
            return new ArrayList<>();
        }
        //批量删除关系数据
        for (ObjectRelation relation : list) {
            relation.setValid(ValidEnum.FALSE.getType());
        }
        iService.saveOrUpdateBatch(list);
        //发送删除消息
        list.forEach(vo->{
            messageSender.sendMessage(DigitalMessageConstant.OPERATE_AFTER_DELETE, null, vo, false);
        });
        return list;
    }

}
