package com.xintong.visualinspection.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.xintong.visualinspection.bean.Role;
import com.xintong.visualinspection.bean.User;
import com.xintong.visualinspection.service.UserService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.xintong.visualinspection.bean.Constant;
import com.xintong.visualinspection.bean.Permission;
import com.xintong.visualinspection.dao.cluster.UserInfoDao;
import com.xintong.visualinspection.dao.master.PermissionDao;
import com.xintong.visualinspection.dao.master.RoleDao;
import com.xintong.visualinspection.dao.master.UserDao;
import com.xintong.visualinspection.pojo.SimpleGrantedAuthority;
import com.xintong.visualinspection.service.BaseService;
import com.xintong.visualinspection.util.CodeUtil;

import lombok.Data;

/**
 * 文件名：UserServiceImpl
 * 版本信息：日期：2017/3/30 Copyright 江苏省交通规划设计院 Corporation 2017 版权所有.
 */
@Service
@Data
@com.alibaba.dubbo.config.annotation.Service(
		version = "1.0.0",
		application = "${dubbo.application.id}",
		protocol = "${dubbo.protocol.id}",
		registry = "${dubbo.registry.id}"
)
public class UserServiceImpl extends BaseService implements UserService {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(UserService.class);


    @Autowired
    private UserDao userDao;

    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<User> getAll() {
    	List<User> users = userInfoDao.getAll();
    	if(users!=null && users.size()>0){
    		for(User u :users){
    			u.setPassword(null);
    		}
    	}
        return users;
    }
    
	@Override
	public List<User> getUsers(User user) {
		//获取权限
		
		List<User> users= userInfoDao.getUsers(user);
		if(users!=null && users.size()>0){
			for(User u : users){
				u.setPassword(null);
				List<Permission> permissions = permissionDao.findByAdminUserId(u.getId());
	            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
	            List<Role> roles = roleDao.getRoleByUser(u.getId());
	            u.setRoles(roles);
	            for (Permission permission : permissions) {
	                if (permission != null && permission.getName() != null) {
	                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());
	                    grantedAuthorities.add(grantedAuthority);
	                }
	            }
	            u.setGrantedAuthorities(grantedAuthorities);
			}
		}
		return users;
		
		
		
	}


    @Override
//    @Cacheable(value = "usercache",keyGenerator = "keyGenerator")
    public User getOne(Integer id) {
    	return userInfoDao.getOne(id);
    }

    @Override
    public void insert(User user) {
    	userInfoDao.insert(user);
    }

    @Override
    public void update(User user) {
    	userInfoDao.update(user);
    }

    @Override
    public void delete(Integer id) {
    	userInfoDao.delete(id);
    }


    @Override
    public UserDetails loadUserByUsername(String username) {
        User user = userInfoDao.findByUserName(username);
        if (user != null) {
            List<Permission> permissions = permissionDao.findByAdminUserId(user.getId());
            List<Role> roles = roleDao.getRoleByUser(user.getId());
            user.setRoles(roles);
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            for (Permission permission : permissions) {
                if (permission != null && permission.getName() != null) {

                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());
                    grantedAuthorities.add(grantedAuthority);
                }
            }
            user.setGrantedAuthorities(grantedAuthorities);
            return user;
        } else {
            throw new UsernameNotFoundException("admin: " + username + " do not exist!");
        }

    }

	@Override
	public int queryCountByJob(User user) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<User> getAllCheckmans() {
		// TODO Auto-generated method stub
		return userInfoDao.getAllCheckmans();
	}
	
	@Override
	public List<User> getFsUserByDeptId(User user) {
		// TODO Auto-generated method stub
		Constant t =  CodeUtil.getCodeByFlagAndValue("feestation_check_jobs", "1");
		
		String[] postions = t.getCode_name().split(",");
		List<Integer> positionList = new ArrayList<Integer>();
		for(int i =0 ;i<postions.length;i++){
			positionList.add(Integer.parseInt(postions[i]));
		}

		user.setPosition_ids(positionList);
		return userInfoDao.getUsers(user);
	}

	@Override
	public List<User> getWGUserByDeptId(User user) {
		Constant t =  CodeUtil.getCodeByFlagAndValue("wrecker_group_check_jobs", "1");
		
		String[] postions = t.getCode_name().split(",");
		List<Integer> positionList = new ArrayList<Integer>();
		for(int i =0 ;i<postions.length;i++){
			positionList.add(Integer.parseInt(postions[i]));
		}

		user.setPosition_ids(positionList);
		return userInfoDao.getUsers(user);
	}
}
