package com.hzya.frame.seeyon.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.seeyon.entity.CollAttachmentResDTO;
import com.hzya.frame.sysnew.application.api.entity.SysApplicationApiEntity;
import com.hzya.frame.sysnew.application.api.service.ISysApplicationApiService;
import com.hzya.frame.web.exception.BaseSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * @Description 致远rest接口工具类
 * @Author xiangerlin
 * @Date 2024/6/17 15:49
 **/
@Component
public  class OARestUtil {
    @Autowired
    private static ISysApplicationApiService sysApplicationApiService;
    static Logger logger = LoggerFactory.getLogger(OARestUtil.class);

    private OARestUtil() {
    }


    /**
     * 附件上传
     * @param file 附件对象
     * @param api_code 接口编码
     * @return
     */
    public static JSONObject fileUpload(File file,String api_code_upload,String api_code_token) {
        if (StrUtil.isNotEmpty(api_code_upload)){
            //1、查询附件上传api接口信息
            SysApplicationApiEntity sysApp = getByCode(api_code_upload);
            if (null != sysApp){
                String app_url = sysApp.getAppUrl();
                String url = app_url+"/seeyon/rest/attachment?token=@token@";
                String token = getToken(null,api_code_token);
                url = url.replaceAll("@token@",token);
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put("file", file);
                String result = HttpUtil.post(url, paramMap);
                if (StrUtil.isNotBlank(result)) {
                    logger.info("附件上传结果"+result);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    String atts = jsonObject.get("atts").toString();
                    if (StrUtil.isNotEmpty(atts)) {
                        JSONArray jsonArray = JSONArray.parseArray(atts);
                        JSONObject res = (JSONObject) jsonArray.get(0);
                        return res;
                    }
                }
            }
        }else {
            throw new BaseSystemException("api_code不能为空");
        }
        return null;
    }

    /***
     * 查询协同附件列表
     * @param summaryId col_summary表id
     * @param attType 0代表附件,2代表关联文档,“0,2”代表附件和关联文档
     * @param apiCode 接口编码
     * @return
     */
    public List<CollAttachmentResDTO> getColAttachments(String summaryId,String attType,String apiCode,String loginName){
        if (StrUtil.isNotEmpty(summaryId) && StrUtil.isNotEmpty(apiCode)){
            SysApplicationApiEntity sysApp = getByCode(apiCode);
            String token = getToken(loginName,sysApp);
            String appUrl = StrUtil.removeSuffix(sysApp.getAppUrl(),"/");
            if (StrUtil.isEmpty(attType)){
                attType = "0";
            }
            String url = "/seeyon/rest/coll/attachments/@SummaryID@/@attType@";
            url = url.replaceAll("@SummaryID@",summaryId).replaceAll("@attType@",attType);
            String body = HttpRequest.get(appUrl + url).header("token", token).execute().body();
            if (StrUtil.isNotEmpty(body) && JSONUtil.isTypeJSON(body)){
                List<CollAttachmentResDTO> list = JSON.parseArray(body,CollAttachmentResDTO.class);
                return list;
            }
        }
        return null;
    }

    /**
     * 附件下载
     * @param loginName oa登录名
     * @param apiCode 接口编码
     * @param fileId 附件id
     * @param fileName 附件名
     * @return 附件字节数组
     */
    public byte[] downloadFileBytes(String loginName,String apiCode,String fileId,String fileName){
        if (StrUtil.isNotEmpty(apiCode)){
            SysApplicationApiEntity sysApp = getByCode(apiCode);
            String token = getToken(loginName,sysApp);
            String appUrl = StrUtil.removeSuffix(sysApp.getAppUrl(),"/");
            String url = "/seeyon/rest/attachment/file/@ctp_file_ID@?fileName=@文件名@&token=@token@";
            url = url.replaceAll("@ctp_file_ID@",fileId).replaceAll("@文件名@",fileName).replaceAll("@token@",token);
            byte[] bytes = HttpUtil.downloadBytes(appUrl + url);
            return bytes;
        }
        return null;
    }


    /**
     * 附件下载
     * @param loginName oa登录名
     * @param apiCode 接口编码
     * @param fileId 附件id
     * @param fileName 附件名
     * @param token
     * @return 附件字节数组
     */
    public byte[] downloadFileBytes(String loginName,String apiCode,String fileId,String fileName,String token){
        if (StrUtil.isNotEmpty(apiCode)){
            SysApplicationApiEntity sysApp = getByCode(apiCode);
            if (StrUtil.isEmpty(token)){
                token = getToken(loginName,sysApp);
            }
            String appUrl = StrUtil.removeSuffix(sysApp.getAppUrl(),"/");
            String url = "/seeyon/rest/attachment/file/@ctp_file_ID@?fileName=@文件名@&token=@token@";
            url = url.replaceAll("@ctp_file_ID@",fileId).replaceAll("@文件名@",fileName).replaceAll("@token@",token);
            byte[] bytes = HttpUtil.downloadBytes(appUrl + url);
            return bytes;
        }
        return null;
    }
    /**
     * 获取token
     * @param login_name
     * @param api_code
     * @return
     */
    public static String getToken(String login_name,String api_code){
        if (StrUtil.isNotEmpty(api_code)){
            SysApplicationApiEntity sysApp = getByCode(api_code);
            return getToken(login_name,sysApp);
        }else {
            throw new BaseSystemException("api_code不能为空");
        }
    }

    /**
     * 获取token
     * @param login_name oa登录名
     * @param sysApp 应用信息
     * @return
     */
    public static String getToken(String login_name,SysApplicationApiEntity sysApp){
        if (null != sysApp){
            HashMap<String, String> hashMap = new HashMap<>();
            String app_url = StrUtil.removeSuffix(sysApp.getAppUrl(), "/");
            String url = app_url+"/seeyon/rest/token";
            String headerIn = sysApp.getHeaderIn();
            JSONArray headers = JSON.parseArray(headerIn);
            for (int i = 0; i < headers.size(); i++) {
                JSONObject object1 = headers.getJSONObject(i);
                String parameterName = object1.getString("parameterName");
                if ("userName".equals(parameterName) || "password".equals(parameterName) || "loginName".equals(parameterName)){
                    String example = object1.getString("example");
                    hashMap.put(parameterName,example);
                }
            }
            login_name = hashMap.get("loginName");
            if (StrUtil.isEmpty(login_name)){
                hashMap.put("loginName","hzya");
            }
            String result = HttpRequest.post(url).body(JSON.toJSONString(hashMap)).execute().body();
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (null != jsonObject) {
                logger.info("======token：{}======" ,jsonObject.getString("id"));
                return jsonObject.getString("id");
            }
        }
        return null;
    }
    private static SysApplicationApiEntity getByCode(String api_code){
        if (StrUtil.isNotEmpty(api_code)){
            SysApplicationApiEntity sysApp = new SysApplicationApiEntity();
            sysApp.setApiCode(Long.valueOf(api_code));
            sysApp = sysApplicationApiService.queryOne(sysApp);
            if (null != sysApp && StrUtil.isNotEmpty(sysApp.getId())){
                sysApp = sysApplicationApiService.get(sysApp.getId());
                if (null != sysApp){
                    return sysApp;
                }
            }
        }else {
            throw new BaseSystemException("api_code不能为空");
        }
        return null;
    }
}
