package org.springblade.flow.visual.base.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springblade.flow.base.ActionResult;
import org.springblade.flow.base.entity.DictionaryDataEntity;
import org.springblade.flow.base.service.DictionaryDataService;
import org.springblade.flow.base.vo.ListVO;
import org.springblade.flow.database.exception.DataException;
import org.springblade.flow.exception.WorkFlowException;
import org.springblade.flow.model.visiual.FormDataField;
import org.springblade.flow.model.visiual.JnpfKeyConsts;
import org.springblade.flow.model.visiual.VisualdevTreeChildModel;
import org.springblade.flow.model.visiual.fields.FieldsModel;
import org.springblade.flow.permission.entity.UserEntity;
import org.springblade.flow.permission.service.User4FlowService;
import org.springblade.flow.util.JsonUtil;
import org.springblade.flow.util.JsonUtilEx;
import org.springblade.flow.util.RandomUtil;
import org.springblade.flow.util.StringUtil;
import org.springblade.flow.util.treeutil.SumTree;
import org.springblade.flow.util.treeutil.newtreeutil.TreeDotUtils;
import org.springblade.flow.visual.base.entity.VisualdevEntity;
import org.springblade.flow.visual.base.model.PaginationVisualdev;
import org.springblade.flow.visual.base.model.VisualDevCrForm;
import org.springblade.flow.visual.base.model.VisualDevInfoVO;
import org.springblade.flow.visual.base.model.VisualDevListVO;
import org.springblade.flow.visual.base.model.VisualTreeModel;
import org.springblade.flow.visual.base.model.VisualdevTreeVO;
import org.springblade.flow.visual.base.model.template6.BtnData;
import org.springblade.flow.visual.base.service.VisualdevService;
import org.springblade.flow.visual.base.util.VisualUtil;
import org.springblade.flow.visual.onlinedev.service.VisualdevModelDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 可视化基础模块
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月27日 上午9:18
 */
@Api(tags = "可视化基础模块", value = "Base")
@RestController
@RequestMapping("/paas/visualdev/Base")
public class VisualdevController {

	@Autowired
	private VisualdevService visualdevService;
	@Autowired
	private User4FlowService userService;
	@Autowired
	private DictionaryDataService dictionaryDataService;
	@Autowired
	private VisualdevModelDataService visualdevModelDataService;
	
	@ApiOperation("获取功能列表")
	@GetMapping
	public ActionResult<ListVO<VisualDevListVO>> list(PaginationVisualdev paginationVisualdev) {
		List<VisualdevEntity> data = visualdevService.getList(paginationVisualdev);
		List<DictionaryDataEntity> dictionList = dictionaryDataService.getList();
		List<UserEntity> userList = userService.getList();
		List<String> datalist = data.stream().map(t -> t.getCategory()).distinct().collect(Collectors.toList());
		List<VisualTreeModel> modelAll = new LinkedList<>();
		for (String id : datalist) {
			DictionaryDataEntity dataEntity = dictionList.stream().filter(t -> t.getId().equals(id)).findFirst()
					.orElse(null);
			if (dataEntity != null) {
				VisualTreeModel model = new VisualTreeModel();
				model.setFullName(dataEntity.getFullName());
				model.setId(dataEntity.getId());
				long num = data.stream().filter(t -> t.getCategory().equals(id)).count();
				model.setNum(num);
				if (num > 0) {
					modelAll.add(model);
				}
			}
		}
		for (VisualdevEntity entity : data) {
			VisualTreeModel model = JsonUtil.getJsonToBean(entity, VisualTreeModel.class);
			DictionaryDataEntity dataEntity = dictionList.stream().filter(t -> t.getId().equals(entity.getCategory()))
					.findFirst().orElse(null);
			if (dataEntity != null) {
				model.setParentId(dataEntity.getId());
				UserEntity creatorUser = userList.stream().filter(t -> t.getId().equals(model.getCreatorUser()))
						.findFirst().orElse(null);
				if (creatorUser != null) {
					model.setCreatorUser(creatorUser.getRealName() + "/" + creatorUser.getAccount());
				}
				UserEntity lastmodifyuser = userList.stream().filter(t -> t.getId().equals(model.getLastModifyUser()))
						.findFirst().orElse(null);
				if (lastmodifyuser != null) {
					model.setLastModifyUser(lastmodifyuser.getRealName() + "/" + lastmodifyuser.getAccount());
				}
				modelAll.add(model);
			}
		}
		List<SumTree<VisualTreeModel>> trees = TreeDotUtils.convertListToTreeDot(modelAll);
		List<VisualDevListVO> list = JsonUtil.getJsonToList(trees, VisualDevListVO.class);
		ListVO<VisualDevListVO> vo = new ListVO<>();
		vo.setList(list);
		return ActionResult.success(vo);
	}

