package com.iformall.service.invest.event;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.iformall.domain.po.invest.InvestTaskEntity;
import com.iformall.domain.vo.RentEventInfo;
import com.iformall.enums.EnumInvestType;
import com.iformall.enums.EnumRentContractStatus;
import com.iformall.enums.EnumTaskStatus;
import com.iformall.service.invest.InvestTaskService;
import com.iformall.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class InvestListener implements ApplicationListener<InvestEvent> {

	@Autowired
	private InvestTaskService taskService;

	@Override
	public void onApplicationEvent(InvestEvent event) {
		RentEventInfo rentEventInfo = (RentEventInfo) event.getSource();
		log.debug("receive InvestEvent , info : {}", JSON.toJSONString(rentEventInfo));

		LambdaQueryWrapper<InvestTaskEntity> query = new LambdaQueryWrapper<>();
		query.in(InvestTaskEntity::getTargetId, rentEventInfo.getTargetIds());
		query.eq(InvestTaskEntity::getTargetType, EnumInvestType.RENT);
		List<InvestTaskEntity> tasks = taskService.list(query);
		if (CollectionUtils.isEmpty(tasks)) {
			log.warn("receive InvestEvent , tasks is empty : {}", tasks);
			return;
		}

		EnumTaskStatus status = EnumTaskStatus.CREATED;
		EnumRentContractStatus rentContractStatus = rentEventInfo.getType();
		if (Objects.equals(EnumRentContractStatus.INTENTION, rentContractStatus)) {
			status = EnumTaskStatus.INTENTION;
		} else if (Objects.equals(EnumRentContractStatus.SIGNED_RENT_UNPAID, rentContractStatus)) {
			status = EnumTaskStatus.FINISH;
		} else if (Objects.equals(EnumRentContractStatus.RENT_PAID, rentContractStatus)) {
			status = EnumTaskStatus.FINISH;
		}

		for (InvestTaskEntity task : tasks) {
			task.setStatus(status);
			String content = task.getContent();
			Map contentMap = JSON.parseObject(content, Map.class);
			contentMap.put(InvestTaskEntity.KEY_CONTRACTID, rentEventInfo.getRentId());
			task.setContent(JsonUtil.obj2Json(contentMap));
		}
		taskService.updateBatchById(tasks);
	}
}
