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;

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

	@Autowired
	private DataSourceService dataSourceService;

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

	/**
	 * 找出两次表单提交的不同
	 * 
	 * @param formId
	 * @param oldMap
	 * @param newMap
	 * @return
	 */
	private List<FormDataLog> diff(String formId, 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 log = null;
			CubeTableColumnModel columnData = dataSourceService.getFieldInfo(Integer.decode(columnId));
			if (oldValue == null && newValue != null) {
				// 新增
				log = new FormDataLog(FormDataLogType.add, Integer.decode(columnId), formId);
				log.setValueNew(handleValue(newValue, columnData));
			}

			if (oldValue != null && newValue != null) {
				// 更新
				log = new FormDataLog(FormDataLogType.update, Integer.decode(columnId), formId);
				log.setValueOld(handleValue(oldValue, columnData));
				log.setValueNew(handleValue(newValue, columnData));
			}

			if (oldValue != null && newValue == null) {
				// 删除
				log = new FormDataLog(FormDataLogType.remove, Integer.decode(columnId), formId);
				log.setValueOld(handleValue(oldValue, columnData));
			}

			// 同一批次的数据变更，时间和批号都相同
			log.setTime(new Date());
			log.setSn(sn);
			log.setOperator(SecureUtil.getUserName());
			log.setOperatorId(SecureUtil.getUserId());
			logList.add(log);
		}

		return logList;
	}

	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;
	}
}
