package com.casic.missiles.modular.system.handler;

import com.alibaba.fastjson.JSON;
import com.casic.missiles.core.common.service.ICommonPermissionService;
import com.casic.missiles.core.handler.BizCheckLoginHandler;
import com.casic.missiles.core.shiro.ShiroUser;
import com.casic.missiles.core.support.BeanKit;
import com.casic.missiles.core.util.ToolUtil;
import org.apache.shiro.authc.LockedAccountException;
import org.beetl.ext.fn.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@DependsOn("loadDatabasePropertyConfig")
public class LoginCheckHandler implements BizCheckLoginHandler {
    private static final Logger logger = LoggerFactory.getLogger(LoginCheckHandler.class);
    @Value("${smartcity.leaderRoleName}")
    private String leaderRoleName;
    @Value("${smartcity.memberRoleName}")
    private String memberRoleName;
    @Value(value = "${casic.server.ips}")
    private String[] serverIps;
    @Value(value = "${casic.server.ids}")
    private String[] deptIds;
    private List<Long> pids;
    @Value("${casic.session-invalidate-time:86400}")
    private Long sessionTime;
    @Lazy
    @Autowired
    private ICommonPermissionService service;
    @Lazy
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void checkUser(ShiroUser shiroUser, Boolean isApp) {
        if (isApp) {
            if (!shiroUser.getRoleTips().contains(leaderRoleName) && !shiroUser.getRoleTips().contains(memberRoleName)) {
                logger.error("APP用户业务权限角色校验未通过");
                throw new LockedAccountException("当前用户未授权，请联系管理员");
            }
        }
        if (pids == null) {
            //转换访问数组
            pids = new ArrayList<>();
            for (String deptId : deptIds) {
                pids.add(new Long(deptId));
            }
        }
        //设置登录用户所属服务器组别
        List<Long> pids = service.getParentDeptIds(shiroUser.getDeptId());
        pids.add(shiroUser.getDeptId());
        String ip = getServerIp(pids);
//        System.out.println(redisTemplate.getValueSerializer());
        redisTemplate.opsForValue().set("token:HOST_"+service.getShiroSession().getId(), JSON.toJSONString(ip),sessionTime, TimeUnit.MILLISECONDS);
    }
    /**
     * 获取用户服务id信息
     *
     * @param parentIds
     * @return
     */
    private String getServerIp(List<Long> parentIds) {
        for (int i = 0; i < pids.size(); i++) {
            if (parentIds.contains(pids.get(i))) {
                return serverIps[i];
            }
        }
        return serverIps[serverIps.length - 1];
    }

}
