package com.yeejoin.amos.boot.module.jg.biz.service.impl;

import com.yeejoin.amos.boot.module.jg.api.dto.ChangeDataDto;
import com.yeejoin.amos.boot.module.jg.api.service.IBizDataChangeHandleStrategy;
import com.yeejoin.amos.boot.module.jg.biz.context.DataProcessStrategyContext;
import com.yeejoin.amos.boot.module.jg.biz.event.ChangeDataEvent;
import com.yeejoin.amos.boot.module.jg.biz.event.publisher.EventPublisher;
import com.yeejoin.amos.boot.module.jg.biz.service.IChangeDataProcessStrategy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.context.RequestContext;

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

@Service
public class UseRegisterDataChangeHandleImpl implements IBizDataChangeHandleStrategy {

    private final EventPublisher publisher;


    private final UseRegisterUpdateService useRegisterUpdateService;


    public UseRegisterDataChangeHandleImpl(EventPublisher publisher, UseRegisterUpdateService useRegisterUpdateService) {
        this.publisher = publisher;
        this.useRegisterUpdateService = useRegisterUpdateService;
    }


    @Override
    public String canHandleBizType() {
        return "useRegister";
    }


    /**
     * 保存
     *
     * @param applyNo    单据编号
     * @param model      single, batch
     * @param changeData 前端不支持分组-目前为平铺数据结构
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doSave(String applyNo, ModelType model, Map<String, Object> changeData) {
        // 选择是台套、还是单位办理的方式，进行分类数据的解析
        IChangeDataProcessStrategy dataProcessor = DataProcessStrategyContext.getStrategy(model);
        List<ChangeDataDto> allChangeColumns = dataProcessor.handle(changeData, applyNo);
        if (!allChangeColumns.isEmpty()) {
            // 更新历史的JSON的数据
            this.updateHistoryJson(applyNo);
            this.buildLogData(allChangeColumns);
            // 异步记录日志
            publisher.publish(new ChangeDataEvent(this, allChangeColumns, RequestContext.cloneRequestContext()));
        }
    }

    private void updateHistoryJson(String applyNo) {
        useRegisterUpdateService.updateHisData(applyNo);
    }

    private void buildLogData(List<ChangeDataDto> allChangeColumns) {
        allChangeColumns.forEach(column -> {
            column.setBizType("使用登记");
        });
    }


    @Override
    public Map<String, ?> getDetail(String applyNo, ModelType model, String bizId) {
        IChangeDataProcessStrategy dataProcessor = DataProcessStrategyContext.getStrategy(model);
        // 兼容：台套类打开变更详情(使用applyNo) 和 单位办理批量时选择单个设备打开详情(使用record)
        return dataProcessor.getDetail(applyNo, bizId);
    }

}
