package com.bonus.canteen.core.auth.config;

import cn.hutool.core.util.ObjectUtil;
import com.bonus.canteen.core.auth.enums.DataPermissionTypeEnum;
import com.bonus.canteen.core.auth.enums.RoleCodeV2Enum;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.security.utils.SecurityUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.HexValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.statement.select.PlainSelect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotatedElementUtils;

import java.lang.reflect.Method;
import java.util.Objects;

public class LeNiuDataPermissionHandler {
   private static final Logger log = LoggerFactory.getLogger(LeNiuDataPermissionHandler.class);

   public Expression getSqlSegment(PlainSelect plainSelect, String whereSegment){
      try {
         Expression where = plainSelect.getWhere();
         String className = whereSegment.substring(0, whereSegment.lastIndexOf("."));
         String methodName = whereSegment.substring(whereSegment.lastIndexOf(".") + 1);
         Method[] methods = Class.forName(className).getMethods();
         Method[] var7 = methods;
         int var8 = methods.length;

         for(int var9 = 0; var9 < var8; ++var9) {
            Method m = var7[var9];
            if (Objects.equals(m.getName(), methodName) || Objects.equals(m.getName() + "_COUNT", methodName)) {
               LeNiuDataPermission.List permissionAnnotations = (LeNiuDataPermission.List)AnnotatedElementUtils.findMergedAnnotation(m, LeNiuDataPermission.List.class);
               LeNiuDataPermission permissionAnnotation = (LeNiuDataPermission)AnnotatedElementUtils.findMergedAnnotation(m, LeNiuDataPermission.class);
               if (permissionAnnotations == null && permissionAnnotation == null) {
                  return where;
               } else {
                  Long userId = SecurityUtils.getUserId();
                  String roleCode = (String)SecurityUtils.getLoginUser().getRoles().stream().findFirst().orElse(null);
                  if (ObjectUtil.isEmpty(roleCode)) {
                     return new HexValue(" 1 = 2 ");
                  } else {
                     if (permissionAnnotations != null) {
                        LeNiuDataPermission[] var15 = permissionAnnotations.value();
                        int var16 = var15.length;

                        for(int var17 = 0; var17 < var16; ++var17) {
                           LeNiuDataPermission permission = var15[var17];
                           where = this.expressionLeNiuDataPermission(where, permission, userId, roleCode);
                        }
                     }

                     if (permissionAnnotation != null) {
                        where = this.expressionLeNiuDataPermission(where, permissionAnnotation, userId, roleCode);
                     }

                     return where;
                  }
               }
            }
         }

         where = new HexValue(" 1 = 2 ");
         return where;
      } catch (Exception var19) {
         log.error(var19.getMessage());
         throw new ServiceException("系统异常");
      }
   }

   private Expression expressionLeNiuDataPermission(Expression where, LeNiuDataPermission permission, Long userId, String roleCode) {
      DataPermissionTypeEnum permissionType = permission.permissionType();
      String alias = permission.alias();
      String sql = this.getSqlByAliasAndPermissionType(userId, roleCode, permissionType, alias);
      if (ObjectUtil.isNotEmpty(sql)) {
         if (ObjectUtil.isNull(where)) {
            where = new HexValue(sql);
         } else {
            where = new AndExpression((Expression)where, new HexValue(sql));
         }
      }

      return (Expression)where;
   }