	@ApiOperation("获取功能列表下拉框")
	@GetMapping("/Selector")
	public ActionResult<ListVO<VisualdevTreeVO>> selectorList(Integer type) {
		List<VisualdevEntity> list = visualdevService.getList().stream().filter(t -> t.getState() == 1)
				.collect(Collectors.toList());
		if (type != null) {
			list = list.stream().filter(t -> type.equals(t.getType())).collect(Collectors.toList());
		}
		List<VisualdevTreeVO> voList = new ArrayList<>();
		HashSet<String> cate = new HashSet<>(16);
		for (VisualdevEntity entity : list) {
			if (!StringUtil.isEmpty(entity.getCategory())) {
				DictionaryDataEntity dataEntity = dictionaryDataService.getInfo(entity.getCategory());
				if (dataEntity != null) {
					int i = cate.size();
					cate.add(dataEntity.getId());
					if (cate.size() == i + 1) {
						VisualdevTreeVO visualdevTreeVO = new VisualdevTreeVO();
						visualdevTreeVO.setId(entity.getCategory());
						visualdevTreeVO.setFullName(dataEntity.getFullName());
						visualdevTreeVO.setHasChildren(true);
						voList.add(visualdevTreeVO);
					}
				}
			}
		}

		for (VisualdevTreeVO vo : voList) {
			List<VisualdevTreeChildModel> visualdevTreeChildModelList = new ArrayList<>();
			for (VisualdevEntity entity : list) {
				if (vo.getId().equals(entity.getCategory())) {
					VisualdevTreeChildModel model = JsonUtil.getJsonToBean(entity, VisualdevTreeChildModel.class);
					visualdevTreeChildModelList.add(model);
				}
			}
			vo.setChildren(visualdevTreeChildModelList);
		}
		ListVO<VisualdevTreeVO> listVO = new ListVO<>();
		listVO.setList(voList);
		return ActionResult.success(listVO);
	}

