package cn.quantgroup.customer.service.impl;

import cn.quantgroup.customer.entity.OpUser;
import cn.quantgroup.customer.enums.ErrorCodeEnum;
import cn.quantgroup.customer.exception.BusinessException;
import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.service.IOpSystemService;
import cn.quantgroup.customer.service.http.IHttpService;
import cn.quantgroup.customer.util.JSONTools;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author yangjun
 * @Date 2020/4/16 10:05
 * @Desc
 * @Update
 */

@Slf4j
@Service("opSystemService")
public class OpSystemServiceImpl implements IOpSystemService {

    @Value("${opapi.http}")
    private String kaSysUrl;

    @Autowired
    private IHttpService httpService;

    @Override
    public JsonResult<OpUser> findUserByToken(String token, String system) {
        String logPre = "OpSystemServiceImpl.findUserByToken";
        log.info("{} 通过token查询用户登录信息 token={}，system={}", logPre, token, system);

        String url = kaSysUrl + "/user/info";
        try {
            Map<String, String> param = Maps.newHashMap();
            param.put("x-auth-token", token);
            // 增加请求类型 api
            param.put("request-type","api");
            if(StringUtils.isNotBlank(system)){
                param.put("x-auth-system", system);
            }

            String result;
            try {
                result = httpService.post(url, param, null);
            } catch (Exception e) {
                log.error(" {}查询用户登录信息失败http请求异常 url={},param={}", logPre, url, param, e);
                return JsonResult.buildErrorStateResult("通讯异常", null);
            }
            log.info("{} 系统返回值:{}", logPre, result);

            if (StringUtils.isBlank(result)) {
                log.error("{} 查询用户登录信息失败 jsonResult={}", logPre, result);
                return JsonResult.buildErrorStateResult("查询数据异常", null);
            }
            TypeReference<JsonResult<OpUser>> typeToken = new TypeReference<JsonResult<OpUser>>() {
            };
            JsonResult<OpUser> jsonResult = JSONTools.deserialize(result, typeToken);
            return jsonResult;
        } catch (Exception e) {
            log.error("{} 网络通讯异常,token:{},system:{},ex:{}", logPre, token, system, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }
}
