package com.yeejoin.amos.boot.module.jg.biz.edit.process.biz;

import com.yeejoin.amos.boot.module.jg.api.dto.ChangeDataDto;
import com.yeejoin.amos.boot.module.jg.biz.context.EquipDataProcessStrategyContext;
import com.yeejoin.amos.boot.module.jg.biz.edit.core.IEventPublisher;
import com.yeejoin.amos.boot.module.jg.biz.edit.event.BaseBizDataChangeEvent;
import com.yeejoin.amos.boot.module.jg.biz.edit.event.ChangeLogInsertEvent;
import com.yeejoin.amos.boot.module.jg.biz.edit.process.biz.strategy.IBizDataChangeHandleStrategy;
import com.yeejoin.amos.boot.module.jg.biz.edit.process.equip.strategy.IEquipChangeDataProcessStrategy;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import java.util.List;
import java.util.Map;

public abstract class DefaultBizDataChangeHandler<U extends BaseBizDataChangeEvent> implements IBizDataChangeHandleStrategy {

    private final IEventPublisher<BaseBizDataChangeEvent> eventPublisher;

    protected DefaultBizDataChangeHandler(IEventPublisher<BaseBizDataChangeEvent> eventPublisher) {
        this.eventPublisher = eventPublisher;
    }


    @Override
    public final void doSave(String applyNo, ModelType model, Map<String, Object> changeData) {
        if (beforeCheck(applyNo, model, changeData)) {
            IEquipChangeDataProcessStrategy dataProcessor = EquipDataProcessStrategyContext.getStrategy(model);
            List<ChangeDataDto> allChangeColumns = dataProcessor.handle(changeData, applyNo);
            List<ChangeDataDto> bizEditColumns = bizDataSave(applyNo, model, changeData);
            allChangeColumns.addAll(bizEditColumns);
            // 发送数据变更
            publish2OtherBiz(buildEvent(applyNo, model, changeData));
            // 异步记录日志
            writeLog(allChangeColumns, applyNo);
        }
    }

    protected abstract U buildEvent(String applyNo, ModelType model, Map<String, Object> changeData);

    private void publish2OtherBiz(U event) {
        eventPublisher.publish(event);
    }

    private void writeLog(List<ChangeDataDto> allChangeColumns, String applyNo) {
        eventPublisher.publish(new ChangeLogInsertEvent(this, applyNo, canHandleBizType(), allChangeColumns, RequestContext.cloneRequestContext()));
    }
}
