package cn.com.tenlion.systembase.util.fullsyncmsg;

import cn.com.tenlion.systembase.pojo.dtos.institution.InstitutionDTO;
import cn.com.tenlion.systembase.pojo.vos.institution.InstitutionVO;
import cn.com.tenlion.systembase.service.institution.IInstitutionService;
import com.alibaba.fastjson.JSONObject;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

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

/**
 * 表单全量数据同步
 * 接收数据整合系统发来的全量数据同步命令, 向数据整合系统发送表单的全部数据
 */
@Component
public class FullSyncMsgDemo implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher applicationEventPublisher;
    @Autowired
    private IInstitutionService institutionService;

    @Autowired
    KafkaTemplate kafkaTemplate;

    public FullSyncMsgDemo() {}

    @KafkaListener(topics = "C0032")
    public void message(ConsumerRecord<?, ?> record) {
        JSONObject jsonObject = JSONObject.parseObject(record.value().toString());
        Map<String, Object> params = new HashMap<>();
        if(!"delete".equals(jsonObject.getString("action"))) {
            InstitutionDTO institutionDTO = institutionService.get(jsonObject.getString("uid"));
            InstitutionVO institutionVO = new InstitutionVO();
            institutionVO.setLocationCode(institutionDTO.getLocationCode());
            institutionVO.setInstitutionName(institutionDTO.getInstitutionName());
            institutionVO.setInstitutionTypeText(institutionDTO.getInstitutionTypeText());
            institutionVO.setInstitutionLevelText(institutionDTO.getInstitutionLevelText());
            institutionVO.setGrid(institutionDTO.getGrid());
            institutionService.saveKafka(institutionDTO.getInstitutionId(), institutionVO);
        }else {
            institutionService.deleteKafka(jsonObject.getString("uid"));
        }
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

}