package com.yeejoin.amos.boot.module.jg.biz.event.handler;

import com.yeejoin.amos.boot.module.jg.api.entity.JgMaintenanceContract;
import com.yeejoin.amos.boot.module.jg.biz.event.ChangeDataEvent;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.JgMaintenanceContractServiceImpl;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.UseRegisterDataChangeHandleImpl;
import com.yeejoin.amos.boot.module.ymt.api.enums.FlowStatusEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@RequiredArgsConstructor
@Slf4j
public class MaintenanceContractUpdateUpdateHandler implements IChangeUpdateHandler<ChangeDataEvent> {

    private final JgMaintenanceContractServiceImpl jgMaintenanceContractService;


    @Override
    @Async
    public void handle(ChangeDataEvent event) {
        log.info("开始更新维保备案json数据：{}", event);
        // 查询关联的单据-未删除且已完成状态
        Set<Long> maintenanceContractList = this.getRelationMaintenanceContractList(event);
        // 更新历史json
        maintenanceContractList.forEach(seq -> {
            // 更新json
            JgMaintenanceContract maintenanceContract = jgMaintenanceContractService.getById(seq);
            jgMaintenanceContractService.updateHisDataAfterEquipEdit(maintenanceContract);
        });
    }

    private Set<Long> getRelationMaintenanceContractList(ChangeDataEvent event) {
        // 变化的设备
        Set<String> records = event.getBizRelationData().getRecords();
        // 查询关联的单据-已完成时更新其json
        return jgMaintenanceContractService.getBaseMapper().queryListByEqsAndStatus(records, FlowStatusEnum.TO_BE_FINISHED.getName());
    }

    @Override
    public Boolean supports(ChangeDataEvent event) {
        return event.getBizRelationData().getBizType().equals(UseRegisterDataChangeHandleImpl.BIZ_TYPE);
    }
}