   private String getSqlByAliasAndPermissionType(Long userId, String roleCode, DataPermissionTypeEnum permissionType, String alias) {
      StringBuilder sb = new StringBuilder();

      if (roleCode.startsWith(RoleCodeV2Enum.ROLE_ADMIN.key())) {
         return "";
      } else {
            if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_ORG, permissionType)) {
                  sb.append(" EXISTS ( ").append(" SELECT null FROM sys_role_dept it1")
                       .append(" LEFT JOIN sys_role it2 ON it2.role_id = it1.role_id")
                       .append(" LEFT JOIN sys_user_role it3 ON it1.role_id = it3.role_id")
                       .append(" WHERE it2.del_flag = 0 AND it2.role_key = '").append(roleCode)
                       .append("' AND it3.user_id = ").append(userId).append(" AND ")
                       .append(alias).append(".org_id = it1.dept_id)");
            } else if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_AREA, permissionType)) {
                  sb.append(" EXISTS ( ").append(" SELECT null FROM sys_role_area it1")
                       .append(" LEFT JOIN sys_role it2 ON it2.role_id = it1.role_id")
                       .append(" LEFT JOIN sys_user_role it3 ON it1.role_id = it3.role_id")
                       .append(" WHERE it2.del_flag = 0 AND it2.role_key = '").append(roleCode).append("'")
                       .append(" AND it3.user_id = ").append(userId).append(" AND ")
                       .append(alias).append(".area_id = it1.area_id)");
            } else if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_CANTEEN, permissionType)) {
                  sb.append(" EXISTS ( ").append(" SELECT null FROM sys_role_canteen it1")
                       .append(" LEFT JOIN sys_role it2 ON it2.role_id = it1.role_id")
                       .append(" LEFT JOIN sys_user_role it3 ON it1.role_id = it3.role_id")
                       .append(" WHERE it2.del_flag = 0 AND it2.role_key = '").append(roleCode).append("'")
                       .append(" AND it3.user_id = ").append(userId).append(" AND ")
                       .append(alias).append(".canteen_id = it1.data_id)");
            } else if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_SUPERMARKET, permissionType)) {
                  sb.append(" EXISTS ( ").append(" SELECT null FROM sys_role_canteen it1")
                       .append(" LEFT JOIN sys_role it2 ON it2.role_id = it1.role_id")
                       .append(" LEFT JOIN sys_user_role it3 ON it1.role_id = it3.role_id")
                       .append(" WHERE it2.del_flag = 0 AND it2.role_key = '").append(roleCode).append("'")
                       .append(" AND it3.user_id = ").append(userId).append(" AND ")
                       .append(alias).append(".supermarket_id = it1.data_id)");
            } else if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_STALL, permissionType)) {
                  sb.append(" EXISTS ( ").append(" SELECT null FROM sys_role_canteen it1")
                          .append(" LEFT JOIN sys_role it2 ON it2.role_id = it1.role_id")
                          .append(" LEFT JOIN sys_user_role it3 ON it1.role_id = it3.role_id")
                          .append(" WHERE it2.del_flag = 0 AND it2.role_key = '").append(roleCode)
                          .append("' AND it3.user_id = ").append(userId)
                          .append(" AND ").append(alias).append(".stall_id = it1.data_id)");
            } else if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_CANTEEN_STALL, permissionType)) {
                  sb.append(" EXISTS ( ").append(" SELECT null FROM sys_role_canteen it1")
                          .append(" LEFT JOIN sys_role it2 ON it2.role_id = it1.role_id")
                          .append(" LEFT JOIN sys_user_role it3 ON it1.role_id = it3.role_id")
                          .append(" WHERE it2.del_flag = 0 AND it2.role_key = '").append(roleCode)
                          .append("' AND it3.user_id = ").append(userId)
                          .append(" AND (").append(alias).append(".canteen_id = it1.data_id OR ")
                          .append(alias).append(".stall_id = it1.data_id ))");
            } else if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_WAREHOUSE, permissionType)) {
                  sb.append(" EXISTS ( ").append(" SELECT null FROM sys_role_warehouse it1")
                       .append(" LEFT JOIN sys_role it2 ON it2.role_id = it1.role_id")
                       .append(" LEFT JOIN sys_user_role it3 ON it1.role_id = it3.role_id")
                       .append(" WHERE it2.del_flag = 0 AND it2.role_key = '").append(roleCode).append("'")
                       .append(" AND it3.user_id = ").append(userId).append(" AND ")
                       .append(alias).append(".warehouse_id = it1.warehouse_id)");
            } else {
                  sb.append("1 = 2");
            }
      }

