package cn.cslg.pas.service;

import cn.cslg.pas.common.model.dto.ClientDTO;
import cn.cslg.pas.common.model.vo.UserVO;
import cn.cslg.pas.common.utils.ApiUtils;
import cn.cslg.pas.common.utils.SecurityUtils.LoginUtils;
import cn.cslg.pas.domain.Project;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import lombok.RequiredArgsConstructor;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 李仁杰
 * @description 调用外部接口的Service类
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class RequestService {
    @Value("${authorUrl}")
    private String url;
    private final ApiUtils apiUtils;
    public static final MediaType JSON1 = MediaType.parse("application/json; charset=utf-8");
    private final ProjectService projectService;

    //从权限系统查询专题库负责人信息
    public String getDepartmentFromPCS(List<Project> dataList) throws IOException {
        //获取专题库负责人对应信息
        Map<String, Object> map1 = new HashMap<>();
        map1.put("departmentId", dataList.stream().map(Project::getDepartmentId).filter(Objects::nonNull).collect(Collectors.toList()));
        return apiUtils.invokeApi(new JSONObject(map1), "/permission/api/system/getDepartmentById", "post", "data");
    }

    //从权限系统获取专题库负责人对应信息
    public String getPersonnelFromPCS(List<Integer> personnelIds) throws IOException {
        Map<String, Object> map1 = new HashMap<>();
        map1.put("personnelId", personnelIds);
        return apiUtils.invokeApi(new JSONObject(map1), "/permission/api/system/getPersonnelById", "post", "data");
    }

    //从权限系统获取验证码
    public String getVerifyCodeFromPCS() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url + "/permission/api/admin/verifyCode")
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    //从权限系统登录
    public String LoginFromPCS(String username, String password, String code, String uuid) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("uuid", uuid);
        map.put("username", username);
        map.put("password", password);
        JSONObject json = new JSONObject(map);
        RequestBody a = RequestBody.create(JSON1, String.valueOf(json));
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url + "/permission/api/admin/login")
                .post(a)
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    //从权限系统获得租户信息
    public String getTenantMessageFromPCS(UserVO params) throws IOException {
        //查询数据规则
        //设定formData类型参数
        Project project = projectService.getProjectById(params.getProjectId());
        int tentId = project.getTenantId();
        String name = "";
        name = params.getName() == null ? name : params.getName();
        RequestBody requestBody = new FormBody.Builder()
                .add("tenantId", tentId + "")
                .add("tenantName", name)
                .add("current", params.getCurrent().toString())
                .add("size", params.getSize().toString())
                .build();
        //建立连接
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url + "/permission/api/system/getTenantMessage")
                .post(requestBody)
                .addHeader("Cookie", LoginUtils.getToken())
                .build();
        //获得请求返回
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    //从权限系统获得人员信息
    public String getPersonnelMessageFromPCS(UserVO params) throws IOException {
        //查询数据规则
        //设定formData类型参数
        String name = "";
        name = params.getName() == null ? name : params.getName();
        RequestBody requestBody = new FormBody.Builder()
                .add("tenantId", params.getTenantId() + "")
                .add("personnelName", name)
                .add("current", params.getCurrent().toString())
                .add("size", params.getSize().toString())
                .build();
        //建立连接
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url + "/permission/api/system/getPersonnelMessage")
                .post(requestBody)
                .addHeader("Cookie", LoginUtils.getToken())
                .build();
        //获得请求返回
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    /**
     * @title 获得专题库成员列表
     * @description 获得专题库成员列表
     * @autor lrj
     */

    public String getClientByIds(List<Integer> ids) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        String param = new Gson().toJson(ids);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
        Request request = new Request.Builder()
                .url(url + "/permission/api/client/getByIds")
                .addHeader("Cookie", LoginUtils.getToken())
                .post(requestBody)
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    public String getClientByName(String name) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url + "/permission/api/client/getByName?name="+name)
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }
    /**
     * @title 获得专题库成员列表
     * @description 获得专题库成员列表
     * @autor lrj
     */

    public String addClient(ClientDTO client) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        String param = new Gson().toJson(client);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
        Request request = new Request.Builder()
                .url(url + "/permission/api/client/add")
                .addHeader("Cookie", LoginUtils.getToken())
                .post(requestBody)
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    public String getPersonIdByNamePCS(String personName) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url + "/permission/api/system/getPersonIdByName?personName=" + personName)
                .get()
                .build();

        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }
}
