package com.hotent.portal.service.impl;

import com.hotent.base.exception.BaseException;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.*;
import com.hotent.base.util.BeanUtils;
import com.hotent.base.util.StringUtil;
import com.hotent.portal.model.SysIndexLayoutManage;
import com.hotent.portal.model.SysIndexMyLayout;
import com.hotent.portal.params.IndexLayoutVo;
import com.hotent.portal.persistence.manager.SysIndexLayoutManageManager;
import com.hotent.portal.persistence.manager.SysIndexMyLayoutManager;
import com.hotent.portal.service.MainPortalService;
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.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Service
public class MainPortalServiceImpl implements MainPortalService {

    @Resource
    SysIndexLayoutManageManager sysIndexlayoutManageService;
    @Resource
    private SysAuthUserManager sysAuthUserManager;
    @Resource
    SysIndexMyLayoutManager sysIndexMylayoutService;

    @Override
    public CommonResult<IndexLayoutVo> myHome() {
        IndexLayoutVo vo = null;
        //1、首先查询缓存中是否存在
        vo = getCacheLayout(SysIndexLayoutManage.TYPE_MNG);
        if(BeanUtils.isNotEmpty(vo)) {
            return new CommonResult<IndexLayoutVo>(true,"获取成功！",vo);
        }
        SysIndexLayoutManage layout = null;
        try {
            layout = this.traceLayout(SysIndexLayoutManage.TYPE_MNG);
        } catch (IOException e) {
            e.printStackTrace();
        }
        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 IOException {
        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 IOException {
        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);
    }

    private IndexLayoutVo getCacheLayout(short layoutType) {
        IndexLayoutVo vo = null;
        IUser user = ContextUtil.getCurrentUser();
        if(BeanUtils.isNotEmpty(user)) {
            String cacheValue = sysIndexlayoutManageService.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 = sysIndexlayoutManageService.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 = sysIndexlayoutManageService.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 = sysIndexlayoutManageService.getDefaultLayoutManageByLayoutType(SysIndexLayoutManage.MNG_DEFAULT_ID);
                }else if(SysIndexLayoutManage.TYPE_MOBILE == layoutType){
                    layout = sysIndexlayoutManageService.getDefaultLayoutManageByLayoutType(SysIndexLayoutManage.MOBILE_DEFAULT_ID);
                }else if(SysIndexLayoutManage.TYPE_APPLICATION == layoutType){
                    layout = sysIndexlayoutManageService.getDefaultLayoutManageByLayoutType(SysIndexLayoutManage.APPLICATION_DEFAULT_ID);
                }
            }
            catch(Exception e) {
                throw new BaseException(e.getMessage(),e);
            }
        }
        return layout;
    }
}
