package com.yanzhu.flowable.rpc;

import com.yanzhu.common.core.constant.SecurityConstants;
import com.yanzhu.common.core.domain.R;
import com.yanzhu.common.core.exception.ServiceException;
import com.yanzhu.common.core.utils.bean.BeanUtils;
import com.yanzhu.common.core.web.domain.BaseEntity;
import com.yanzhu.system.api.domain.SysRole;
import com.yanzhu.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class RemoteSystemService {

    @Autowired
    private IRemoteSystemService remoteSystemService;

    private <T> List<T> resultToList(R<List<T>> dataResult) {
        if (R.FAIL == dataResult.getCode()) {
            throw new ServiceException(dataResult.getMsg());
        }
        return dataResult.getData();
    }

    private <T> T resultToBean(R<T> dataResult) {
        if (R.FAIL == dataResult.getCode()) {
            throw new ServiceException(dataResult.getMsg());
        }
        return dataResult.getData();
    }

    public List<SysUser> getUsers(SysUser sysUser) {
        //远程调用system接口获取所有电站信息
        R<List<SysUser>> dataResult = remoteSystemService.getUsers(beanToMap(sysUser), SecurityConstants.INNER);
        return resultToList(dataResult);
    }

    public List<SysRole> getRoles(SysRole sysRole) {
        //远程调用system接口获取所有电站信息
        R<List<SysRole>> dataResult = remoteSystemService.getRoles(beanToMap(sysRole), SecurityConstants.INNER);
        return resultToList(dataResult);
    }

    private Map<String, Object> beanToMap(Object obj) {
        try {
            Map<String, Object> paraMap = BeanUtils.beanToMap(obj);
            if (obj instanceof BaseEntity) {
                paraMap.remove("params");
            }
            return paraMap;
        }catch (Exception e){
            throw new ServiceException(e.getMessage());
        }
    }

    public SysUser getUserById(Long userId) {
        //远程调用system接口获取所有电站信息
        R<SysUser> dataResult = remoteSystemService.getUserById(userId, SecurityConstants.INNER);
        return resultToBean(dataResult);
    }

    public SysRole getRoleById(Long roleId) {
        //远程调用system接口获取所有电站信息
        R<SysRole> dataResult = remoteSystemService.getRoleById(roleId, SecurityConstants.INNER);
        return resultToBean(dataResult);
    }

}