	@ApiOperation("获取功能信息")
	@GetMapping("/{id}")
	public ActionResult<VisualDevInfoVO> info(@PathVariable("id") String id) throws DataException {
		VisualdevEntity entity = visualdevService.getInfo(id);
		VisualDevInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, VisualDevInfoVO.class);
		return ActionResult.success(vo);
	}

	@ApiOperation("获取表单主表属性下拉框")
	@GetMapping("/{id}/FormDataFields")
	public ActionResult<ListVO<FormDataField>> getFormData(@PathVariable("id") String id) {
		VisualdevEntity entity = visualdevService.getInfo(id);
		Map<String, Object> formData = JsonUtil.stringToMap(entity.getFormData());
		List<FieldsModel> fieLdsModelList = JsonUtil.getJsonToList(formData.get("fields").toString(),
				FieldsModel.class);
		List<FormDataField> formDataFieldList = new ArrayList<>();
		for (FieldsModel fieLdsModel : fieLdsModelList) {
			if (!"".equals(fieLdsModel.getVModel())
					&& !JnpfKeyConsts.CHILD_TABLE.equals(fieLdsModel.getConfig().getJnpfKey())
					&& !"relationForm".equals(fieLdsModel.getConfig().getJnpfKey())) {
				FormDataField formDataField = new FormDataField();
				formDataField.setLabel(fieLdsModel.getConfig().getLabel());
				formDataField.setVModel(fieLdsModel.getVModel());
				formDataFieldList.add(formDataField);
			}
		}
		ListVO<FormDataField> listVO = new ListVO<>();
		listVO.setList(formDataFieldList);
		return ActionResult.success(listVO);
	}

	@ApiOperation("获取表单主表属性列表")
	@GetMapping("/{id}/FieldDataSelect")
	public ActionResult<List<Map<String, Object>>> getFormData(@PathVariable("id") String id, String key)
			throws ParseException, DataException, IOException, SQLException {
		VisualdevEntity visualdevEntity = visualdevService.getInfo(id);
		List<Map<String, Object>> realList = visualdevModelDataService.getListResultAll(visualdevEntity);
		List<Map<String, Object>> dataAll = new ArrayList<>();
		if (StringUtil.isNotEmpty(key)) {
			for (Map<String, Object> map : realList) {
				for (Object value : map.values()) {
					if (String.valueOf(value).contains(key)) {
						dataAll.add(map);
						break;
					}
				}
			}
		} else {
			dataAll = realList;
		}
		return ActionResult.success(dataAll);
	}

	/**
	 * 复制功能
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation("复制功能")
	@PostMapping("/{id}/Actions/Copy")
	public ActionResult<String> copyInfo(@PathVariable("id") String id) {
		VisualdevEntity entity = visualdevService.getInfo(id);
		entity.setState(0);
		entity.setFullName(entity.getFullName() + "_副本");
		entity.setId(RandomUtil.uuId());
		VisualdevEntity entity1 = JsonUtil.getJsonToBean(entity, VisualdevEntity.class);
		visualdevService.create(entity1);
		return ActionResult.success("复制成功");
	}

	/**
	 * 更新功能状态
	 *
	 * @param id 主键值
	 * @return
	 */
	@ApiOperation("更新功能状态")
	@PutMapping("/{id}/Actions/State")
	public ActionResult<String> update(@PathVariable("id") String id) {
		VisualdevEntity entity = visualdevService.getInfo(id);
		if (entity != null) {
			if (entity.getState() == 1) {
				entity.setState(0);
			} else {
				entity.setState(1);
			}
			boolean flag = visualdevService.update(entity.getId(), entity);
			if (flag == false) {
				return ActionResult.fail("更新失败，任务不存在");
			}
		}
		return ActionResult.success("更新成功");
	}

	@ApiOperation("新建表单")
	@PostMapping
	public ActionResult<String> create(@RequestBody VisualDevCrForm visualDevCrForm) {
		VisualdevEntity entity = JsonUtil.getJsonToBean(JsonUtilEx.getObjectToString(visualDevCrForm),
				VisualdevEntity.class);
		visualdevService.create(entity);
		return ActionResult.success("新建成功");
	}

	@ApiOperation("修改功能")
	@PutMapping("/{id}")
	public ActionResult<String> update(@PathVariable("id") String id, @RequestBody VisualDevCrForm visualDevCrForm) {
		VisualdevEntity entity = JsonUtil.getJsonToBean(JsonUtilEx.getObjectToString(visualDevCrForm),
				VisualdevEntity.class);
		boolean flag = visualdevService.update(id, entity);
		if (flag == false) {
			return ActionResult.fail("更新失败，数据不存在");
		}
		return ActionResult.success("更新成功");
	}

	@ApiOperation("删除功能")
	@DeleteMapping("/{id}")
	public ActionResult<String> delete(@PathVariable("id") String id) throws WorkFlowException {
		VisualdevEntity entity = visualdevService.getInfo(id);
		if (entity != null) {
			visualdevService.delete(entity);
			return ActionResult.success("删除成功");
		}
		return ActionResult.fail("删除失败，数据不存在");
	}

	@ApiOperation("获取模板按钮和列表字段")
	@GetMapping("/ModuleBtn")
	public ActionResult<List<BtnData>> getModuleBtn(String moduleId) {
		VisualdevEntity visualdevEntity = visualdevService.getInfo(moduleId);
		// 去除模板中的F_
		VisualUtil.delfKey(visualdevEntity);
		List<BtnData> btnData = new ArrayList<>();
		Map<String, Object> column = JsonUtil.stringToMap(visualdevEntity.getColumnData());
		if (column.get("columnBtnsList") != null) {
			btnData.addAll(JsonUtil.getJsonToList(JsonUtil.getJsonToListMap(column.get("columnBtnsList").toString()),
					BtnData.class));
		}
		if (column.get("btnsList") != null) {
			btnData.addAll(JsonUtil.getJsonToList(JsonUtil.getJsonToListMap(column.get("btnsList").toString()),
					BtnData.class));
		}
		return ActionResult.success(btnData);
	}

}