//      if (roleCode.startsWith(RoleCodeV2Enum.ROLE_ADMIN.key())) {
//         if (roleCode.split("&&").length <= 1) {
//            return "";
//         }
//
//         if (!ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_AREA, permissionType)) {
//            return "";
//         }
//
//         sb.append(" EXISTS ( ").append(" SELECT null FROM mgr_role_area it1").append(" LEFT JOIN mgr_role it2 ON it2.role_id = it1.role_id").append(" LEFT JOIN mgr_user_role it3 ON it1.role_id = it3.role_id").append(" WHERE it2.del_flag = 2 AND it2.role_code = '").append(roleCode).append("'").append(" AND it1.half_select = 1 AND it3.user_id = ").append(userId).append(" AND ").append(alias).append(".area_id = it1.data_id)");
//      } else if (roleCode.startsWith(RoleCodeV2Enum.ROLE_ORG.key())) {
//         if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_ORG, permissionType)) {
//            sb.append(" EXISTS ( ").append(" SELECT null FROM mgr_role_org it1").append(" LEFT JOIN mgr_role it2 ON it2.role_id = it1.role_id").append(" LEFT JOIN mgr_user_role it3 ON it1.role_id = it3.role_id").append(" WHERE it2.del_flag = 2 AND it2.role_code = '").append(roleCode).append("' AND it1.half_select = 1 AND it3.user_id = ").append(userId).append(" AND ").append(alias).append(".org_id = it1.org_id)");
//         }
//      } else if (roleCode.startsWith(RoleCodeV2Enum.ROLE_MERCHANT.key())) {
//         if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_CANTEEN, permissionType)) {
//            sb.append(" EXISTS ( ").append(" SELECT null FROM mgr_role_canteen it1").append(" LEFT JOIN mgr_role it2 ON it2.role_id = it1.role_id").append(" LEFT JOIN mgr_user_role it3 ON it1.role_id = it3.role_id").append(" WHERE it2.del_flag = 2 AND it2.role_code = '").append(roleCode).append("'").append(" AND it1.half_select = 1 AND it3.user_id = ").append(userId).append(" AND ").append(alias).append(".canteen_id = it1.data_id)");
//         } else if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_STALL, permissionType)) {
//            sb.append(" EXISTS ( ").append(" SELECT null FROM mgr_role_canteen it1").append(" LEFT JOIN mgr_role it2 ON it2.role_id = it1.role_id").append(" LEFT JOIN mgr_user_role it3 ON it1.role_id = it3.role_id").append(" WHERE it2.del_flag = 2 AND it2.role_code = '").append(roleCode).append("' AND it1.half_select = 1 AND it3.user_id = ").append(userId).append(" AND ").append(alias).append(".stall_id = it1.data_id)");
//         } else if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_CANTEEN_STALL, permissionType)) {
//            sb.append(" EXISTS ( ").append(" SELECT null FROM mgr_role_canteen it1").append(" LEFT JOIN mgr_role it2 ON it2.role_id = it1.role_id").append(" LEFT JOIN mgr_user_role it3 ON it1.role_id = it3.role_id").append(" WHERE it2.del_flag = 2 AND it2.role_code = '").append(roleCode).append("' AND it1.half_select = 1 AND it3.user_id = ").append(userId).append(" AND (").append(alias).append(".canteen_id = it1.data_id OR ").append(alias).append(".stall_id = it1.data_id ))");
//         } else if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_WAREHOUSE, permissionType)) {
//            sb.append(" EXISTS ( ").append(" SELECT null FROM mgr_role_warehouse it1").append(" LEFT JOIN mgr_role it2 ON it2.role_id = it1.role_id").append(" LEFT JOIN mgr_user_role it3 ON it1.role_id = it3.role_id").append(" WHERE it2.del_flag = 2 AND it2.role_code = '").append(roleCode).append("'").append(" AND it3.user_id = ").append(userId).append(" AND ").append(alias).append(".warehouse_id = it1.warehouse_id)");
//         } else if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_SUPERMARKET, permissionType)) {
//            sb.append(" EXISTS ( ").append(" SELECT null FROM mgr_role_canteen it1").append(" LEFT JOIN mgr_role it2 ON it2.role_id = it1.role_id").append(" LEFT JOIN mgr_user_role it3 ON it1.role_id = it3.role_id").append(" WHERE it2.del_flag = 2 AND it2.role_code = '").append(roleCode).append("'").append(" AND it1.half_select = 1 AND it3.user_id = ").append(userId).append(" AND ").append(alias).append(".supermarket_id = it1.data_id)");
//         } else if (ObjectUtil.equal(DataPermissionTypeEnum.PERMISSION_AREA, permissionType)) {
//            sb.append(" EXISTS ( ").append(" SELECT null FROM mgr_role_area it1").append(" LEFT JOIN mgr_role it2 ON it2.role_id = it1.role_id").append(" LEFT JOIN mgr_user_role it3 ON it1.role_id = it3.role_id").append(" WHERE it2.del_flag = 2 AND it2.role_code = '").append(roleCode).append("'").append(" AND it1.half_select = 1 AND it3.user_id = ").append(userId).append(" AND ").append(alias).append(".area_id = it1.data_id)");
//         }
//      } else {
//         sb.append("1 = 2");
//      }

      return sb.toString();
   }
}
