package cn.cslg.report.service;

import cn.cslg.report.common.core.base.Constants;
import cn.cslg.report.common.model.vo.LoginVO;
import cn.cslg.report.common.model.vo.PatentVO;
import cn.cslg.report.common.model.vo.PersonnelVO;
import cn.cslg.report.common.model.vo.TaskParams;
import cn.cslg.report.common.utils.CacheUtils;
import cn.cslg.report.common.utils.JsonUtils;
import cn.cslg.report.common.utils.SecurityUtils.LoginUtils;
import cn.cslg.report.entity.ImportTask;
import cn.cslg.report.entity.Report;
import cn.cslg.report.service.business.ImportTaskService;
import cn.cslg.report.service.business.ReportService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 沈永艺
 * @description 调用外部接口的Service类 PCS:权限系统 PAS:专利分析系统
 * @date 2022-10-31
 */
@SuppressWarnings({"all"})
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class OutInterfaceService {
    @Value("${PCSUrl}")
    private String PCSUrl;
    @Value("${PASUrl}")
    private String PASUrl;
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private final CacheUtils cacheUtils;
    private final LoginUtils loginUtils;
    private final ReportService reportService;
    private final ImportTaskService importTaskService;

    /**
     * @title 获取验证码
     * @description 接口来源:PCS
     */
    public String getVerifyCodeFromPCS() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PCSUrl + "/permission/api/admin/verifyCode")
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    /**
     * @title 登录接口
     * @description 接口来源:PCS
     */
    public String loginFromPCS(LoginVO loginVO) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("code", loginVO.getCode());
        map.put("uuid", loginVO.getUuid());
        map.put("username", loginVO.getUsername());
        map.put("password", loginVO.getPassword());
        JSONObject json = new JSONObject(map);
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PCSUrl + "/permission/api/admin/login")
                .post(requestBody)
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    /**
     * @title 登录人信息
     * @description 接口来源:PCS
     */
    public String userInfoFromPCS() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PCSUrl + "/permission/api/system/userinfo")
                .get()
                .addHeader("Cookie", LoginUtils.getToken())
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    /**
     * @title 获取字典项
     * @description 接口来源:PCS PAS
     */
    public Map<String, Object> dictMessageFromPCS() throws IOException {
        //从PCS取字典项
        OkHttpClient okHttpClient1 = new OkHttpClient();
        Request request1 = new Request.Builder()
                .url(PCSUrl + "/permission/api/system/getDict")
                .get()
                .build();
        String pcsDictMessage = Objects.requireNonNull(okHttpClient1.newCall(request1).execute().body()).string();
        //从PAS取字典项
        OkHttpClient okHttpClient2 = new OkHttpClient();
        Request request2 = new Request.Builder()
                .url(PASUrl + "/api/v2/common/getDictMessage")
                .get()
                .build();
        String pasDictMessage = Objects.requireNonNull(okHttpClient2.newCall(request2).execute().body()).string();

        JSONObject jsonObject1 = JSONObject.parseObject(pcsDictMessage);
        JSONObject jsonObject2 = JSONObject.parseObject(pasDictMessage);
        Map<String, Object> map = new HashMap<>();
        map.putAll(JsonUtils.jsonToMap(String.valueOf(jsonObject1.get("data"))));
        map.putAll(JsonUtils.jsonToMap(String.valueOf(jsonObject2.get("data"))));
        return map;
    }

    /**
     * @title 获取权限列表
     * @description 接口来源:PCS
     */
    public String getPermissionListFromPCS(String code) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PCSUrl + "/permission/api/system/getPermissionList?code=" + code)
                .addHeader("Cookie", LoginUtils.getToken())
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    /**
     * @title 获取所有部门(无权限控制)
     * @description 接口来源:PCS
     */
    public String getAllDepartmentFromPCS() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PCSUrl + "/permission/api/system/getAllDepartment")
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    /**
     * @title 获取部分部门(有权限控制)
     * @description 接口来源:PCS
     */
    // TODO: 2022/11/2 未开发
    public String getPartDepartmentFromPCS() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PCSUrl + "/permission/api/system/getPartDepartment")
                .addHeader("Cookie", LoginUtils.getToken())
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    /**
     * @title 获取所有人员(无权限控制)
     * @description 接口来源:PCS
     */
    public String getPartPersonnelID(Integer ID) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PCSUrl + "/permission/api/personnel/getPerson?id=" + ID)
                .addHeader("Cookie", LoginUtils.getToken())
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    public String getAllPersonnelFromPCS() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PCSUrl + "/permission/api/system/getAllPersonnel")
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    /**
     * @title 分页查询人员
     * @description 接口来源:PCS
     */
    public String getPartPersonnelFromPCS(PersonnelVO personnelVO) throws IOException {
        Map<String, Object> map = new HashMap<>();
        if (personnelVO.getName() == null) {
            personnelVO.setName("");
        }
        map.put("name", personnelVO.getName());
        map.put("tenant", personnelVO.getTenant());
        map.put("size", personnelVO.getSize());
        map.put("current", personnelVO.getCurrent());
        map.put("notInPersonIds",personnelVO.getNotInPersonIds());
        JSONObject json = new JSONObject(map);
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PCSUrl + "/permission/api/system/queryPageList")
                .addHeader("Cookie", LoginUtils.getToken())
                .post(requestBody)
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }


    /**
     * @title 根据ID查询人员
     * @description 接口来源:PCS
     */
    public String getPersonnelByIdsFromPCS(List<Integer> ids) throws IOException {

        String param = new Gson().toJson(ids);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PCSUrl + "/permission/api/system/getPersonnelByIds")
                .addHeader("Cookie", LoginUtils.getToken())
                .post(requestBody)
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    /**
     * @title 获取所有客户(无权限控制)
     * @description 接口来源:PCS
     */
    public String getAllClientFromPCS() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PASUrl + "/api/v2/client/getAllClient?id=" + cacheUtils.getLoginUser(loginUtils.getId()).getTenantId())
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    /**
     * @title 获取部分客户(有权限控制)
     * @description 接口来源:PCS
     */
    // TODO: 2022/11/2 未开发
    public String getPartClientFromPCS() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PASUrl + "/api/v2/client/getPartClient")
                .addHeader("Cookie", LoginUtils.getToken())
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    /**
     * @title 根据专利号获得专利信息
     * @description 接口来源:PCS
     */
    public String getPatentFromPAS(String patentNo) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PASUrl + "/api/v2/patent/patentNo?patentNo=" + patentNo)
