package com.hotent.portal.persistence.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotent.base.cache.annotation.*;
import com.hotent.base.constants.CacheKeyConst;
import com.hotent.base.constants.TenantConstant;
import com.hotent.base.context.BaseContext;
import com.hotent.base.exception.BaseException;
import com.hotent.base.handler.MultiTenantHandler;
import com.hotent.base.handler.MultiTenantIgnoreResult;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.*;
import com.hotent.base.util.Base64;
import com.hotent.base.util.*;
import com.hotent.portal.model.*;
import com.hotent.portal.params.IndexLayoutVo;
import com.hotent.portal.persistence.dao.SysIndexLayoutManageDao;
import com.hotent.portal.persistence.manager.AuthorityManager;
import com.hotent.portal.persistence.manager.PortalUserLayoutConfigManager;
import com.hotent.portal.persistence.manager.SysIndexLayoutManageManager;
import com.hotent.portal.persistence.manager.SysIndexMyLayoutManager;
import com.hotent.sys.persistence.manager.SysAuthUserManager;
import com.hotent.sys.persistence.model.SysAuthUser;
import com.hotent.uc.api.impl.util.ContextUtil;
import com.hotent.uc.api.model.IUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 布局管理 Service类
 *
 * @company 广州宏天软件股份有限公司
 * @author maoww
 * @email maoww@jee-soft.cn
 * @date 2018年6月11日
 */
@Service("sysIndexLayoutManageManager")
public class SysIndexLayoutManageManagerImpl extends BaseManagerImpl<SysIndexLayoutManageDao, SysIndexLayoutManage> implements SysIndexLayoutManageManager{
	@Resource
	private SysIndexColumnManagerImpl sysIndexColumnService;
	@Resource
	private AuthorityManager authorityManager;
	@Resource
	SysIndexMyLayoutManager sysIndexMylayoutService;
	@Resource
	private SysAuthUserManager sysAuthUserManager;
	@Resource
	private PortalUserLayoutConfigManager portalUserLayoutConfigManager;
	@Resource
	BaseContext baseContext;
	@Value("${system.saas.enable:false}")
	Boolean saasEnable;

	public SysIndexLayoutManageManagerImpl() {
	}

	@Override
	public SysIndexLayoutManage getLayoutList(String id,List<SysIndexColumn> columnList,Short type) {
		SysIndexLayoutManage sysIndexLayoutManage = null;
		if(StringUtil.isNotEmpty(id)){
			sysIndexLayoutManage = this.get(id);
		}
		if (BeanUtils.isEmpty(sysIndexLayoutManage))
			return getDefaultIndexLayout(type);
		String designHtml = "";
		try {
			designHtml = Base64.getFromBase64(sysIndexLayoutManage.getDesignHtml());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		sysIndexLayoutManage.setDesignHtml(sysIndexColumnService.parserDesignHtml(
				designHtml, columnList));
		return sysIndexLayoutManage;
	}



	public String getDefaultMobileDesignHtml() {
		return   "<div class=\"lyrow ui-draggable\" style=\"display: block;\">"
				+ "<div class=\"preview\"><input type=\"text\" value=\"一列(12)\" readonly=\"readonly\" class=\"form-control\"></div>"
				+ "<div class=\"view\">"
				+ "<div class=\"row clearfix\">"
				+ "<div class=\"col-md-12 column ui-sortable\"></div>"
				+ "</div>"
				+ "</div>"
				+ "</div>";
	}
	public String getDefaultDesignHtml() {
		return   "<div class=\"lyrow ui-draggable\" style=\"display: block;\">"
				+ "<a href=\"#close\" class=\"remove label label-danger\"><i class=\"glyphicon-remove glyphicon\"></i> 删除</a>"
				+ "<span class=\"drag label label-default\"><i class=\"glyphicon glyphglyphicon glyphicon-move\"></i> 拖动</span>"
				+ "<div class=\"preview\"><input type=\"text\" value=\"一列(12)\" readonly=\"readonly\" class=\"form-control\"></div>"
				+ "<div class=\"view\">"
				+ "<div class=\"row clearfix\">"
				+ "<div class=\"col-md-12 column ui-sortable\"></div>"
				+ "</div>"
				+ "</div>"
				+ "</div>";
	}

	private SysIndexLayoutManage getDefaultIndexLayout(Short type) {
		String designHtml  = getDefaultDesignHtml();
		if(type.equals(SysIndexLayoutManage.TYPE_MOBILE)){
			designHtml = getDefaultMobileDesignHtml();
		}
		SysIndexLayoutManage sysIndexLayoutManage  = new SysIndexLayoutManage();
		sysIndexLayoutManage.setDesignHtml(designHtml);
		sysIndexLayoutManage.setIsDef((short) 0);
		return sysIndexLayoutManage;
	}



	@Override
	public String getMyHasRightsLayout() {
		Map<String, Set<String>> relationMap= authorityManager.getUserRightMap();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("relationMap", relationMap);
		params.put("objType", SysObjRights.RIGHT_TYPE_INDEX_MANAGE);
		List<SysIndexLayoutManage> list = baseMapper.getByUserIdFilter(params);
		if(BeanUtils.isNotEmpty(list))
			return list.get(0).getTemplateHtml();
		return "";
	}

	@Override
	public String getManagerLayout() {
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("orgIds", null);
		params.put("isDef", 1);
		List<SysIndexLayoutManage> list = baseMapper.getManageLayout(params);
		if(BeanUtils.isNotEmpty(list) )
			return list.get(0).getDesignHtml();
		return null;
	}

	@Override
	public String obtainIndexManageData(String layoutId) {
		SysIndexLayoutManage sysIndexLayoutManage = this.get(layoutId);
		if (BeanUtils.isNotEmpty(sysIndexLayoutManage))
			return sysIndexLayoutManage.getTemplateHtml();
		//2.找自己拥有权限的管理布局 ，按是否默认，排序
		String html = getMyHasRightsLayout();
		if (BeanUtils.isNotEmpty(html))
			return html;
		//3、找自己所属子组织没权限但设置默认布局；
//		html = getHasRightsLayout();
		if (BeanUtils.isNotEmpty(html))
			return html;
		//4、如果找不到找系统管理员的设置默认布局;
		html = getManagerLayout();
		if (BeanUtils.isNotEmpty(html))
			return html;
		//5、再找不到则使用系统默认布局。
		if (BeanUtils.isEmpty(html))
			html = getDefaultDesignHtml();
		return "";
	}

	@Override
	public SysIndexLayoutManage getEnableByOrgIdAndType(String orgId,Short layoutType) {
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		params.put("layoutType", layoutType);
		return baseMapper.getEnableByOrgIdAndType(params);
	}

	@Override
	public Boolean isExistName(String name) {
		Integer count = baseMapper.isExistName(name);
		return count > 0;
	}

	@Override
	public List<SysIndexLayoutManage> getByOrgIdAndLayoutType(String orgId, Short layoutType) {
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		params.put("layoutType", layoutType);
		return baseMapper.getByOrgIdAndLayoutType(params);
	}

	@Override
	public void cancelOrgIsDef(String orgId, Short layoutType) {
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		params.put("layoutType", layoutType);
		baseMapper.cancelOrgIsDef(params);
	}

	@Override
	public String obtainIndexManageMobileData(String layoutId) {
		SysIndexLayoutManage sysIndexLayoutManage = this.get(layoutId);
		return sysIndexLayoutManage.getTemplateHtml();
	}

	@Override
	public SysIndexLayoutManage getByIdAndType(String id, Short type) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		params.put("type", type);
		return baseMapper.getByIdAndType(params);
	}

