package org.springblade.flow.datalog.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springblade.bi.client.model.CubeTableColumnModel;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.cube.enums.ViewColumnTypeEnum;
import org.springblade.flow.datalog.enums.FormDataLogType;
import org.springblade.flow.datalog.mapper.FormDataLogMapper;
import org.springblade.flow.datalog.model.FormDataLog;
import org.springblade.flow.util.DateUtil;
import org.springblade.flow.visual.onlinedev.common.dynamic.DataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 
 * @author William
 * @date 2022年11月17日 上午11:55:38
 */
@Service
public class FormDataLogService extends ServiceImpl<FormDataLogMapper, FormDataLog> {

	@Autowired
	private DataSourceService dataSourceService;

	/**
	 * 保存表单数据变化
	 * 
	 * @param formId
	 * @param dataId
	 * @param oldMap
	 * @param newMap
	 * @return
	 */
	public boolean saveLog(String formId, String dataId, Map<String, Object> oldMap, Map<String, Object> newMap) {
		List<FormDataLog> diffList = diff(formId, dataId, oldMap, newMap);
		if (CollUtil.isNotEmpty(diffList)) {
			return saveBatch(diffList);
		}
		return false;
	}

	/**
	 * 找出两次表单提交的不同
	 * 
	 * @param formId
	 * @param dataId
	 * @param oldMap
	 * @param newMap
	 * @return
	 */
	private List<FormDataLog> diff(String formId, String dataId, Map<String, Object> oldMap,
			Map<String, Object> newMap) {
		if (oldMap == null) {
			oldMap = new HashMap<>();
		}
		if (newMap == null) {
			newMap = new HashMap<>();
		}

		List<FormDataLog> logList = new ArrayList<>();
		long sn = IdWorker.getId();

		Set<String> oldKeys = oldMap.keySet();
		Set<String> newKeys = newMap.keySet();
		Set<String> allKeys = new HashSet<>();
		if (CollUtil.isNotEmpty(oldKeys)) {
			allKeys.addAll(oldKeys);
		}
		if (CollUtil.isNotEmpty(newKeys)) {
			allKeys.addAll(newKeys);
		}
		for (String columnId : allKeys) {
			Object oldValue = null;
			if (oldMap.containsKey(columnId)) {
				oldValue = oldMap.get(columnId);
			}

			Object newValue = null;
			if (newMap.containsKey(columnId)) {
				newValue = newMap.get(columnId);
				if (newValue.toString().equalsIgnoreCase("[]")) {
					newValue = null;
				}
			}

			FormDataLog dataLog = null;
			CubeTableColumnModel columnData = dataSourceService.getFieldInfo(Integer.decode(columnId));
			if (isEmptyObject(oldValue) && !isEmptyObject(newValue)) {
				// 新增
				dataLog = new FormDataLog(FormDataLogType.add, Integer.decode(columnId), formId);
				dataLog.setValueNew(handleValue(newValue, columnData));
				inserLog(logList, dataLog, sn, dataId);
			} else if (!isEmptyObject(oldValue) && !isEmptyObject(newValue) && !isEqualObject(oldValue, newValue)) {
				// 更新
				dataLog = new FormDataLog(FormDataLogType.update, Integer.decode(columnId), formId);
				dataLog.setValueOld(handleValue(oldValue, columnData));
				dataLog.setValueNew(handleValue(newValue, columnData));
				inserLog(logList, dataLog, sn, dataId);
			} else if (!isEmptyObject(oldValue) && isEmptyObject(newValue)) {
				// 删除
				dataLog = new FormDataLog(FormDataLogType.remove, Integer.decode(columnId), formId);
				dataLog.setValueOld(handleValue(oldValue, columnData));
				inserLog(logList, dataLog, sn, dataId);
			}

		}

		return logList;
	}

	private void inserLog(List<FormDataLog> logList, FormDataLog dataLog, long sn, String dataId) {
		// 同一批次的数据变更，时间和批号都相同
		dataLog.setDataId(dataId);
		dataLog.setTime(new Date());
		dataLog.setSn(sn);
		dataLog.setOperator(SecureUtil.getNickName());
		dataLog.setOperatorId(SecureUtil.getUserId());
		logList.add(dataLog);
	}

	private boolean isEmptyObject(Object obj) {
		if (obj == null) {
			return true;
		}

		String value = obj.toString();
		if (StrUtil.isBlankIfStr(value)) {
			return true;
		}

		return false;
	}

	private boolean isEqualObject(Object obj1, Object obj2) {
		String value1 = obj1.toString();
		String value2 = obj2.toString();
		return value1.equalsIgnoreCase(value2);
	}

	private String handleValue(Object object, CubeTableColumnModel field) {
		if (object != null) {
			String value = null;
			ViewColumnTypeEnum dataType = ViewColumnTypeEnum.resolve(field.getViewDataType());
			if (dataType == ViewColumnTypeEnum.DATETIME) {
				// 时间日期类型 前端统一传递的都是时间戳
				long timestamp = Long.decode(object.toString());
				value = DateUtil.daFormat(timestamp);
			} else {
				value = object.toString();
			}
			return value;
		}
		return null;
	}
}
