package cn.superdesk.uniorder.mq.consumer.superdeskser.organisation;


import cn.superdesk.uniorder.dao.entity.organisation.SysEnterprise;
import cn.superdesk.uniorder.dao.entity.sys.SysOderUser;
import cn.superdesk.uniorder.dao.entity.organisation.SysOrganization;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysEnterpriseDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysOrganizationDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.sys.SysOderUserDubboConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 来源 老系统
 * 弃用? TODO 再验证一下
 */
@Slf4j
@Component
public class ReceiveConsumerHandler {


	/**
	 * 项目
	 */
	@Autowired
	private SysOrganizationDubboConsumerService organizatioDubboService;
	/**
	 * 企业
	 */
	@Autowired
	private SysEnterpriseDubboConsumerService   sysEnterpriseDubboConsumerService;
	/**
	 * 用户 老系统过来的 tb_user
	 */
	@Autowired
	private SysOderUserDubboConsumerService     sysOderUserDubboConsumerService;


	// 项目 企业 用户
	@KafkaListener(topics = "${custom.buildwindow.topic}")
	public void listenBuildwindow(ConsumerRecord<?, ?> record) {

		String topic = record.topic();// 消费的topic

		log.info("-------------recieve message from {} topic-------------", topic);
		log.info("data.String:{}", record);
		log.info("key:{}", String.valueOf(record.key()));//消费的topic的分区
		log.info("partition:{}", String.valueOf(record.partition()));//消费的topic的分区
		log.info("offset:{}", String.valueOf(record.offset()));//消费者的位置
		log.info("get message from {} topic : {}", topic, record.value());//接收到的消息

		Optional<?> kafkaMessage = Optional.ofNullable(record.value());
		String      messageStr   = (String) kafkaMessage.get();

		//Map jsonMap=gson.fromJson(messageStr, Map.class);
		Map<String, Object> jsonMap = com.alibaba.fastjson.JSONObject.parseObject(messageStr);

		log.info("get message from {} topic : {}", topic, record.value());//接收到的消息

		try {

			// 项目
			if (record.key().equals("addOrUpdateOrg")) {

				SysOrganization org = new SysOrganization();

				org.setOrganizationId(Long.decode(String.valueOf((Integer) jsonMap.get("id"))));
				org.setOrganizationNo((String) jsonMap.get("code"));
				org.setOrganizationName((String) jsonMap.get("name"));
				org.setOtherField1((String) jsonMap.get("cityCode"));
				org.setOtherField2((String) jsonMap.get("cityName"));

				List<SysOrganization> ListOrgs = organizatioDubboService.findByOrgId(org.getOrganizationId());

				// 存在 update
				if (ListOrgs.size() >= 1) {
					org.setId(ListOrgs.get(0).getId());
					organizatioDubboService.update(org);
				}
				// insert
				else {
					organizatioDubboService.add(org);
				}

			}
			// 企业
			else if (record.key().equals("addOrUpdateVirtualarchitecture")) {

				SysEnterprise vir = new SysEnterprise();
				vir.setEnterpriseId(Long.decode(String.valueOf((Integer) jsonMap.get("id"))));
				vir.setEnterpriseNo((String) jsonMap.get("codeNumber"));
				vir.setEnterpriseName((String) jsonMap.get("name"));

				if (jsonMap.containsKey("organizationId")) {
					if (null != jsonMap.get("organizationId")) {
						vir.setOrganizationId(Long.decode(String.valueOf((Integer) jsonMap.get("organizationId"))));
					}
				}

				vir.setEnabled(Integer.parseInt(jsonMap.get("enabled").toString()));
				SysEnterprise ListOrgs = sysEnterpriseDubboConsumerService.findByVirtId(vir.getEnterpriseId());

				if (ListOrgs != null) {//存在 update
					vir.setId(ListOrgs.getId());
					sysEnterpriseDubboConsumerService.update(vir);
				} else {//insert
					sysEnterpriseDubboConsumerService.add(vir);
				}

			}
			// 人员
			else if (record.key().equals("addOrUpdateUser")) {

				SysOderUser orderUser = new SysOderUser();

				orderUser.setUserId(Long.decode(String.valueOf((Integer) jsonMap.get("id"))));
				orderUser.setRealname((String) jsonMap.get("userName"));
				orderUser.setMobile((String) jsonMap.get("userMobile"));
				orderUser.setBillEmail((String) jsonMap.get("email"));

				if (jsonMap.containsKey("organizationId")) {

					if (null != jsonMap.get("organizationId")) {
						orderUser.setOrganizationId(Long.decode(String.valueOf((Integer) jsonMap.get("organizationId"))));
					}
				}

				if (jsonMap.containsKey("virtualArchId")) {
					if (null != jsonMap.get("virtualArchId")) {
						orderUser.setEnterpriseId(Long.decode(String.valueOf((Integer) jsonMap.get("virtualArchId"))));
					}
				}

				List<SysOderUser> userList = sysOderUserDubboConsumerService.findByUserId(orderUser.getUserId());

				// 存在 update
				if (userList.size() >= 1) {

					orderUser.setId(userList.get(0).getId());
					orderUser.setFundBalance(userList.get(0).getFundBalance());

					sysOderUserDubboConsumerService.update(orderUser);
				}
				// insert
				else {

					orderUser.setFundBalance(new BigDecimal("0"));

					sysOderUserDubboConsumerService.add(orderUser);
				}
			}
		} catch (Exception e) {

			log.error("listenBuildwindow error===>" + e.getMessage());
			log.error(e.getMessage(), e);

			e.printStackTrace();
		}

	}
}