	@Override
	public String getMobileManagerLayout() {
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("layoutType", SysIndexLayoutManage.TYPE_MOBILE);
		params.put("orgIds", null);
		params.put("isDef", 1);
		List<SysIndexLayoutManage> list = baseMapper.getManageLayout(params);
		if(BeanUtils.isNotEmpty(list) )
			return list.get(0).getDesignHtml();
		return null;
	}

	@Override
	public SysIndexLayoutManage getSharedByOrgIdAndType(String orgId,Short layoutType) {
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("orgId", orgId);
		params.put("layoutType", layoutType);
		return baseMapper.getSharedByOrgIdAndType(params);
	}

	@Override
	public SysIndexLayoutManage getSharedByOrgIds(List<String> orgIds, Short layoutType) {
		List<SysIndexLayoutManage> list = baseMapper.getSharedByOrgIds(orgIds, layoutType);
		if(BeanUtils.isNotEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	@Transactional
	public void setEnable(String id, Short enable) {
		SysIndexLayoutManage layout = this.get(id);
//		//如果是启用，必须把现有的其他停用
//		if(enable ==1){
//			List<SysIndexLayoutManage> list = this.getByOrgIdAndLayoutType(layout.getOrgId(), layout.getLayoutType());
//			for(SysIndexLayoutManage item : list){
//				if(item.getEnable()==1){
//					item.setEnable((short)0);
//					this.update(item);
//				}
//			}
//		}
		layout.setEnable(enable);
		this.update(layout);
	}

	@Override
	@Transactional
	public void setAsTemplate(String id, Short asTemplate) {
		SysIndexLayoutManage layout = this.get(id);
		layout.setAsTemplate(asTemplate);
		this.update(layout);
	}

	@Override
	public SysIndexLayoutManage getDefaultLayoutManageByLayoutType(String layoutType) {
		QueryWrapper<SysIndexLayoutManage> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("LAYOUT_TYPE", Short.parseShort(layoutType)).eq("ENABLE",SysIndexLayoutManage.ENABLE).eq("IS_DEF", SysIndexLayoutManage.SET_DEF);
		SysIndexLayoutManage defaultLayout = baseMapper.selectOne(queryWrapper);
//		if(list.size()>0){
//			return  list.get(0);
//		}
		return defaultLayout;
	}

	@Override
	public String exportDefaultLayout(List<String> ids, boolean isDefault) throws Exception {
		if (BeanUtils.isEmpty(ids)) {
			throw new BaseException("请先选择要导出的默认布局");
		}
		QueryFilter<SysIndexLayoutManage> queryFilter = QueryFilter.build();
		if(isDefault){
			queryFilter.addFilter("IS_DEF",1, QueryOP.EQUAL, FieldRelation.AND);
		}else{
			queryFilter.addFilter("IS_DEF",0, QueryOP.EQUAL, FieldRelation.AND);
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < ids.size(); i++) {
			sb.append(ids.get(i));
			if(i != ids.size() - 1){
				sb.append(",");
			}
		}
		queryFilter.addFilter("ID", sb.toString(), QueryOP.IN, FieldRelation.AND);
		PageList<SysIndexLayoutManage> query = this.query(queryFilter);
		if (BeanUtils.isNotEmpty(query.getRows())) {
			return JsonUtil.toJson(query.getRows());
		}else{
			throw new BaseException("未查找到任何记录");
		}

	}

	@Transactional
	public Boolean importDatavFile(String uzPath, String orgId, boolean isDefault) {
		try {
			String fileName = isDefault ? "defaultLayout.json" : "orgLayout.json";
			String fileJson = FileUtil.readFile(uzPath + File.separator + fileName);
			List list = JsonUtil.toBean(fileJson, List.class);
			List<SysIndexLayoutManage> sysIndexLayoutManageList = new ArrayList<SysIndexLayoutManage>();
			List<SysIndexLayoutManage> checkList = new ArrayList<>();
			//导入部门门户
			if (StringUtil.isEmpty(orgId)) {
				throw new BaseException("请先选择部门");
			}
			for (Object o : list) {
				SysIndexLayoutManage layout = JsonUtil.toBean(JsonUtil.toJson(o), SysIndexLayoutManage.class);
				if(StringUtil.isEmpty(layout.getName())){
					throw new BaseException("大屏名称不能为空！");
				}
				if(StringUtil.isEmpty(layout.getAlias())){
					throw new BaseException("大屏别名不能为空！");
				}
				if(StringUtil.isEmpty(layout.getType())){
					throw new BaseException("布局type不能为空！");
				}if(!StringUtil.equals(layout.getType(),SysIndexLayoutManage.LAYOUT_TYPE_DATAV)){
					throw new BaseException("布局类型只能为datav！");
				}
				sysIndexLayoutManageList.add(layout);
				SysIndexLayoutManage checkLayout = baseMapper.getDatavByAlias(layout.getAlias());
				if (BeanUtils.isNotEmpty(checkLayout)) {
					checkList.add(checkLayout);
				}
			}
			if(checkList.size() > 0) {return false;}
			for (SysIndexLayoutManage sysIndexLayoutManage : sysIndexLayoutManageList) {
				sysIndexLayoutManage.setId(UniqueIdUtil.getSuid());
				sysIndexLayoutManage.setEnable(SysIndexLayoutManage.ENABLE);
				baseMapper.insert(sysIndexLayoutManage);
			}
		}catch (Exception e){
			throw new BaseException(e.getMessage());
		}
		return true;
	}

	public void isImportFileRepeat(String fileJson, String orgId, boolean isDefault) throws IOException {
		List list = JsonUtil.toBean(fileJson, List.class);

		//导入默认栏目
		if (isDefault) {
			for (Object o : list) {
				SysIndexLayoutManage layout = JsonUtil.toBean(JsonUtil.toJson(o), SysIndexLayoutManage.class);

				SysIndexLayoutManage byId = this.getById(layout.getId());
				List<SysIndexLayoutManage> byAlias = this.getByAlias(layout.getAlias());
				if (BeanUtils.isNotEmpty(byId) || BeanUtils.isNotEmpty(byAlias)) {
					ThreadMsgUtil.addMapMsg2("sysIndexLayoutRepeat", String.format("<div style='margin-left:12px; margin-top:6px;'>%s [%s]</div>", layout.getName() + "", layout.getAlias() + ""));
				}
			}
			return;
		}

		//导入部门门户
		if (StringUtil.isEmpty(orgId)) {
			throw new BaseException("请先选择部门");
		}
		for (Object o : list) {
			SysIndexLayoutManage orgLayout = JsonUtil.toBean(JsonUtil.toJson(o), SysIndexLayoutManage.class);
			orgLayout.setOrgId(orgId);

			SysIndexLayoutManage byId = this.getById(orgLayout.getId());
			List<SysIndexLayoutManage> byAlias = this.getByAlias(orgLayout.getAlias());
			if (BeanUtils.isNotEmpty(byId) || BeanUtils.isNotEmpty(byAlias)) {
				ThreadMsgUtil.addMapMsg2("sysIndexLayoutRepeat", String.format("<div style='margin-left:12px; margin-top:6px;'>%s [%s]</div>", orgLayout.getName() + "", orgLayout.getAlias() + ""));
			}
		}
	}

    @Override
    @Transactional
    public void importFile(String fileJson, String orgId, boolean isDefault) throws IOException {
        List list = JsonUtil.toBean(fileJson, List.class);
        if (isDefault) {
            //导入默认栏目
            for (Object o : list) {
				SysIndexLayoutManage layout = JsonUtil.toBean(JsonUtil.toJson(o), SysIndexLayoutManage.class);

				SysIndexLayoutManage byId = this.getById(layout.getId());
				List<SysIndexLayoutManage> byAlias = this.getByAlias(layout.getAlias());

				if (BeanUtils.isNotEmpty(byId)) {
					baseMapper.updateById(layout);
				} else if (BeanUtils.isNotEmpty(byAlias)) {
					QueryWrapper<SysIndexLayoutManage> wrapper = new QueryWrapper<>();
					wrapper.eq("ALIAS", layout.getAlias());
					baseMapper.update(layout,wrapper);
				} else {
					layout.setEnable(SysIndexLayoutManage.ENABLE);
					baseMapper.insert(layout);
				}
            }
            return;
        }

        //导入部门门户
        if (StringUtil.isEmpty(orgId)) {
            throw new BaseException("请先选择部门");
        }
        for (Object o : list) {
            SysIndexLayoutManage orgLayout = JsonUtil.toBean(JsonUtil.toJson(o), SysIndexLayoutManage.class);
            orgLayout.setOrgId(orgId);

            SysIndexLayoutManage byId = this.getById(orgLayout.getId());
			List<SysIndexLayoutManage> byAlias = this.getByAlias(orgLayout.getAlias());


            if (BeanUtils.isNotEmpty(byId)) {
				if (StringUtil.equals(byId.getOrgId(), orgId) || (orgId.equals("undefined") && BeanUtils.isEmpty(byId.getOrgId()))) {
                    //更新
                    baseMapper.updateById(orgLayout);
                } else {
                    //导入到其它组织，修改ID
                    orgLayout.setId(UniqueIdUtil.getSuid());
					orgLayout.setEnable(SysIndexLayoutManage.ENABLE);
                    baseMapper.insert(orgLayout);
                }
            } else if (BeanUtils.isNotEmpty(byAlias)) {
				if (StringUtil.equals(byAlias.get(0).getOrgId(), orgId) || (orgId.equals("undefined") && BeanUtils.isEmpty(byAlias.get(0).getOrgId()))) {
                    //更新
					QueryWrapper<SysIndexLayoutManage> wrapper = new QueryWrapper<>();
					wrapper.eq("ALIAS", orgLayout.getAlias());
                    baseMapper.update(orgLayout,wrapper);
                } else {
                    //导入到其它组织，修改ID
                    orgLayout.setId(UniqueIdUtil.getSuid());
					orgLayout.setEnable(SysIndexLayoutManage.ENABLE);
                    baseMapper.insert(orgLayout);
                }
            } else {
				orgLayout.setEnable(SysIndexLayoutManage.ENABLE);
                baseMapper.insert(orgLayout);
            }
        }
    }

    @Override
    @CachePut(value = CacheKeyConst.EIP_SYS_INDEX_LAYOUT_FILE, key="#fileId",
            firstCache = @FirstCache(expireTime = 1, timeUnit = TimeUnit.HOURS))
    public String putImportFileInCache(String fileId, String fileJson) {
        return fileJson;
    }

    @Override
    @Cacheable(value = CacheKeyConst.EIP_SYS_INDEX_LAYOUT_FILE, key="#fileId",
            firstCache = @FirstCache(expireTime = 1, timeUnit = TimeUnit.HOURS))
    public String getImportFileFromCache(String fileId) {
        return null;
    }

    @Override
    @CacheEvict(value = CacheKeyConst.EIP_SYS_INDEX_LAYOUT_FILE, key="#fileId")
    public void delImportFileFromCache(String fileId) {}



	@Override
	public List<SysIndexLayoutManage> getByAlias(String alias) {
		return baseMapper.getByAlias(alias);
	}

	@CachePut(value = CacheKeyConst.EIP_PORTAL_INDEX_LAYOUT, key = "#layoutType+'_'+#userId", ignoreException = false,
			firstCache = @FirstCache(expireTime = 7, expireTimeExp = "#expireTime", timeUnit = TimeUnit.DAYS),
			secondaryCache = @SecondaryCache(expireTime = 7, expireTimeExp = "#expireTime", preloadTime = 7, forceRefresh = true, timeUnit = TimeUnit.DAYS))
	@Override
	public String cacheUserLayout(String layoutId, String layoutType,String type, String userId) {
		return type+"_"+layoutId;
	}

	@Cacheable(value = CacheKeyConst.EIP_PORTAL_INDEX_LAYOUT, key = "#layoutType+'_'+#userId", ignoreException = false,
			firstCache = @FirstCache(expireTime = 7, expireTimeExp = "#expireTime", timeUnit = TimeUnit.DAYS),
			secondaryCache = @SecondaryCache(expireTime = 7, expireTimeExp = "#expireTime", preloadTime = 7, forceRefresh = true, timeUnit = TimeUnit.DAYS))
	@Override
	public String getCacheUserLayout(String layoutType, String userId) {
		return null;
	}

	@CacheEvict(value = CacheKeyConst.EIP_PORTAL_INDEX_LAYOUT, key = "#userId+'_'+#layoutType", ignoreException = false)
	@Override
	public void removeCacheUserLayout(String layoutType, String userId) {

	}

	@Override
	public CommonResult<IndexLayoutVo> myHome() throws Exception{
		IndexLayoutVo vo = null;
		//1、首先查询缓存中是否存在
		vo = getCacheLayout(SysIndexLayoutManage.TYPE_MNG);
		if(BeanUtils.isNotEmpty(vo)) {
			return new CommonResult<IndexLayoutVo>(true,"获取成功！",vo);
		}
		SysIndexLayoutManage layout = this.traceLayout(SysIndexLayoutManage.TYPE_MNG);
		if(BeanUtils.isNotEmpty(layout)) {
			vo = new IndexLayoutVo(IndexLayoutVo.TYPE_SYS, layout.getId(), layout.getName(), layout.getAlias(), layout.getDesignHtml(), layout.getIsDef(), SysIndexLayoutManage.TYPE_MNG, StringUtil.isNotEmpty(layout.getType())?layout.getType():SysIndexLayoutManage.LAYOUT_TYPE_COLUMN);
		}else {
			vo = new IndexLayoutVo();
			vo.setDesignHtml("");
		}
		return new CommonResult<IndexLayoutVo>(true,"获取成功！",vo);
	}

	@Override
	public CommonResult<IndexLayoutVo> myVueFrontHome() throws Exception {
		IndexLayoutVo vo = null;
		//1、首先查询缓存中是否存在
		vo = getCacheLayout(SysIndexLayoutManage.TYPE_APPLICATION);
		if(BeanUtils.isNotEmpty(vo)) {
			return new CommonResult<IndexLayoutVo>(true,"获取成功！",vo);
		}

		//2、再查询个人门户里面是否有布局
		QueryFilter<SysIndexMyLayout> query=QueryFilter.build();
		query.addFilter("USER_ID", ContextUtil.getCurrentUserId(), QueryOP.EQUAL);
		query.addFilter("VALID_", 1, QueryOP.EQUAL);
		List<SysIndexMyLayout> SysIndexMyLayouts = sysIndexMylayoutService.queryNoPage(query);
		if(BeanUtils.isNotEmpty(SysIndexMyLayouts)&& SysIndexMyLayouts.size()>0){
			SysIndexMyLayout myLayout = SysIndexMyLayouts.get(0);
			vo = new IndexLayoutVo(IndexLayoutVo.TYPE_PERSONAL, myLayout.getId(), myLayout.getName(), "", myLayout.getDesignHtml(), (short)0, SysIndexLayoutManage.TYPE_APPLICATION, SysIndexLayoutManage.LAYOUT_TYPE_COLUMN);
		}else{
			SysIndexLayoutManage layout = this.traceLayout(SysIndexLayoutManage.TYPE_APPLICATION);
			if(BeanUtils.isEmpty(layout)){
				vo = new IndexLayoutVo();
				vo.setDesignHtml("");
			}else{
				vo = new IndexLayoutVo(IndexLayoutVo.TYPE_SYS, layout.getId(), layout.getName(), layout.getAlias(), layout.getDesignHtml(), layout.getIsDef(), SysIndexLayoutManage.TYPE_APPLICATION, StringUtil.isNotEmpty(layout.getType())?layout.getType():SysIndexLayoutManage.LAYOUT_TYPE_COLUMN);
			}
		}
		return new CommonResult<IndexLayoutVo>(true,"获取成功！",vo);
	}

	@Override
	public CommonResult<IndexLayoutVo> myMobileHome() throws Exception {
		IndexLayoutVo vo = null;
		//1、首先查询缓存中是否存在
		vo = getCacheLayout(SysIndexLayoutManage.TYPE_MOBILE);
		if(BeanUtils.isNotEmpty(vo)) {
			return new CommonResult<IndexLayoutVo>(true,"获取成功！",vo);
		}
		//2、
		SysIndexLayoutManage layout = this.traceLayout(SysIndexLayoutManage.TYPE_MOBILE);
		if(BeanUtils.isNotEmpty(layout)) {
			vo = new IndexLayoutVo(IndexLayoutVo.TYPE_SYS, layout.getId(), layout.getName(), layout.getAlias(), layout.getDesignHtml(), layout.getIsDef(), SysIndexLayoutManage.TYPE_MOBILE, StringUtil.isNotEmpty(layout.getType())?layout.getType():SysIndexLayoutManage.LAYOUT_TYPE_COLUMN);
		}else {
			vo = new IndexLayoutVo();
			vo.setDesignHtml("");
		}
		return new CommonResult<IndexLayoutVo>(true,"获取成功！",vo);
	}

    @Override
    public PageList<SysIndexLayoutManage> listJson(QueryFilter<SysIndexLayoutManage> queryFilter) {
		IUser user = ContextUtil.getCurrentUser();
		if(!user.isAdmin()) {
			List<String> authIds = sysAuthUserManager.getAuthorizeIdsByUserMap(SysAuthUser.BPMDEFUSER_OBJ_TYPE.LAYOUT_MANAGE);
			if(BeanUtils.isNotEmpty(authIds)) {
				queryFilter.addFilter("ID", authIds, QueryOP.IN, FieldRelation.AND, "auth");
				//有权限布局
				queryFilter.addFilter("CREATE_BY_", user.getUserId(), QueryOP.EQUAL, FieldRelation.OR, "auth");
			}else {
				//有权限布局
				queryFilter.addFilter("CREATE_BY_", user.getUserId(), QueryOP.EQUAL, FieldRelation.AND, "auth");
			}
		}
		return query(queryFilter);
    }

	@Override
	public List<SysIndexLayoutManage> getDataByAlias(List<String> alias,Boolean isAdmin) {
		List<SysIndexLayoutManage> list = new ArrayList<>();
		alias.forEach(item->{
			SysIndexLayoutManage layoutManage = getDataByAlias(item,isAdmin);
			if(layoutManage!=null){
				list.add(layoutManage);
			}
		});
		return list;
	}

	/**
	 * 检查当前用户对传入的 alias 是否有权限
	 * @param alias  String 别名
	 * @return String 有权限则返回原对象，无权限返回null
	 */
	public String checkLayoutAuth(String  alias){
		List<IndexLayoutVo> list = getCurrentAuthLayout(Optional.of("front"));		// 当前用户所有有权限的布局
		list.addAll(getCurrentAuthLayout(Optional.of("manage")));
		for (IndexLayoutVo indexLayoutVo : list) {
			if(alias.equals(indexLayoutVo.getAlias())){
				return alias;
			}
		}
		return null;
	}

	@Override
    public SysIndexLayoutManage getDataByAlias(String alias,Boolean isAdmin) {
		// 权限控制，无权限则返回null
		alias = checkLayoutAuth(alias);
		if(StringUtil.isEmpty(alias))
			return null;

		List<SysIndexLayoutManage> list = getByAlias(alias);
		if(BeanUtils.isNotEmpty(list)) {
			if(list.size()>1) {
				for (SysIndexLayoutManage sysIndexLayoutManage : list) {
					if("datav".equals(sysIndexLayoutManage.getType())) {
						return sysIndexLayoutManage;
					}
				}
			}else if(list.size() == 1) {
				String acount=ContextUtil.getCurrentUserId();
				if (isAdmin){
					acount="1";
				}
				SysIndexLayoutManage sysIndexLayoutManage = list.get(0);
				PortalUserLayoutConfig layoutConfig
						= portalUserLayoutConfigManager.getByLayoutIdUserId(sysIndexLayoutManage.getId(), acount );
				if (BeanUtils.isNotEmpty(layoutConfig)) {
					sysIndexLayoutManage.setLayoutConfig(layoutConfig.getConfigContent());
				}
				return sysIndexLayoutManage;
			}
		}
		return null;
    }

	@Override
	public CommonResult<String> delete(String ids) {
		try{
			String[] aryIds = StringUtil.getStringAryByStr(ids);
			//不允许删除默认布局
			for (String id : aryIds) {
				SysIndexLayoutManage layout = get(id);
				if(BeanUtils.isNotEmpty(layout) && layout.getIsDef()==1) {
					return new CommonResult<>(false, "删除大屏失败，不允许删除系统默认布局!", null);
				}
			}
			removeByIds(aryIds);
			return new CommonResult<>(true, "删除大屏成功!", null);
		}catch(Exception ex){
			return new CommonResult<>(false, "删除失败" + ex.getMessage(), null);
		}
	}

	@Override
	public Map<String, Object> design(String id, short layoutType) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		IUser user = ContextUtil.getCurrentUser();
		//首页布局
		QueryFilter queryFilter= QueryFilter.build().withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
		queryFilter.addFilter("IS_PUBLIC", layoutType, QueryOP.EQUAL);

		if(saasEnable) {
			queryFilter.addFilter("tenant_id_", user.getTenantId(), QueryOP.EQUAL, FieldRelation.OR, "tenantId");
			queryFilter.addFilter("tenant_id_", TenantConstant.PLATFORM_TENANT_ID, QueryOP.EQUAL, FieldRelation.OR, "tenantId");
		}
//		Map<String,Object>  params  =  new HashMap<String, Object>();
		//首页栏目，true 取出来是已经解析了SysIndexColumn
//		List<SysIndexColumn>  columnList = sysIndexColumnService.getHashRightColumnList(queryFilter,params, false,layoutType,user);

		List<SysIndexColumn> columnList = null;
		try(MultiTenantIgnoreResult setThreadLocalIgnore = MultiTenantHandler.setThreadLocalIgnore()){
			columnList = sysIndexColumnService.getAllByLayoutType(queryFilter);
		}
		//获取展示的布局
		Map<String, List<Map<String, Object>>> columnMap = sysIndexColumnService.getColumnMap2(columnList);
		//获取当前的布局
		SysIndexLayoutManage sysIndexLayoutManage = get(id);
		map.put("columnMap",columnMap);
		map.put("sysIndexLayout", sysIndexLayoutManage);
		return map;
	}

	@Override
	public CommonResult<String> saveLayout(SysIndexLayoutManage indexLayout) {
		try {
			List<SysIndexLayoutManage> list = getByAlias(indexLayout.getAlias());
			if (BeanUtils.isEmpty(indexLayout.getId())) {
				if(BeanUtils.isNotEmpty(list)) {
					return new CommonResult<>(false, "布局别名【"+indexLayout.getAlias()+"】已存在。");
				}
				indexLayout.setId(UniqueIdUtil.getSuid());
				indexLayout.setEnable(SysIndexLayoutManage.ENABLE);
				create(indexLayout);
                //初始化默认授权
                sysAuthUserManager.saveRights(indexLayout.getId(), "layoutManage", "[{\"type\":\"everyone\",\"title\":\"所有人\",\"checked\":true}]");
                sysAuthUserManager.delUserMenu();
			} else {
				if(list.size()>0 && !list.get(0).getId().equals(indexLayout.getId())) {
					return new CommonResult<>(false, "布局别名【"+indexLayout.getAlias()+"】已存在。");
				}
				update(indexLayout);
			}
			return new CommonResult<>(true, "保存成功",indexLayout.getId());
		} catch (Exception e) {
			e.printStackTrace();
			return new CommonResult<>(false, e.getMessage(), null);
		}
	}

//	@Override
	public CommonResult importDefaultLayout(String cacheFileId,String orgId,boolean isDefault) throws IOException {
        String fileJson = AppUtil.getBean(getClass()).getImportFileFromCache(cacheFileId);
        if (BeanUtils.isEmpty(fileJson)) {
            return new CommonResult<>(false,"导入的文件已经过期，请重新导入。");
        }
        importFile(fileJson,orgId,isDefault);
        delImportFileFromCache(cacheFileId);
        return new CommonResult<>(true,"导入成功！");
	}

    @Override
    public CommonResult<String> importDefaultLayoutCheck(MultipartHttpServletRequest request, String orgId, boolean isDefault) {
        MultipartFile file = request.getFile("file");
        String uzPath = "";

        if (file == null) {
            return new CommonResult(false,"导入失败：导入内容不能为空");
        }

        try {
            String rootRealPath = (FileUtil.getIoTmpdir() +"/attachFiles/unZip/").replace("/", File.separator);
            FileUtil.createFolder(rootRealPath, true);
            String name = file.getOriginalFilename();
            String fileDir = StringUtil.substringBeforeLast(name, ".");
            ZipUtil.unZipFile(file, rootRealPath); // 解压文件
            uzPath = rootRealPath + File.separator + fileDir; // 解压后文件的真正路径
            //isDefault不能确认，前端不知道该传true还是false
            //String fileName = isDefault ? "defaultLayout.json" : "orgLayout.json";
            String fileJson = "";
            try {
                fileJson = FileUtil.readFile(uzPath + File.separator + "defaultLayout.json");
            }catch (RuntimeException e){
                fileJson = FileUtil.readFile(uzPath + File.separator + "orgLayout.json");
            }

            isImportFileRepeat(fileJson, orgId, isDefault);
            LinkedHashSet<String> sysIndexLayoutRepeat = ThreadMsgUtil.getMapMsg2("sysIndexLayoutRepeat");
            if (BeanUtils.isNotEmpty(sysIndexLayoutRepeat)) {
                StringBuilder sb = new StringBuilder();
                sb.append("<div style='font-weight:bold;'>以下布局重复，是否覆盖更新：</div>");
                String msg =  String.format( "%s", String.join("", sysIndexLayoutRepeat));
                sb.append(msg);

                //放入缓存
                String cacheFileId = UniqueIdUtil.getSuid();
                AppUtil.getBean(getClass()).putImportFileInCache(cacheFileId, fileJson);
                return new CommonResult<>(false, sb.toString(),cacheFileId);
            }

            importFile(fileJson,orgId,isDefault);
            return new CommonResult<>(true,"导入成功！");
        }catch (Exception e){
            return new CommonResult(false,"导入失败："+e.getMessage());
        }finally {
            if (StringUtil.isNotEmpty(uzPath)) {
                File file1 = new File(uzPath);
                if (file1.exists()) {
                    file1.delete();
                }
            }
        }
    }



	@Override
	public CommonResult saveCopy(SysIndexLayoutManage layout) {
		SysIndexLayoutManage oldLayout = get(layout.getId());
		if(StringUtil.isEmpty(layout.getAlias())) {
			throw new RuntimeException("布局别名不能为空。");
		}
		if(BeanUtils.isNotEmpty(getByAlias(layout.getAlias()))){
			throw new RuntimeException("布局别名已存在:"+layout.getAlias());
		}
		layout.setId(UniqueIdUtil.getSuid());
		layout.setEnable(oldLayout.getEnable());
		layout.setDesignHtml(oldLayout.getDesignHtml());
		layout.setIsDef((short)0);
		layout.setType(oldLayout.getType());
		layout.setLayoutType(oldLayout.getLayoutType());
		layout.setMemo(oldLayout.getMemo());
		layout.setTemplateHtml(oldLayout.getTemplateHtml());
		create(layout);
		return new CommonResult(true, "复制布局成功", null);
	}

	@Override
	public List<IndexLayoutVo> getCurrentAuthLayout(Optional<String> from) {
		List<IndexLayoutVo> authVoList = new ArrayList<IndexLayoutVo>();
		IUser user = ContextUtil.getCurrentUser();
		String fromStr = from.orElse(null);
		if(BeanUtils.isNotEmpty(user)) {//只有应用端查询个人设计的布局
			if("front".equals(fromStr)) {
				//先查询个人门户里面是否有布局
				QueryFilter<SysIndexMyLayout> query=QueryFilter.build();
				query.addFilter("USER_ID", ContextUtil.getCurrentUserId(), QueryOP.EQUAL);
				query.addFilter("VALID_", 1, QueryOP.EQUAL);
				List<SysIndexMyLayout> SysIndexMyLayouts = sysIndexMylayoutService.queryNoPage(query);
				if(BeanUtils.isNotEmpty(SysIndexMyLayouts)&& SysIndexMyLayouts.size()>0){
					for (SysIndexMyLayout myLayout : SysIndexMyLayouts) {
						IndexLayoutVo vo = new IndexLayoutVo(IndexLayoutVo.TYPE_PERSONAL, myLayout.getId(), myLayout.getName(), "", myLayout.getDesignHtml(), (short)0, SysIndexLayoutManage.TYPE_APPLICATION, SysIndexLayoutManage.LAYOUT_TYPE_COLUMN);
						authVoList.add(vo);
					}

				}
			}

			//获取管理端设计的布局
			List<SysIndexLayoutManage> authList = new ArrayList<SysIndexLayoutManage>();
			QueryFilter<SysIndexLayoutManage> queryFilter = QueryFilter.build();
			queryFilter.setGroupRelation(FieldRelation.OR);
			queryFilter.withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
			queryFilter.addFilter("ENABLE", 1, QueryOP.EQUAL);//启动的
			List<String> notInTypes = new ArrayList<String>();
			notInTypes.add("unit");
			notInTypes.add("template");
			queryFilter.addFilter("TYPE_", notInTypes, QueryOP.NOT_IN);//门户类型
			short type = -1;
			if(StringUtil.isNotEmpty(fromStr)) {//来自管理端或应用端或移动端
				type =  "manage".equals(fromStr)?SysIndexLayoutManage.TYPE_MNG:"mobile".equals(fromStr)?SysIndexLayoutManage.TYPE_MOBILE:SysIndexLayoutManage.TYPE_APPLICATION;
				queryFilter.addFilter("LAYOUT_TYPE", type, QueryOP.EQUAL);//门户类型
			}
			if(!user.isAdmin()) {
				List<String> authIds = sysAuthUserManager.getAuthorizeIdsByUserMap(SysAuthUser.BPMDEFUSER_OBJ_TYPE.LAYOUT_MANAGE);
				if(BeanUtils.isNotEmpty(authIds)) {
					queryFilter.addFilter("ID", authIds, QueryOP.IN);//有权限布局
				}
				queryFilter.addFilter("IS_DEF", 1, QueryOP.EQUAL, FieldRelation.AND, "defaultDef");//添加默认门户
				if(type!=-1) {
					queryFilter.addFilter("LAYOUT_TYPE", type, QueryOP.EQUAL, FieldRelation.AND, "defaultDef");//添加默认门户
				}
			}
//			queryFilter.getSorter().add(0, new FieldSort("RANK", Direction.ASC));
			queryFilter.getSorter().add(0, new FieldSort("RANK_", Direction.ASC));
			PageList<SysIndexLayoutManage> page = query(queryFilter);
			if(BeanUtils.isNotEmpty(page)) {
				authList = page.getRows();
			}
			if(BeanUtils.isNotEmpty(authList)) {
				for (SysIndexLayoutManage layout : authList) {
					IndexLayoutVo vo = new IndexLayoutVo(IndexLayoutVo.TYPE_SYS, layout.getId(), layout.getName(), layout.getAlias(), layout.getDesignHtml(), layout.getIsDef(), SysIndexLayoutManage.TYPE_APPLICATION, StringUtil.isNotEmpty(layout.getType())?layout.getType():SysIndexLayoutManage.LAYOUT_TYPE_COLUMN);
					authVoList.add(vo);
				}
			}
		}

		return authVoList;
	}

	@Override
	public CommonResult<String> importDatav(MultipartHttpServletRequest request, String orgId, boolean isDefault) {
		MultipartFile file = request.getFile("file");
		String uzPath = "";
		try {
			String rootRealPath = (FileUtil.getIoTmpdir() +"/attachFiles/unZip/").replace("/", File.separator);
			FileUtil.createFolder(rootRealPath, true);
			String name = file.getOriginalFilename();
			String fileDir = StringUtil.substringBeforeLast(name, ".");
			ZipUtil.unZipFile(file, rootRealPath); // 解压文件
			uzPath = rootRealPath + File.separator + fileDir; // 解压后文件的真正路径
			Boolean isRepeat = importDatavFile(uzPath, orgId, isDefault);
			if(!isRepeat){
				return new CommonResult<>(true,"confirmUpload",Base64.getBase64(uzPath));
			}
			return new CommonResult<>(true,"导入成功");
		}catch (Exception e){
			return new CommonResult(false,"导入失败："+e.getMessage());
		}finally {
			if (StringUtil.isNotEmpty(uzPath)) {
				File file1 = new File(uzPath);
				if (file1.exists()) {
					file1.delete();
				}
			}
		}
	}

	@Override
	public CommonResult<String> confirmImportData(String unZipFilePath, String status) {
		try {
			String json = FileUtil.readFile(Base64.getFromBase64(unZipFilePath) + File.separator + "orgLayout.json");
			List list = JsonUtil.toBean(json, List.class);
			ArrayList<SysIndexLayoutManage> sysIndexLayoutManages = new ArrayList<>();
			for (Object o : list) {
				SysIndexLayoutManage layout = JsonUtil.toBean(JsonUtil.toJson(o), SysIndexLayoutManage.class);
				sysIndexLayoutManages.add(layout);
			}
			for (SysIndexLayoutManage sysIndexLayoutManage : sysIndexLayoutManages) {
				SysIndexLayoutManage checkLayout = baseMapper.getDatavByAlias(sysIndexLayoutManage.getAlias());
				if (BeanUtils.isEmpty(checkLayout)) {
					sysIndexLayoutManage.setId(UniqueIdUtil.getSuid());
					checkLayout.setEnable(SysIndexLayoutManage.ENABLE);
					baseMapper.insert(checkLayout);
				}else {
					if ("cover".equals(status)) {  //else jump
						sysIndexLayoutManage.setId(checkLayout.getId());
						baseMapper.updateById(sysIndexLayoutManage);
					}
				}
			}

		} catch (Exception e){
			throw new BaseException(e.getMessage());
		}
		return new CommonResult<>(true, "导入成功");
	}

	private IndexLayoutVo getCacheLayout(short layoutType) {
		IndexLayoutVo vo = null;
		IUser user = ContextUtil.getCurrentUser();
		if(BeanUtils.isNotEmpty(user)) {
			String cacheValue = this.getCacheUserLayout(String.valueOf(layoutType), user.getUserId());
			if(StringUtil.isNotEmpty(cacheValue)) {
				String[] values = cacheValue.split("_");
				if(values.length==2) {
					if(IndexLayoutVo.TYPE_PERSONAL.equals(values[0])) {
						SysIndexMyLayout myLayout = sysIndexMylayoutService.get(values[1]);
						if(BeanUtils.isNotEmpty(myLayout)) {
							vo = new IndexLayoutVo(IndexLayoutVo.TYPE_PERSONAL, myLayout.getId(), myLayout.getName(), "", myLayout.getDesignHtml(), (short)0, layoutType, SysIndexLayoutManage.LAYOUT_TYPE_COLUMN);
						}
					}else if(IndexLayoutVo.TYPE_SYS.equals(values[0])) {
						SysIndexLayoutManage layout = this.get(values[1]);
						if(BeanUtils.isNotEmpty(layout)) {
							vo = new IndexLayoutVo(IndexLayoutVo.TYPE_SYS, layout.getId(), layout.getName(), layout.getAlias(), layout.getDesignHtml(), layout.getIsDef(), layoutType, StringUtil.isNotEmpty(layout.getType())?layout.getType():SysIndexLayoutManage.LAYOUT_TYPE_COLUMN);
						}
					}
					if(BeanUtils.isNotEmpty(vo)) {
						return vo;
					}
				}
			}
		}
		return vo;
	}

	/**
	 * 根据规则查询出布局
	 * @param layoutType 布局类型：
	 * @return
	 * @throws IOException
	 */
	private SysIndexLayoutManage traceLayout(Short layoutType) throws IOException {

		IUser user = ContextUtil.getCurrentUser();
		SysIndexLayoutManage layout =null;
		//1、获取主岗位、主组织（优先获取默认维度的主岗位、主组织，没有时获取其他维度的）；
//		ObjectNode mainPost = ucFeignService.getMainPostOrOrgByUserId(user.getUserId());
//		if(BeanUtils.isNotEmpty(mainPost)){
//			String orgId = JsonUtil.getString(mainPost, "orgId");
//			layout = sysIndexlayoutManageService.getEnableByOrgIdAndType(orgId, layoutType);
//		}
		//2、从父部门共享过来的；
//		if(BeanUtils.isEmpty(layout)){
//			ArrayNode myOrgs = ucFeignService.getOrgListByUserId(user.getUserId());
//			Set<String> shareOrgIds = new HashSet<>();
//			if(BeanUtils.isNotEmpty(myOrgs)){
//				for (Object org : myOrgs) {
//					String path = JsonUtil.toJsonNode(org).get("path").asText();
//					path = path.substring(0, path.length()-1);
//					String[] pathArr = path.replace(".", ",").split(",");
//					for(int i=pathArr.length-1;i >=0;i--){
//						shareOrgIds.add(pathArr[i]);
//					}
//				}
//				if(shareOrgIds.size() > 0) {
//					layout = sysIndexlayoutManageService.getSharedByOrgIds(new ArrayList<>(shareOrgIds), layoutType);
//				}
//			}
//		}

		//查找自己有权限的布局，按优先级获取
		if(BeanUtils.isNotEmpty(user)) {
			QueryFilter<SysIndexLayoutManage> queryFilter = QueryFilter.build();
			queryFilter.setGroupRelation(FieldRelation.OR);
			queryFilter.withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
			queryFilter.addFilter("ENABLE", 1, QueryOP.EQUAL);//启动的
			queryFilter.addFilter("LAYOUT_TYPE", layoutType, QueryOP.EQUAL);//门户类型
			queryFilter.addFilter("IS_DEF", 1, QueryOP.NOT_EQUAL);
			List<String> notInTypes = new ArrayList<String>();
			notInTypes.add("unit");
			notInTypes.add("template");
			queryFilter.addFilter("TYPE_", notInTypes, QueryOP.NOT_IN);//门户类型
			if(!user.isAdmin()) {
				List<String> authIds = sysAuthUserManager.getAuthorizeIdsByUserMap(SysAuthUser.BPMDEFUSER_OBJ_TYPE.LAYOUT_MANAGE);
				if(BeanUtils.isNotEmpty(authIds)) {
					queryFilter.addFilter("ID", authIds, QueryOP.IN);//有权限布局
				}
			}
//			queryFilter.getSorter().add(0, new FieldSort("RANK", Direction.ASC));
			queryFilter.getSorter().add(0, new FieldSort("RANK_", Direction.ASC));
			PageList<SysIndexLayoutManage> page = this.query(queryFilter);
			if(BeanUtils.isNotEmpty(page) && page.getRows().size()>0) {
				layout = page.getRows().get(0);
			}
		}

		//如果从部门树都查询不到布局，则获取系统默认布局。该默认布局系统初始化就有。
		if(BeanUtils.isEmpty(layout)){
			try{
				if(SysIndexLayoutManage.TYPE_MNG == layoutType){
					layout = this.getDefaultLayoutManageByLayoutType(SysIndexLayoutManage.MNG_DEFAULT_ID);
				}else if(SysIndexLayoutManage.TYPE_MOBILE == layoutType){
					layout = this.getDefaultLayoutManageByLayoutType(SysIndexLayoutManage.MOBILE_DEFAULT_ID);
				}else if(SysIndexLayoutManage.TYPE_APPLICATION == layoutType){
					layout = this.getDefaultLayoutManageByLayoutType(SysIndexLayoutManage.APPLICATION_DEFAULT_ID);
				}
			}
			catch(Exception e) {
				throw new BaseException(e.getMessage(),e);
			}
		}
		return layout;
	}
}
