package com.yeejoin.equipmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.equipmanage.common.entity.DynamicFormInstance;
import com.yeejoin.equipmanage.common.exception.BaseException;
import com.yeejoin.equipmanage.mapper.EqDynamicFormInstanceMapper;
import com.yeejoin.equipmanage.service.IEqDynamicFormInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 动态表单实例表 服务实现类
 *
 * @author duanwei
 * @date 2021-03-08
 */
@Service
public class EqEqDynamicFormInstanceServiceImpl extends ServiceImpl<EqDynamicFormInstanceMapper, DynamicFormInstance> implements IEqDynamicFormInstanceService {

    @Autowired
    Sequence sequence;

    @Override
    public Long saveInstanceBatch(List<DynamicFormInstance> formInstances) {
        Long instanceId = sequence.nextId();
        formInstances.forEach(s -> {
            s.setId(sequence.nextId());
            s.setInstanceId(instanceId);
            s.setCreateDate(new Date());
        });
        this.saveOrUpdateBatch(formInstances);
        return instanceId;
    }

    @Override
    public void updateInstanceBatch(Long instanceId, List<DynamicFormInstance> formInstances) {
        List<DynamicFormInstance> instances = this.list(new LambdaQueryWrapper<DynamicFormInstance>()
                .eq(DynamicFormInstance::getInstanceId, instanceId));
        if (instances.isEmpty()) {
            throw new BaseException("该实例不存在");
        }
        formInstances.forEach(f -> {
            f.setInstanceId(instanceId);
            f.setCreateDate(new Date());
        });
        this.saveOrUpdateBatch(formInstances);
    }
}
