package org.springblade.flow.visual.base.service.impl;

import java.util.Date;
import java.util.List;

import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.flow.engine.entity.FlowEngineEntity;
import org.springblade.flow.engine.service.FlowEngineService;
import org.springblade.flow.exception.WorkFlowException;
import org.springblade.flow.util.CacheKeyUtil;
import org.springblade.flow.util.RandomUtil;
import org.springblade.flow.util.RedisUtil;
import org.springblade.flow.util.StringUtil;
import org.springblade.flow.visual.base.entity.VisualdevDataPermission;
import org.springblade.flow.visual.base.entity.VisualdevEntity;
import org.springblade.flow.visual.base.mapper.VisualdevMapper;
import org.springblade.flow.visual.base.model.PaginationVisualdev;
import org.springblade.flow.visual.base.service.VisualdevService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 *
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @author JNPF开发平台组
 * @date 2021/3/16
 */
@Service
public class VisualdevServiceImpl extends ServiceImpl<VisualdevMapper, VisualdevEntity> implements VisualdevService {

	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private CacheKeyUtil cacheKeyUtil;
	@Autowired
	private FlowEngineService flowEngineService;

	@Autowired
	private VisualdevDataPermissionService dataPermissionService;

	@Override
	public List<VisualdevEntity> getList(PaginationVisualdev paginationVisualdev) {
		QueryWrapper<VisualdevEntity> queryWrapper = new QueryWrapper<>();
		if (!StringUtil.isEmpty(paginationVisualdev.getKeyword())) {
			queryWrapper.lambda().like(VisualdevEntity::getFullName, paginationVisualdev.getKeyword());
		}
		queryWrapper.lambda().eq(VisualdevEntity::getType, paginationVisualdev.getType());
		queryWrapper.lambda().orderByDesc(VisualdevEntity::getCreatorTime);
		return list(queryWrapper);
	}

	@Override
	public List<VisualdevEntity> getList() {
		QueryWrapper<VisualdevEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().orderByAsc(VisualdevEntity::getSortCode);
		return this.list(queryWrapper);
	}

	@Override
	public VisualdevEntity getInfo(String id) {
		QueryWrapper<VisualdevEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(VisualdevEntity::getId, id);
		return this.getOne(queryWrapper);
	}

	@Override
	public void create(VisualdevEntity entity) {
		if (StringUtil.isEmpty(entity.getId())) {
			entity.setId(RandomUtil.uuId());
		}
		entity.setSortCode(RandomUtil.parses());
		if (StringUtil.isNotEmpty(entity.getWebType())) {
			if (entity.getWebType() != null && entity.getWebType().equals("3")) {
				FlowEngineEntity flowEngineEntity = new FlowEngineEntity();
				flowEngineEntity.setId(entity.getId());
				flowEngineEntity.setFlowTemplateJson(entity.getFlowTemplateJson());
				flowEngineEntity.setEnCode("visualDev" + entity.getEnCode());
				flowEngineEntity.setType(1);
				flowEngineEntity.setIcon("icon-ym icon-ym-node");
				flowEngineEntity.setIconBackground("#008cff");
				flowEngineEntity.setEnabledMark(1);
				flowEngineEntity.setFormType(2);
				flowEngineEntity.setTables(entity.getTables());
				flowEngineEntity.setDbLinkId(entity.getDbLinkId());
				flowEngineEntity.setFormData(entity.getFormData());
				flowEngineService.create(flowEngineEntity);
				entity.setFlowId(flowEngineEntity.getId());
			}
		}

		entity.setCreatorTime(new Date());
		entity.setCreatorUser(SecureUtil.getUserName());
		boolean flag = this.save(entity);
		if (flag) {
			LambdaQueryWrapper<VisualdevDataPermission> wrapper = Wrappers.lambdaQuery(VisualdevDataPermission.class)
					.eq(VisualdevDataPermission::getIsDefault, 1)
					.eq(VisualdevDataPermission::getVisualdevId, entity.getId());
			VisualdevDataPermission defPermission = dataPermissionService.getOne(wrapper);
			if (defPermission == null) {
				//该表单不存在默认权限，则添加一条默认权限组
				String permJson = "[{\"permKey\":\"add\",\"permName\":\"新增\",\"permValue\":1},{\"permKey\":\"download\",\"permName\":\"导出\",\"permValue\":1},{\"permKey\":\"batchUpload\",\"permName\":\"批量导入\",\"permValue\":0},{\"permKey\":\"batchRemove\",\"permName\":\"批量删除\",\"permValue\":0},{\"permKey\":\"edit\",\"permName\":\"编辑\",\"permValue\":0},{\"permKey\":\"remove\",\"permName\":\"删除\",\"permValue\":1},{\"permKey\":\"detail\",\"permName\":\"详情\",\"permValue\":0}]";
				defPermission = new VisualdevDataPermission();
				defPermission.setCreateTime(new Date());
				defPermission.setCreateUserId(SecureUtil.getUserId());
				defPermission.setVisualdevId(entity.getId());
				defPermission.setIsDefault(1);
				defPermission.setPermJson(permJson);
				defPermission.setDataPermId(0);
				defPermission.setVisualdevPermName("默认权限组");
				dataPermissionService.save(defPermission);
			}
		}
	}

