package ${basePackage}.module.system.mgr;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ${basePackage}.config.CacheConfig;
import ${basePackage}.frame.base.ErrorType;
import ${basePackage}.frame.auth.Token;
import ${basePackage}.frame.base.SortType;
import ${basePackage}.frame.utils.IDgenerator;
import ${basePackage}.frame.utils.MapperUtil;
import ${basePackage}.frame.utils.Message;
import ${basePackage}.frame.utils.ValidationUtil;
import ${basePackage}.module.system.ent.Tokens;
import ${basePackage}.module.system.mpr.TokensMapper;
import ${basePackage}.module.system.req.ResFindRequest;
import ${basePackage}.module.system.req.TokensBuildRequest;
import ${basePackage}.module.system.req.TokensCreateRequest;
import ${basePackage}.module.system.req.TokensDeleteRequest;
import ${basePackage}.module.system.req.TokensFindRequest;
import ${basePackage}.module.system.req.TokensGetRequest;
import ${basePackage}.module.system.req.TokensLogoutRequest;
import ${basePackage}.module.system.req.TokensUpdateRequest;
import ${basePackage}.module.system.rsp.ResFindResponse;
import ${basePackage}.module.system.rsp.TokensBuildResponse;
import ${basePackage}.module.system.rsp.TokensCreateResponse;
import ${basePackage}.module.system.rsp.TokensDeleteResponse;
import ${basePackage}.module.system.rsp.TokensFindResponse;
import ${basePackage}.module.system.rsp.TokensGetResponse;
import ${basePackage}.module.system.rsp.TokensLogoutResponse;
import ${basePackage}.module.system.rsp.TokensUpdateResponse;

/**
 * TOKENS - 通行证
 *
 * @author author
 * @version 0.0.1
 * @since 2017-01-01
 */
@Transactional
@Service
public class TokensManagerImpl implements ${basePackage}.module.system.mgr.TokensManager {

    @Value("${r'${web.url.auth.admin}'}")
    private String admin;
    @Autowired
    private TokensMapper tokensMapper;
    @Autowired
    private UserRoleManager userRoleManager;
    @Autowired
    private ResManager resManager;

