/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.common.aspect;


import io.renren.common.annotation.DataFilter;
import io.renren.common.annotation.PlantDataFilter;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Constant;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysDeptService;
import io.renren.modules.sys.service.SysRoleDeptService;
import io.renren.modules.sys.service.SysUserPlantService;
import io.renren.modules.sys.service.SysUserRoleService;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 数据过滤，切面处理类
 *
 * @author Mark 735032128@qq.com
 */
@Aspect
@Component
public class PlantDataFilterAspect {
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserPlantService sysUserPlantService;
    @Autowired
    private SysRoleDeptService sysRoleDeptService;

    @Pointcut("@annotation(io.renren.common.annotation.PlantDataFilter)")
    public void dataFilterCut() {

    }

    @Before("dataFilterCut()")
    public void dataFilter(JoinPoint point) throws Throwable {
        Object params = point.getArgs()[0];
        if (params != null && params instanceof Map) {
            SysUserEntity user = ShiroUtils.getUserEntity();

            //如果不是超级管理员，则进行数据过滤
            if (user.getUserId() != Constant.SUPER_ADMIN) {
                Map map = (Map) params;
                map.put(Constant.SQL_FILTER, getSQLFilter(user, point));
            }

            return;
        }

        throw new RRException("数据权限接口，只能是Map类型参数，且不能为NULL");
    }

    /**
     * 获取数据过滤的SQL
     */
    private String getSQLFilter(SysUserEntity user, JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        PlantDataFilter dataFilter = signature.getMethod().getAnnotation(PlantDataFilter.class);
        //获取表的别名
        String tableAlias = dataFilter.tableAlias();
        if (StringUtils.isNotBlank(tableAlias)) {
            tableAlias += ".";
        }

        //装置ID名称列表
        Set<String> plantNameList = new HashSet<>();

        //用户角色对应的部门ID列表
        List<String> plantList = sysUserPlantService.queryPlantNameList(user.getUserId());

        //用户子部门ID列表
//        if (dataFilter.subDept()) {
//            List<Long> subDeptIdList = sysDeptService.getSubDeptIdList(user.getDeptId());
//            plantNameList.addAll(subDeptIdList);
//        }

        StringBuilder sqlFilter = new StringBuilder();
        sqlFilter.append(" (");

        if (plantList.size() > 0) {
            for (String s : plantList
            ) {
                s = "'" + s + "'";
                plantNameList.add(s);
            }
            sqlFilter.append(tableAlias).append(dataFilter.plantCode()).append(" in(").append(StringUtils.join(plantNameList, ",")).append(")");
        }

        //没有本部门数据权限，也能查询本人数据
        if (dataFilter.user()) {
            if (plantNameList.size() > 0) {
                sqlFilter.append(" or ");
            }
            sqlFilter.append(tableAlias).append(dataFilter.userId()).append("=").append(user.getUserId());
        }

        sqlFilter.append(")");

        if (sqlFilter.toString().trim().equals("()")) {
            return null;
        }

        return sqlFilter.toString();
    }
}
