package org.springblade.flow.datalog.controller;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import org.springblade.core.tool.api.R;
import org.springblade.core.tool.support.Kv;
import org.springblade.flow.datalog.model.FormDataLog;
import org.springblade.flow.datalog.service.FormDataLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.hutool.core.collection.CollUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 表单数据操作记录控制器
 * 
 * @author William
 * @date 2022年11月17日 上午11:54:32
 */
@RestController
@RequestMapping("/paas/visualdev/datalog")
@Api(tags = "表单数据操作记录", value = "FormDataLog")
public class FormDataLogController {

	@Autowired
	private FormDataLogService logService;

	@PostMapping("/all")
	@ApiOperation(value = "表单所有数据变更记录")
	public R<List<Kv>> all(String formId) {
		LambdaQueryWrapper<FormDataLog> wrapper = Wrappers.<FormDataLog>lambdaQuery();
		wrapper.eq(FormDataLog::getFormId, formId);
		wrapper.orderByAsc(FormDataLog::getSn);
		LinkedHashMap<Long, List<FormDataLog>> map = new LinkedHashMap<>();
		List<FormDataLog> all = logService.list(wrapper);
		if (CollUtil.isNotEmpty(all)) {
			all.forEach(item -> {
				List<FormDataLog> list = new ArrayList<>();
				if (map.containsKey(item.getSn())) {
					list = map.get(item.getSn());
					list.add(item);
				}
				map.put(item.getSn(), list);
			});
		}

		if (CollUtil.isNotEmpty(map)) {
			List<Kv> allList = new ArrayList<>();
			Set<Long> keys = map.keySet();
			keys.forEach(key -> {
				Kv kv = Kv.create();
				kv.set("sn", key);
				kv.set("items", map.get(key));
				allList.add(kv);
			});
			return R.data(allList);
		}

		return R.data(null);
	}

//	@PostMapping("/list")
//	@ApiOperation(value = "分页查询")
//	public R<IPage<FormDataLog>> list(String formId, Query query) {
//		LambdaQueryWrapper<FormDataLog> wrapper = Wrappers.<FormDataLog>lambdaQuery();
//		wrapper.eq(FormDataLog::getFormId, formId);
//		wrapper.orderByDesc(FormDataLog::getId);
//		return R.data(logService.page(Condition.getPage(query), wrapper));
//	}
}
