package com.tofly.watermeter.util.service.impl;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.net.multipart.MultipartFormData;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.watermeter.config.ApiCallsBean;
import com.tofly.watermeter.em.ApiCallEnum;
import com.tofly.watermeter.util.service.CallAPIService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author bubble
 */
@Slf4j
@Service
@AllArgsConstructor
public class CallAPIServiceImpl implements CallAPIService {

    private final ApiCallsBean apiCallsBean;
    /**
     * 获取授权信息
     *
     * @return string
     */
    @Override
    public String getAuthorization() {
        Map<String, Object> body = new HashMap<>(3);
        body.put("username", apiCallsBean.getUsername());
        body.put("password", apiCallsBean.getPassword());
        body.put("uuid", apiCallsBean.getUuid());

        String login = "/api/v1/rabbit/local/login/auth";
        String url = apiCallsBean.getIp() + login;
        String execute = null;
        String authorization = null;
        try {
            execute =
                    HttpRequest.post(url)
                            .timeout(10000)
                            .body(JSONObject.toJSONString(body))
                            .execute()
                            .body();
        } catch (IORuntimeException exception) {
            log.info("请求登录接口失败：" + exception.getMessage());
        }

        if (execute != null) {
            Map result = JSONObject.parseObject(execute, Map.class);
            if (CollectionUtils.isNotEmpty(result)) {
                Object statusCode = String.valueOf(result.get("statusCode"));
                if (ApiCallEnum.STATUS_CODE_OK.getCode().equals(statusCode)) {
                    authorization = "Bearer " + result.get("data");
                }
            }
        } else {
            log.info("请求登录接口失败：获取信息为空");
        }
        return authorization;
    }

    /**
     * 获取接口返回结果
     *
     * @param body 条件查询
     * @param url  url
     * @return map
     */
    @Override
    public Map getApiResult(Object body, String url) {
        String authorization = getAuthorization();
        if (StringUtils.isBlank(authorization)) {
            throw new ToflyDeniedException("获取授权信息为空，请检查网络或营销接口是否正常");
        }
        url = apiCallsBean.getIp() + url;
        try {
            String execute =
                    HttpRequest.post(url)
                            .header("Authorization", authorization)
                            .body(JSONObject.toJSONString(body))
                            .execute()
                            .body();
            if (execute != null) {
                Map map = JSONObject.parseObject(execute, Map.class);
                if (CollectionUtils.isNotEmpty(map)) {
                    Object statusCode = String.valueOf(map.get("statusCode"));
                    if (!ApiCallEnum.STATUS_CODE_OK.getCode().equals(statusCode)) {
                        log.info("获取接口返回结果失败:" + map.get("message"));
                    }
                }
                return map;
            }
        } catch (IORuntimeException exception) {
            log.info("请求登录接口失败：" + exception.getMessage());
        }
        return null;
    }

    /**
     * 文件上传
     *
     * @param formData form
     * @param url      url
     * @return map
     */
    @Override
    public Map<String,Object> uploadFile(Map<String, Object> formData, MultipartFile file, String url) {
        String authorization = getAuthorization();

        if (file == null){
            throw new ToflyDeniedException("未选择上传文件");
        }

        byte[] bytes = new byte[0];
        try {
            bytes = IoUtil.readBytes(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        url = apiCallsBean.getIp() + url;
        try {
            String execute =
                    HttpRequest.post(url)
                            .header("Authorization", authorization)
                            .contentType("multipart/form-data")
                            .form(formData)
                            .form("file",bytes,file.getOriginalFilename())
                            .execute()
                            .body();
            if (execute != null) {
                Map map = JSONObject.parseObject(execute, Map.class);
                if (CollectionUtils.isNotEmpty(map)) {
                    String statusCode = String.valueOf(map.get("statusCode"));
                    if (!ApiCallEnum.STATUS_CODE_OK.getCode().equals(statusCode)) {
                        log.info("获取接口返回结果失败:" + map.get("message"));
                    }
                }
                return map;
            }
        } catch (IORuntimeException exception) {
            log.info("请求登录接口失败：" + exception.getMessage());
        }
        return null;
    }
}
