package cn.iocoder.yudao.server.service;

import cn.iocoder.yudao.module.system.oa.E9ApiTokenUtil;
import cn.iocoder.yudao.module.system.oa.SslSkippingRestTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class PortalOaFlow {
    @Value("${oa.appid}")
    private String appid;
    @Value("${oa.cpk}")
    private String cpk;
    @Value("${oa.register}")
    private String registerUrl;
    @Value("${oa.gettoken}")
    private String tokenUrl;
    @Value("${oa.companyUrl}")
    private String companyUrl;
    @Value("${oa.departmentUrl}")
    private String departmentUrl;
    @Value("${oa.userUrl}")
    private String userUrl;
    @Value("${oa.workflowId}")
    private String workflowId;
    @Value("${oa.requestName}")
    private String requestName;
    @Value("${oa.outMaintain}")
    private String outMaintainUrl;

    private static String spk = "";
    private static String secret = "";



    public void register() throws Exception{
        HttpHeaders headers = new HttpHeaders();
        headers.add("appid", appid);
        headers.add("cpk", cpk);

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(headers);
        RestTemplate restTemplate = SslSkippingRestTemplate.createRestTemplate();

        String result = restTemplate.postForObject(registerUrl, requestEntity, String.class);
        JSONObject jsonObject = JSON.parseObject(result);
        spk = String.valueOf(jsonObject.get("spk"));
        secret = String.valueOf(jsonObject.get("secret"));
        System.out.println("result register:" + result);

    }

    public String getToken() throws Exception{
//        if (StringUtils.isBlank(spk) || StringUtils.isBlank(secret)) {
            register();
//        }
        String secretEn = E9ApiTokenUtil.encryptString(spk, secret);
        HttpHeaders headers = new HttpHeaders();
        headers.add("appid", appid);
        headers.add("secret", secretEn);

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(headers);
        RestTemplate restTemplate = SslSkippingRestTemplate.createRestTemplate();

        String result = restTemplate.postForObject(tokenUrl, requestEntity, String.class);
        JSONObject jsonObject = JSON.parseObject(result);
        String token = String.valueOf(jsonObject.get("token"));
        System.out.println("result token:" + result);
        return token;
    }

    @Autowired
    private RestTemplate restTemplate;

    // ==================== 新增：每次使用【全新的、无Cookie】的RestTemplate ====================
    private RestTemplate getNewRestTemplateWithoutCookie() {
        return new RestTemplate(new HttpComponentsClientHttpRequestFactory(
                HttpClients.custom()
                        .disableCookieManagement() // 彻底禁用Cookie，不保存、不携带
                        .setRedirectStrategy(new LaxRedirectStrategy())
                        .build()
        ));
    }

    public ImmutableMap<String, Object> getOaTodo(String oaId) throws Exception {
        String token = getToken();

        HttpHeaders headersOut = new HttpHeaders();
        headersOut.add("token", token);
        headersOut.add("appid", appid);
        String person = E9ApiTokenUtil.encryptString(spk, oaId);
        headersOut.add("userid", person);
        headersOut.setContentType(MediaType.APPLICATION_JSON);
        headersOut.remove(HttpHeaders.COOKIE); // 保险清空

        Map<String, Object> params = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("root", ImmutableMap.of("createrid", oaId));
        params.put("conditions", map);
        params.put("pageSize", 20);
        params.put("pageNo", 1);

        HttpEntity<Map<String, Object>> requestEntityOut = new HttpEntity<>(params, headersOut);

        // ==================== 关键：每次都用全新无Cookie的RestTemplate ====================
        RestTemplate noCookieRestTemplate = getNewRestTemplateWithoutCookie();

        // 待办数量
        String out = noCookieRestTemplate.postForObject(
                "https://yfoa.keruioil.com/api/workflow/paService/getDoingWorkflowRequestCount",
                requestEntityOut, String.class
        );

        // 待办明细
        map.put("root", ImmutableMap.of("craterid", oaId));
        params.put("conditions", map);
        HttpEntity<Map<String, Object>> requestEntityOut1 = new HttpEntity<>(params, headersOut);

        String todoList = noCookieRestTemplate.postForObject(
                "https://yfoa.keruioil.com/api/workflow/paService/getDoingWorkflowRequestList",
                requestEntityOut1, String.class
        );

        List<JSONObject> jsonObjects = JSON.parseArray(todoList, JSONObject.class);
        return ImmutableMap.of("todoCount", out, "todoList", jsonObjects);
    }

}
