package com.liangjian.dataplatform.member.dao;

import com.liangjian.dataplatform.member.entity.po.BasicEntity;
import com.liangjian.dataplatform.member.entity.po.LifeCycleObject;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author: 黄子奇
 * @Date: 2019/10/7 10:53
 */
public interface JpaLifeCycleRepository<T extends BasicEntity,ID> extends JpaRepository<T,ID>, JpaSpecificationExecutor<T> {
    /**
     * 带有生命周期的保存函数
     * @param s
     * @param <S>
     * @return
     */
    default <S extends T> S saveWithCycle(S s) {
        if (s.isNew()) {
            s.beforeCreate();
            S ns = this.save(s);
            ns.afterCreate();
            return ns;
        } else {
            s.beforeUpdate();
            S ns = this.save(s);
            ns.afterUpdate();
            return ns;
        }
    }

    /**
     * 带有生命周期的删除操作
     * @param t
     */
    default void deleteWithCycle(T t) {
        t.beforeDelete();
        this.delete(t);
        t.afterDelete();
    }

    /**
     * 带有生命周期的保存函数
     * @param iterable
     * @param <S>
     * @return
     */
    default  <S extends T> List<S> saveAllWithCycle(Iterable<S> iterable) {
        List<S> insert = new ArrayList<>();
        List<S> update = new ArrayList<>();
        for (S s : iterable) {
            if (s.isNew()) {
                s.beforeCreate();
                insert.add(s);
            } else {
                s.beforeUpdate();
                update.add(s);
            }
        }
        insert = this.saveAll(insert);
        update = this.saveAll(update);
        for (S s : insert) {
            s.afterCreate();
        }
        for (S s : update) {
            s.afterUpdate();
        }
        List<S> list = new ArrayList<>();
        list.addAll(insert);
        list.addAll(update);
        return list;
    }
}
