package com.zcxk.org;

import com.zcxk.client.UserCenterClient;
import com.zcxk.util.RedisUtil;
import com.zcxk.util.UserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class OrgInfoUtil {

    private static final String REDIS_CACHE_KEY_ORGINFO = "orgInfo%s";

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserCenterClient userCenterClient;

    public String getOrgName(Integer id) {
        String tenantId = UserUtil.getCurrentUser().getTenantId();
        if(tenantId == null){
            return "";
        }
        String key = String.format(REDIS_CACHE_KEY_ORGINFO, tenantId);
        String keysValue = (String) redisUtil.getHashValues(key,id+"");
        if (keysValue == null) {
            Map<String,String> keysValues = updateOrgInfo(key);
            keysValue = keysValues.get(id+"");
        }
        return keysValue;
    };
    public Map<String,String> getAllOrgName(){
        String tenantId = UserUtil.getCurrentUser().getTenantId();
        if (tenantId == null) {
            return new HashMap<>();
        }
        String key = String.format(REDIS_CACHE_KEY_ORGINFO, tenantId);
        Map<String, String> hashValue = redisUtil.getHashValue(key);
        if (hashValue.size() == 0) {
            hashValue = updateOrgInfo(key);
        }
        return hashValue;
    }

    private Map<String,String> updateOrgInfo(String key){
        Map<String,String> keysValues= new HashMap<>();
        List<Org> orgs = userCenterClient.getAllByTenantId();
        for (Org org1 : orgs) {
            keysValues.put(org1.getId() + "",org1.getOrgName());
        }
        redisUtil.putHashValues(key,keysValues);
        return keysValues;
    }
    public Integer getOrgCompanyId(Integer id) {
        Integer parentId = null;
        Org org = userCenterClient.selectOne(id).getData();
        Org parentOrg = new Org();
        BeanUtils.copyProperties(org,parentOrg);
        while ("department".equals(parentOrg.getOrgType())) {
            if (parentOrg.getParentOrgId().equals(0)|| parentOrg.getParentOrgId()==null) {
                break;
            }
            Org temp = userCenterClient.selectOne(parentOrg.getParentOrgId()).getData();
            parentOrg.setOrgType(temp.getOrgType());
            parentOrg.setId(temp.getId());
            parentOrg.setParentOrgId(temp.getParentOrgId());
            if ("company".equals(temp.getOrgType())) {
                parentId = temp.getId();
            }
        }
        return parentId;
    }
}
