package com.zzwtec.wechat.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zzwtec.third.model.permission.dto.ObjRelationDTO;
import com.zzwtec.third.utils.StringUtil;
import com.zzwtec.wechat.config.WeChatConfig;
import com.zzwtec.wechat.rpc.APIResponse;
import com.zzwtec.wechat.rpc.api.APIService;
import com.zzwtec.wechat.rpc.inject.ProxyBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName LoginService
 * @Author Administrator
 * @Date 2018/12/20 0020 10:41
 */
@Service
public class LoginService {

    @Value("${sysUser.username}")
    private String userName;
    @Value("${sysUser.password}")
    private String pwd;
    private static final APIService apiService = ProxyBuilder.build(APIService.class, WeChatConfig.weChatConfig);
    @Autowired
    private StringRedisTemplate redisTemplate;

    public  String getLoginToken(){
        String tokenId=redisTemplate.opsForValue().get("adminTokenId");
        if(StringUtil.isEmpty(tokenId)){
            tokenId=getNewToken();
        }
        return tokenId;
    }
    //
    public String getNewToken(){
        String adminTokenId="";
//        String propertyId="";
        String communityIds="";
        APIResponse response = apiService.adminLogin(userName,pwd);
        if (response.isSuccess()) {
            System.out.println(response.getData());
            adminTokenId= JSONObject.parseObject(response.getData()).getString("tokenId");
//            propertyId= JSONObject.parseObject(response.getData()).getString("propertyId");
            JSONArray dataAuthList=JSONObject.parseObject(response.getData()).getJSONArray("dataAuthList");
            for(int i=0;i<dataAuthList.size();i++){
                if(i>=1) communityIds+=",";
                communityIds+= JSONObject.parseObject(dataAuthList.get(i)+"").getString("objId");
            }

        }
        redisTemplate.opsForValue().set("adminTokenId", adminTokenId);
        redisTemplate.opsForValue().set("adminCommunityIds", communityIds);
        redisTemplate.expire("adminTokenId", 20, TimeUnit.MINUTES);
        redisTemplate.expire("adminCommunityIds", 20, TimeUnit.MINUTES);
        return adminTokenId;
    }



}
