package com.persagy.bdtp.adm.entity.db;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.Data;

import java.sql.Timestamp;

@Data
@TableName(value = "adm_upload_log",autoResultMap = true)
public class AdmUploadLog {

	public static final String ADD = "add";

	public static final String MODIFY = "modify";

	public static final String REMOVE = "remove";

	private String operator;

	private String jobId;

	private String entityType;

	private String operation;

	private String data; //数据库中json类型

	private Timestamp ts;

	private String uploadTime;

	private String uploadFlag;

	public AdmUploadLog() {

	}

	public AdmUploadLog(String jobId, String operator, String operation) {
		this.jobId = jobId;
		this.operator = operator;
		this.operation = operation;
	}

	public AdmUploadLog(String uploadFlag, String uploadTime, Object data) {
		this.uploadFlag = uploadFlag;
		this.uploadTime = uploadTime;
		setData(data, SpringUtil.getBean(ObjectMapper.class));
	}

	public void setData(Object data, ObjectMapper objectMapper){
		this.entityType = getLogEntityType(data);
		try {
			this.data = objectMapper.writeValueAsString(data);
		} catch (Exception e) {

		}
	}

	private String getLogEntityType(Object o){
		if (o instanceof ObjectNode) {
			JsonNode ot = ((ObjectNode) o).get("objType");
			if(ot != null)
				return ot.asText();
			if(((ObjectNode) o).get("relCode") != null)
				return "relation";
		}
		return o.getClass().getSimpleName();
	}

}
