package com.railway.business.catenary.util;

import com.railway.business.catenary.domain.BusJcab;
import com.railway.business.catenary.domain.BusJceb;
import com.railway.business.catenary.domain.vo.JcebQueryParamVo;
import com.railway.business.catenary.domain.vo.JcebQueryVo;
import com.railway.business.catenary.enums.JcebStatusEnum;
import com.railway.common.core.domain.entity.SysRole;
import com.railway.common.core.domain.entity.SysUser;
import com.railway.common.enums.PostTypeEnum;
import com.railway.common.utils.SecurityUtils;
import com.railway.framework.aspectj.DataScopeAspect;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;

/**
 * @author ZhaoMn
 */
public class JcebQueryUtil {

  private static JcebQueryParamVo getJcebQuery(){
    SysUser user = SecurityUtils.getLoginUser().getUser();
    // 管理员全部数据
    JcebQueryParamVo jcebQuery = new JcebQueryParamVo();
    if(user.isAdmin()){
      jcebQuery.setSubmitState(JcebStatusEnum.REPORTED.getCode());
      jcebQuery.setCreateBy(null);
      return jcebQuery;
    }
    // 角色数据权限
    String scope = DataScopeAspect.DATA_SCOPE_SELF;
    List<SysRole> roles = user.getRoles();
    if(CollectionUtils.isNotEmpty(roles)){
      for(SysRole role : roles){
        if(role.getDataScope().compareTo(scope) < 0){
          scope = role.getDataScope();
        }
      }
    }
    if(scope.equals(DataScopeAspect.DATA_SCOPE_ALL)){
      jcebQuery.setCreateBy(null);
      return jcebQuery;
    }
    // 职位
    String post = user.getPost();
    PostTypeEnum postType = PostTypeEnum.ofValue(post);
    jcebQuery.setDeptId(user.getDeptId());
    if(postType == PostTypeEnum.LEADER
        || scope.equals(DataScopeAspect.DATA_SCOPE_DEPT)
        || scope.equals(DataScopeAspect.DATA_SCOPE_DEPT_AND_CHILD)){
      jcebQuery.setSubmitState(JcebStatusEnum.REPORTED.getCode());
      jcebQuery.setCreateBy(null);
    }else {
      jcebQuery.setCreateBy(user.getUserName());
    }
    return jcebQuery;
  }

  public static void setBusJceb(BusJceb jceb){
    JcebQueryParamVo jcebQuery = getJcebQuery();
    jceb.setSubmitState(jcebQuery.getSubmitState());
    jceb.setDeptId(jcebQuery.getDeptId());
    jceb.setCreateBy(jcebQuery.getCreateBy());
  }

  public static void setBusJcab(BusJcab jcab){
    JcebQueryParamVo jcebQuery = getJcebQuery();
    jcab.setSubmitState(jcebQuery.getSubmitState());
    jcab.setDeptId(jcebQuery.getDeptId());
    jcab.setCreateBy(jcebQuery.getCreateBy());
  }

  public static void setBusJcebQuery(JcebQueryVo query){
    JcebQueryParamVo jcebQuery = getJcebQuery();
    query.setSubmitState(jcebQuery.getSubmitState());
    query.setDeptId(jcebQuery.getDeptId());
    query.setCreateBy(jcebQuery.getCreateBy());
  }

}