//                .addHeader("Cookie", LoginUtils.getToken())
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    /**
     * @title 根据专利号获得专利信息
     * @description 接口来源:PCS
     */
    public String getPatentRightFromPAS(String patentNo) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PASUrl + "/api/v2/patent/right?patentNo=" + patentNo)
//                .addHeader("Cookie", LoginUtils.getToken())
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    public String getClientNameFromPAS(Integer id) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PASUrl + "/api/v2/client/getClientName?id=" + id)
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    public String getPersonNameAndDepart(Integer personId, Integer departId) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PCSUrl + "/permission/api/system/getPersonNameAndDepart?personId=" + personId + "&departId=" + departId)
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    public String getPatentNos(Integer projectId) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PASUrl + "/api/v2/patent/getPatentNos?projectId=" + projectId)
                .get()
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    public String getDictsFromPAS() throws IOException {
        List<String> dicts = new ArrayList<>();
        dicts.add(Constants.ENTERPRISE_APPLICATION_SCENARIO);
        String param = new Gson().toJson(dicts);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PASUrl + "/api/v2/system/dict")
                .post(requestBody)
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    public String getPatentFromPAS(PatentVO patentVO, int type) throws IOException {
        LambdaQueryWrapper<ImportTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImportTask::getReportId, patentVO.getReportId());
        List<ImportTask> importTasks = importTaskService.list(queryWrapper);
        List<Integer> taskIds = importTasks.stream().map(ImportTask::getId).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        Report report = reportService.getById(patentVO.getReportId());
        if (type == 0) {
            map.put("projectId", report.getProjectId());
            map.put("importTaskId", taskIds);
            map.put("startNumber", patentVO.getStartNumber());
            map.put("endNumber", patentVO.getEndNumber());
        }
        map.put("size", patentVO.getSize());
        map.put("current", patentVO.getCurrent());
        map.put("patentNos", patentVO.getPatentNos());
        map.put("notInPatentNos", patentVO.getNotInPatentNos());
        JSONObject json = new JSONObject(map);
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PASUrl + "/api/v2/system/patentList")
                .post(requestBody)
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }
    //根据专利号列表获得专利详情
  public String  getPatentDTOListForRMS(PatentVO patentVO) throws  IOException{
      Map<String, Object> map = new HashMap<>();
      map.put("patentNos", patentVO.getPatentNos());
      JSONObject json = new JSONObject(map);
      RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
      OkHttpClient okHttpClient = new OkHttpClient();
      Request request = new Request.Builder()
              .url(PASUrl + "/api/v2/system/getPatentDTOListForRMS")
              .post(requestBody)
              .build();
      return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();


  }

    public String getComPatentNos(PatentVO patentVO) throws IOException {
        LambdaQueryWrapper<ImportTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImportTask::getReportId, patentVO.getReportId());
        Map<String, Object> map = new HashMap<>();
        Report report = reportService.getById(patentVO.getReportId());
        map.put("projectId", report.getProjectId());
        List<ImportTask> importTasks = importTaskService.list(queryWrapper);
        List<Integer> taskIds = importTasks.stream().map(ImportTask::getId).collect(Collectors.toList());
        map.put("importTaskId", taskIds);

        map.put("startNumber", patentVO.getStartNumber());
        map.put("endNumber", patentVO.getEndNumber());
        map.put("patentNos", patentVO.getPatentNos());
        JSONObject json = new JSONObject(map);
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(PASUrl + "/api/v2/system/getComPantentNos")
                .post(requestBody)
                .build();
        return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
    }

    public String importPatents(TaskParams taskParams) throws IOException {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .pingInterval(400, TimeUnit.SECONDS) // 设置 PING 帧发送间隔
                .connectTimeout(30, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(30, TimeUnit.SECONDS)//设置读取超时时间
                .build();
            String param = new Gson().toJson(taskParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
        Request request = new Request.Builder()
                .url(PASUrl + "/api/v2/project/import/sysPatent")
                .post(requestBody)
                .build();
        return Objects.requireNonNull(httpClient.newCall(request).execute().body()).string();
    }
}
