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.JSON;
import com.alibaba.fastjson.JSONArray;
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.JgInstallationNotice;
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.JgBizChangeLogServiceImpl;
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.Collections;
import java.util.Date;
import java.util.Set;

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

    private final JgMaintenanceContractServiceImpl jgMaintenanceContractService;

    private final JgBizChangeLogServiceImpl jgBizChangeLogService;


    @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);
            // 查询之前数据json
            JSONArray beforeData = jgMaintenanceContractService.getHisData(maintenanceContract);
            jgMaintenanceContractService.updateHisDataAfterEquipEdit(maintenanceContract);
            // 查询之后数据json
            JSONArray afterData = jgMaintenanceContractService.getHisData(maintenanceContract);
            // es记录日志
            this.log2es(beforeData, afterData, maintenanceContract, event);
        });
    }

    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);
    }

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