    /**
     * 插入
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public TokensCreateResponse create(TokensCreateRequest request, Token token) {
        TokensCreateResponse response = new TokensCreateResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        {// 检查是否有其他登录信息，是否多端登录，并注销
            TokensFindRequest tokensFindRequest = new TokensFindRequest();
            tokensFindRequest.setUserId(request.getUserId());
            tokensFindRequest.setUserName(request.getUserName());
            tokensFindRequest.setValid(true);
            tokensFindRequest.setTerminalType(request.getTerminalType());
            tokensFindRequest.setPageSize(0);
            tokensFindRequest.setSortKey("CREATE_TIME");
            tokensFindRequest.setSortType(SortType.ASC);
            TokensFindResponse tokensFindResponse = this.find(tokensFindRequest, token);
            if (tokensFindResponse.hasError()) {
                response.addErrors(tokensFindResponse.getErrors());
                return response;
            }

            for (Tokens tokens : tokensFindResponse.getResult()) {
                TokensLogoutRequest tokensLogoutRequest = new TokensLogoutRequest();
                tokensLogoutRequest.setToken(tokens.getToken());
                TokensLogoutResponse tokensLogoutResponse = this.logout(tokensLogoutRequest, token);
                if (tokensLogoutResponse.hasError()) {
                    response.addErrors(tokensLogoutResponse.getErrors());
                    return response;
                }
            }
        }

        long id = IDgenerator.nextId();
        Tokens entity = MapperUtil.map(request, Tokens.class);
        entity.setId(id);

        long result = tokensMapper.insert(entity, token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.CREATE_FAILURE);
            return response;
        }
        response.setId(id);

        return response;
    }

    /**
     * 逻辑删除
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    @CacheEvict(value = CacheConfig.TOKEN_CACHE, key = "#request.token", condition = "!#result.hasError()")
    public TokensDeleteResponse delete(TokensDeleteRequest request, Token token) {
        TokensDeleteResponse response = new TokensDeleteResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        long result = tokensMapper.delete(request, token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.DELETE_FAILURE);
            return response;
        }
        response.setResult(result);

        return response;
    }

    /**
     * 更新
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    @CacheEvict(value = CacheConfig.TOKEN_CACHE, key = "#request.token", condition = "!#result.hasError()")
    public TokensUpdateResponse update(TokensUpdateRequest request, Token token) {
        TokensUpdateResponse response = new TokensUpdateResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        long result = tokensMapper.update(request, token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.UPDATE_FAILURE);
            return response;
        }
        response.setResult(result);

        return response;
    }

    /**
     * 查询
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    @Transactional(readOnly = true)
    public TokensFindResponse find(TokensFindRequest request, Token token) {
        TokensFindResponse response = new TokensFindResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        if (request.getPageSize() != 0) {
            PageHelper.startPage(request.getPageNumber(), request.getPageSize());
        }
        if (StringUtil.isNotEmpty(request.getSortKey())) {
            PageHelper.orderBy(request.getSortKey() + " " + request.getSortType());
        }
        PageInfo<Tokens> pageInfo = new PageInfo<>(tokensMapper.find(request, token));

        response.setResult(pageInfo.getList());
        response.setTotalCount(pageInfo.getTotal());

        return response;
    }

    /**
     * 获得对象
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    @Transactional(readOnly = true)
    public TokensGetResponse get(TokensGetRequest request, Token token) {
        TokensGetResponse response = new TokensGetResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        Tokens po = tokensMapper.get(request, token);

        if (po != null) {
            response.setTokens(po);
        } else {
            response.addError(ErrorType.BUSINESS_ERROR, Message.GET_FAILURE);
        }

        return response;
    }

    /**
     * 构建Token
     *
     * @param request 请求对象
     * @param token   令牌
     * @return
     */
    @Override
    @Cacheable(value = CacheConfig.TOKEN_CACHE, key = "#request.token", unless = "#result.hasError()")
    public TokensBuildResponse build(TokensBuildRequest request, Token token) {
        TokensBuildResponse response = new TokensBuildResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        TokensFindRequest tokensFindRequest = MapperUtil.map(request, TokensFindRequest.class);
        tokensFindRequest.setValid(true);
        TokensFindResponse tokensFindResponse = this.find(tokensFindRequest, token);
        if (tokensFindResponse.hasError()) {
            response.addErrors(tokensFindResponse.getErrors());
            return response;
        }

        if (tokensFindResponse.getResult().size() == 0) {
            response.addError(ErrorType.BUSINESS_ERROR, "令牌无效或不存在");
            return response;
        } else if (tokensFindResponse.getResult().size() > 1) {
            response.addError(ErrorType.BUSINESS_ERROR, "令牌异常");
            return response;
        } else {
            Tokens tokens = tokensFindResponse.getResult().get(0);
            Token newToken = new Token();
            if (tokens.getUserName().equals(admin)) {//超级管理员
                newToken.setId(0);
                newToken.setToken(tokensFindResponse.getResult().get(0).getToken());
                newToken.setUserId(0);
                newToken.setUserName(admin);
                newToken.putRes(".*");

                // 获取用户的资源
                ResFindRequest resFindRequest = new ResFindRequest();
                resFindRequest.setPageSize(0);
                ResFindResponse resFindResponse = resManager.find(resFindRequest, token);
                if (resFindResponse.hasError()) {
                    response.addErrors(resFindResponse.getErrors());
                    return response;
                }
                newToken.putRes(resFindResponse.getResult());
            } else { // 管理员或用户
                newToken.setId(tokens.getId());
                newToken.setToken(tokensFindResponse.getResult().get(0).getToken());
                newToken.setUserId(tokens.getUserId());
                newToken.setUserName(tokens.getUserName());

                // 获取用户的资源
                ResFindRequest resFindRequest = new ResFindRequest();
                resFindRequest.setPageSize(0);
                resFindRequest.setUserId(tokens.getUserId());
                ResFindResponse resFindResponse = resManager.find(resFindRequest, token);
                if (resFindResponse.hasError()) {
                    response.addErrors(resFindResponse.getErrors());
                    return response;
                }
                newToken.putRes(resFindResponse.getResult());
            }

            response.setToken(newToken);
        }

        return response;
    }

    @Override
    @CacheEvict(value = CacheConfig.TOKEN_CACHE, key = "#request.token", condition = "!#result.hasError()")
    public TokensLogoutResponse logout(TokensLogoutRequest request, Token token) {
        TokensLogoutResponse response = new TokensLogoutResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        if (request.getToken().equals(token.getToken())) {
            response.addError(ErrorType.BUSINESS_ERROR, "无法注销当前登录用户!");
            return response;
        }

        TokensFindRequest tokensFindRequest = MapperUtil.map(request, TokensFindRequest.class);
        tokensFindRequest.setValid(true);
        TokensFindResponse tokensFindResponse = this.find(tokensFindRequest, token);
        if (tokensFindResponse.hasError()) {
            response.addErrors(tokensFindResponse.getErrors());
            return response;
        }

        for (Tokens tokens : tokensFindResponse.getResult()) {
            TokensUpdateRequest tokensUpdateRequest = MapperUtil.map(tokens, TokensUpdateRequest.class);
            tokensUpdateRequest.setValid(false);
            long result = tokensMapper.update(tokensUpdateRequest, token);
            if (1L != result) {
                response.addError(ErrorType.BUSINESS_ERROR, Message.UPDATE_FAILURE);
                return response;
            }
        }

        return response;
    }
}
