package com.yeejoin.amos.boot.module.hygf.api.config;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.hygf.api.dto.UserUnitInformationDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.RegionalCompanies;
import com.yeejoin.amos.boot.module.hygf.api.entity.StdUserEmpower;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PersonnelBusinessMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.RegionalCompaniesMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.UserEmpowerMapper;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: tw
 * @createDate: 2023/11/9
 */
@Aspect
@Order(0)// 保证该AOP在@Transactional之前执行
@Component
@Slf4j
public class UserLimitsAdvice {

    @Autowired
    private UserEmpowerMapper userEmpowerMapper;
    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;
    @Autowired
    RegionalCompaniesMapper regionalCompaniesMapper;
    @Autowired
    private RedisUtils redisUtils;

    private static final String ROLEFLAG="-经销商-";

    private static final String FARMER="-农户";
    private static final String ROLEFLAGADMIN="-经销商-管理员";

    private static final String ROLEFLDEVELOP="-经销商-开发";
    private static final String MAINTENANCE="-运维人员";

    //调用的方法有该注解才会拦截
    @Pointcut("@annotation(com.yeejoin.amos.boot.module.hygf.api.config.UserLimits)")
    private void annotationPointCut() {
    }


    //环绕 满足上面的拦截条件就会调用该方法
    @Around("annotationPointCut()")
    public Object annotationAround(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取方法
        String userid=RequestContext.getExeUserId();
        StdUserEmpower stdUserEmpower=new StdUserEmpower();
        ReginParams reginParams=  JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        //判断是否经销商，经销商跟管理端互斥
        String org= reginParams.getUserModel().getOrgNames();
        if(org.contains(ROLEFLAG)){
           UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto(userid);
            stdUserEmpower.setFlag(false);
            stdUserEmpower.setDeveloperId(userUnitInformationDto!=null?userUnitInformationDto.getAmosUnitInfoId():null);
            stdUserEmpower.setRegionalCompaniesCode(userUnitInformationDto!=null?userUnitInformationDto.getRegionalCompaniesCode():null);
            stdUserEmpower.setAmosOrgCode(Arrays.asList(userUnitInformationDto.getAmosDealerOrgCode()));
            int num = StringUtils.countMatches(org, ROLEFLAG);
            if (org.contains(ROLEFLDEVELOP)  && num<2 ){
                stdUserEmpower.setUserId(userid);
            }
            else if  (org.contains(ROLEFLAGADMIN)){
                LambdaQueryWrapper<RegionalCompanies> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(RegionalCompanies::getUnitInfoId,userUnitInformationDto!=null?userUnitInformationDto.getAmosUnitInfoId():null);
                queryWrapper.eq(BaseEntity::getIsDelete,0);
                List<RegionalCompanies> regionalCompanies = regionalCompaniesMapper.selectList(queryWrapper);
                if (CollectionUtils.isNotEmpty(regionalCompanies)){
                    List<String> regionalCompaniesCodes = regionalCompanies.stream().map(RegionalCompanies::getRegionalCompaniesCode).collect(Collectors.toList());
                    stdUserEmpower.setAdminRegionalCompaniesCode(String.join(",",regionalCompaniesCodes));
                }
            } else {
                stdUserEmpower.setAdminRegionalCompaniesCode(stdUserEmpower.getRegionalCompaniesCode());

            }
        }else if(org.contains(FARMER)){
             //农户暂不做需求
            stdUserEmpower.setFarmer(true);


        } else if(org.contains(MAINTENANCE)) {
//          运维人员
            UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getMaintenanceUserUnitInformationDto(userid);
            stdUserEmpower.setFlag(false);
            stdUserEmpower.setDeveloperId(userUnitInformationDto!=null?userUnitInformationDto.getAmosUnitInfoId():null);
            stdUserEmpower.setRegionalCompaniesCode(userUnitInformationDto!=null?userUnitInformationDto.getRegionalCompaniesCode():null);
            stdUserEmpower.setAmosOrgCode(Arrays.asList(userUnitInformationDto.getAmosDealerOrgCode()));
            stdUserEmpower.setUserId(userid);

        } else{
            LambdaQueryWrapper<StdUserEmpower> qu=new LambdaQueryWrapper();
            qu.eq(StdUserEmpower::getAmosUserId,userid);
            qu.eq(StdUserEmpower::getPermissionType,"HYGF");
            stdUserEmpower= userEmpowerMapper.selectOne(qu);
            if(stdUserEmpower==null){
                stdUserEmpower=new StdUserEmpower();
            }
            stdUserEmpower.setFlag(true);
            //获取外部不选数据
            List<Map<String,String>> lis=userEmpowerMapper.georgcodelist(stdUserEmpower.getEliminateAmosOrgCode());
            stdUserEmpower.setNOeliminateAmosOrgCode(lis!=null?lis.stream().map(t -> t.get("orgCode").toString()).collect(Collectors.toList()):null);
        }
       // UserEmpowerThreadLocal.setDataAuthRule(stdUserEmpower!=null?stdUserEmpower:null);


        redisUtils.set("Emp_"+RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken()),stdUserEmpower!=null?stdUserEmpower:null);

        //正常往后执行
        return joinPoint.proceed();
    }


}