	@Override
	public boolean update(String id, VisualdevEntity entity) {
		entity.setId(id);
		String redisKey = cacheKeyUtil.getVisiualData() + id;
		if (redisUtil.exists(redisKey)) {
			redisUtil.remove(redisKey);
		}
		// 关联流程更新
		if (entity.getWebType() != null && entity.getWebType().equals("3")) {
			try {
				VisualdevEntity visualdevEntity = this.getInfo(id);
				FlowEngineEntity flowEngineEntity;
				// 判断是否关联流程id
				if (visualdevEntity.getFlowId() == null) {
					flowEngineEntity = new FlowEngineEntity();
					flowEngineEntity.setId(id);
					flowEngineEntity.setFlowTemplateJson(entity.getFlowTemplateJson());
					flowEngineEntity.setEnCode("#visualDev" + entity.getEnCode());
					flowEngineEntity.setType(1);
					flowEngineEntity.setIcon("icon-ym icon-ym-node");
					flowEngineEntity.setIconBackground("#008cff");
					flowEngineEntity.setEnabledMark(1);
					flowEngineEntity.setFormType(2);
					flowEngineEntity.setTables(entity.getTables());
					flowEngineEntity.setDbLinkId(entity.getDbLinkId());
					flowEngineEntity.setFormData(entity.getFormData());
					flowEngineService.create(flowEngineEntity);
					entity.setFlowId(flowEngineEntity.getId());
				}
				flowEngineEntity = flowEngineService.getInfo(visualdevEntity.getFlowId());
				flowEngineEntity.setFlowTemplateJson(entity.getFlowTemplateJson());
				flowEngineEntity.setTables(entity.getTables());
				flowEngineEntity.setDbLinkId(entity.getDbLinkId());
				flowEngineEntity.setFormData(entity.getFormData());
				flowEngineService.update(visualdevEntity.getFlowId(), flowEngineEntity);
			} catch (WorkFlowException e) {
				e.printStackTrace();
			}
		}
		entity.setLastModifyTime(new Date());
		entity.setLastModifyUser(SecureUtil.getUserName());
		return this.updateById(entity);
	}

	@Override
	public void delete(VisualdevEntity entity) throws WorkFlowException {
		if (entity != null) {
			try {
				if (entity.getFlowId() != null) {
					FlowEngineEntity flowEngineEntity = flowEngineService.getInfo(entity.getFlowId());
					flowEngineService.delete(flowEngineEntity);
				}
			} catch (WorkFlowException e) {
				throw new WorkFlowException("删除失败");
			}
			this.removeById(entity.getId());
		}
	}
}
