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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.jg.api.dto.ESDataChangeLogDto;
import com.yeejoin.amos.boot.module.jg.api.entity.JgBizChangeLog;
import com.yeejoin.amos.boot.module.jg.api.entity.JgUseRegistration;
import com.yeejoin.amos.boot.module.jg.biz.event.ChangeDataEvent;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.JgBizChangeLogServiceImpl;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.JgUseRegistrationServiceImpl;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.UseRegisterDataChangeHandleImpl;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.UseRegisterUpdateService;
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.Collections;
import java.util.Date;
import java.util.Set;

@Component
@RequiredArgsConstructor
@Slf4j
public class UseRegisterChangeEventHandler implements IChangeEventBizHandler<ChangeDataEvent> {

    private final JgUseRegistrationServiceImpl jgUseRegistrationService;

    private final JgBizChangeLogServiceImpl jgBizChangeLogService;

    private final UseRegisterUpdateService registerUpdateService;

    @Override
    @Async
    public void handle(ChangeDataEvent event) {
        log.info("开始更新使用登记json数据：{}", event);
        // 查询关联的单据-未删除且已完成状态-不包括原始使用登记的修改
        Set<Long> useRegistrationIds = this.getRelationUseRegisterList(event);
        // 更新历史json
        useRegistrationIds.forEach(seq -> {
            // 更新json
            JgUseRegistration useRegistration = jgUseRegistrationService.getById(seq);
            // 查询之前数据json
            JSONObject beforeData = jgUseRegistrationService.getHisData(useRegistration);
            registerUpdateService.updateHisData(useRegistration.getApplyNo());
            // 查询之后数据json
            JSONObject afterData = jgUseRegistrationService.getHisData(useRegistration);
            // es记录日志
            this.log2es(beforeData, afterData, useRegistration, event);
        });
        log.info("更新使用登记的单据数量：{}", useRegistrationIds.size());
    }

    private void log2es(JSONObject beforeData, JSONObject afterData, JgUseRegistration jgUseRegistration, ChangeDataEvent event) {
        Date date = DateUtil.date();
        JgBizChangeLog changeLog = new JgBizChangeLog();
        BeanUtil.copyProperties(event.getBizRelationData(), changeLog);
        changeLog.setRecDate(date);
        changeLog.setBizId(jgUseRegistration.getApplyNo());
        // todo 与原始编辑进行关联
        changeLog.setOId(event.getRequestContext().getTraceId());
        changeLog.setBizType(changeLog.getBizType());
        changeLog.setBizTable("tzs_jg_use_registration");
        changeLog.setRecUserId(event.getRequestContext().getExcutedUserId());
        ESDataChangeLogDto esDataChangeLogDto = new ESDataChangeLogDto();
        esDataChangeLogDto.setColumnKey("changeData");
        esDataChangeLogDto.setColumnKeyLabel("历史json数据");
        esDataChangeLogDto.setBeforeData(beforeData.toJSONString());
        esDataChangeLogDto.setAfterData(afterData.toJSONString());
        esDataChangeLogDto.setUserId(event.getRequestContext().getExcutedUserId());
        esDataChangeLogDto.setCreateDate(date.getTime());
        esDataChangeLogDto.setRequestDate(DateUtil.formatDateTime(date));
        esDataChangeLogDto.setChangeId(jgUseRegistration.getApplyNo());
        esDataChangeLogDto.setColumnFamily(changeLog.getBizTable());
        esDataChangeLogDto.setBizType(changeLog.getBizType());
        jgBizChangeLogService.save2DbAndEs(changeLog, Collections.singletonList(esDataChangeLogDto));
    }

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

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