package easydo.technology.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.sql.Connection;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import easydo.technology.components.JdbcClient;
import easydo.technology.exception.BizException;
import easydo.technology.model.GldProject;
import easydo.technology.model.ProjectInfo;
import easydo.technology.service.GLDMasterService;
import easydo.technology.system.domain.SysDept;
import easydo.technology.util.HttpClientUtil;
import easydo.technology.utils.LocalDateUtil;
import easydo.technology.utils.RedisUtils;
import easydo.technology.utils.StringUtil;

@RestController
@RequestMapping("/test")
public class TestController {
    @Resource
    DataSource dataSource;
    @Resource
    JdbcClient jdbcClient;
    @Resource
    GLDMasterService gldMasterService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    RedisUtils redisUtils;

    /*
     * public static void main(String[] args) {
     * String url = "http://218.201.101.181:14780/tenant/v2/tenants?size=20000";
     * String auth =
     * "Basic YlFvc0tIeWJkSlZUZGtMcXA0U1VIMlE0ejNZQjc5eVA6b1ZmaU5zR1c1NVZzSW5ITTlDOVI3c2g0SHlpVGMxY2w="
     * ;
     * String token = "cn-b3c73fac-2629-4337-94fb-e79c289d1979";
     * String tenantId = "5600001";
     * 
     * JSONObject object = HttpClientUtil.sendGLDGET_getTenantId(url, token);
     * System.out.println(object.toJSONString());
     * //{"access_token":"cn-b3c73fac-2629-4337-94fb-e79c289d1979","scope":
     * "paas-clouddoc,paas-gdoc_tenant,paas-new-storage-service_admin,paas-organization_admin,paas-gws_tenant,paas-organization_tenant,paas-comment-service_tenant,paas-databag_tenant,paas-new-storage-service_tenant,paas-databag_admin,paas_databag_tenant,paas-raw-storage-service_tenant"
     * ,"token_type":"bearer","exp":1723342092,"expires_in":74670}
     * }
     */

    // public static void main(String[] args) {
    // String url =
    // "http://218.201.101.181:14780/flow-app-local/v4/flow-definitions/query-for-start?formId=flow/STD_Dcm_PROCUREMENT_SYSTEM&mgtGroupId=11200297";
    // Map<String, String> header = new HashMap<>();
    // header.put("Authorization",
    // "Basic
    // YlFvc0tIeWJkSlZUZGtMcXA0U1VIMlE0ejNZQjc5eVA6b1ZmaU5zR1c1NVZzSW5ITTlDOVI3c2g0SHlpVGMxY2w=");
    // header.put("x-tenant-id", "5600003");

    // JSONArray resObject = HttpClientUtil.sendGETWithHeader_Arr(url, header);
    // System.out.println(resObject.toJSONString());
    // }

    /*
     * public static void main(String[] args) {
     * // String url =
     * "http://218.201.101.181:8180/seeyon/thirdpartyController.do?ticket=-5127817351537210703";
     * // String username = HttpClientUtil.sendOaGET_USERNAME(url);
     * // System.out.println(username);
     * 
     * String url = "http://218.201.101.181:8180/seeyon/rest/token";
     * JSONObject object = new JSONObject();
     * object.put("userName", "zcxt");
     * object.put("password", "2679fc6b-df18-4563-9b8e-773b59bdcb62");
     * JSONObject resObject = HttpClientUtil.sendPOST(url, object.toJSONString());
     * String accessToken = resObject.getString("id");
     * System.out.println(accessToken);
     * 
     * String getUserInfoUrl =
     * "http://218.201.101.181:8180/seeyon/rest/orgMember?loginName=guanglianda";
     * Map<String, String> header = new HashMap<>();
     * header.put("token", accessToken);
     * // header.put("Authorization", "Bearer " + accessToken);
     * JSONObject resObj = HttpClientUtil.sendGETWithHeader_Obj(getUserInfoUrl,
     * header);
     * System.out.println(resObj);
     * }
     */

    @RequestMapping(value = "/getPage")
    public Object getPage() throws Exception {
        redisUtils.set("test", "123456", 600);
        System.out.println(redisUtils.get("test"));
        return "success";
    }

    @GetMapping(value = "/test")
    public void test(HttpServletResponse response, HttpServletRequest request, @RequestParam String objectId,
            @RequestParam(required = false) String fileName) throws Exception {
        String url = "http://jsf-int.glodon.com/cost-management/openapi/attachments/" + objectId;
        Map<String, String> header = new HashMap<>();
        header.put("Authorization",
                "Basic a0ZkMkE4UkhSM1l1ZlplQ1lVUGNjVWFMblJWQW5ZZ1c6VTJNakoycVZiaGNVYlI5VlVyUUdYeVFQekp1WkdoNm4=");
        header.put("X-CORAL-TENANT", "865509948108800");
        if (StringUtil.isEmpty(fileName)) {
            fileName = "contract.pdf";
        }
        HttpClientUtil.sendGETWithHeader_OutputStream(url, header, request, response, fileName);

    }

    // public static void main(String[] args) {
    // String creationDate = LocalDateUtil.localDateTimeFormat(LocalDateTime.now(),
    // "yyyy-MM-dd HH:mm");
    // String creationDate2 = LocalDateUtil.localDateTimeFormat(LocalDateTime.now(),
    // "yyyy-MM-dd HH:mm:ss");

    // String url = "http://218.201.101.181:8180" + "/seeyon/rest/token";
    // JSONObject object = new JSONObject();
    // object.put("userName", "zcxt");
    // object.put("password", "2679fc6b-df18-4563-9b8e-773b59bdcb62");
    // JSONObject resObject = HttpClientUtil.sendPOST(url, object.toJSONString());
    // System.out.println("查询OAtoken的res======>" + resObject.toJSONString());
    // String token = resObject.getString("id");

    // Map<String, String> header = new HashMap<>();
    // header.put("token", token);

    // String sendTodoUrl = "http://218.201.101.181:8180" +
    // "/seeyon/rest/thirdpartyPending/receive?token=" + token;
    // object = new JSONObject();
    // object.put("registerCode", "3007");
    // object.put("taskId", "4e12f28b-8e15-4f82-afbf-59dd0b083394");
    // object.put("title", "供应商评价");
    // object.put("senderName", "guanglianda");
    // object.put("classify", "招采系统");
    // object.put("contentType", "招采系统");
    // object.put("state", 0);
    // object.put("thirdSenderId", "");
    // object.put("thirdReceiverId", "");
    // object.put("creationDate", creationDate);
    // object.put("content", "");
    // object.put("h5url", "");
    // object.put("url", "http://172.16.1.150:8810/purchase/getDetail?"
    // +
    // "type=supplier_evaluate&path=supplier-evaluation-detail&businessId=d0ff0a8b-54bf-4351-ad8d-e7cd26fc181e");
    // object.put("noneBindingSender", "guanglianda");
    // object.put("noneBindingReceiver", "guanglianda");

    // JSONObject resObj = HttpClientUtil.sendPOSTWithHeader(sendTodoUrl,
    // object.toJSONString(), header);
    // System.out.println("生成OA待办req======>" + object.toJSONString() + ",res======>"
    // + resObj.toJSONString());

    // String updateTodoUrl = "http://218.201.101.181:8180" +
    // "/seeyon/rest/thirdpartyPending/updatePendingState?token=" + token;
    // object = new JSONObject();
    // object.put("registerCode", "3007");
    // object.put("taskId","4e12f28b-8e15-4f82-afbf-59dd0b083394" );
    // object.put("state",1 );
    // object.put("subState",2 );
    // JSONObject resObj =
    // HttpClientUtil.sendPOSTWithHeader(updateTodoUrl,object.toJSONString(),
    // header);
    // System.out.println("更新OA待办req======>" + object.toJSONString() + ",res======>"
    // + resObj.toJSONString());

    // String sendMessageUrl = "http://218.201.101.181:8180" +
    // "/seeyon/rest/thirdpartyMessage/receive/singleMessage?token=" + token;
    // object = new JSONObject();
    // object.put("thirdpartyRegisterCode", "3007");
    // object.put("thirdpartyMessageId", "1");
    // object.put("messageContent", "您有一条待测试的消息。");
    // object.put("thirdpartyReceiverId", 0);
    // object.put("creation_date", creationDate2);

    // object.put("noneBindingSender", "guanglianda");
    // object.put("noneBindingReceiver", "guanglianda");

    // JSONObject resObj = HttpClientUtil.sendPOSTWithHeader(sendMessageUrl,
    // object.toJSONString(), header);
    // System.out.println("推送OA消息req======>" + object.toJSONString() + ",res======>"
    // + resObj.toJSONString());
    // }

    // public static void main(String[] args) {
    //     // 初始化RestHighLevelClient
    //     RestClientBuilder builder = RestClient.builder(new HttpHost("172.16.1.150", 9200, "http"));
       
    //     // 进行用户名密码的验证
    //     CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    //     credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "_Easy2024"));
    //     builder.setHttpClientConfigCallback((HttpAsyncClientBuilder httpAsyncclientBuidler) -> httpAsyncclientBuidler
    //             .setDefaultCredentialsProvider(credentialsProvider));

    //     RestHighLevelClient client = new RestHighLevelClient(builder);

    //     // 创建查询请求并设置索引名
    //     SearchRequest searchRequest = new SearchRequest("gld_member");

    //     // 构建查询条件
    //     SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    //     searchSourceBuilder.query(QueryBuilders.matchQuery("user_id", "5600031"));
    //     searchRequest.source(searchSourceBuilder);

    //     // 执行查询
    //     SearchResponse searchResponse;
    //     try {
    //         searchResponse = client.search(searchRequest);
    //         // 处理查询结果
    //         for (SearchHit hit : searchResponse.getHits().getHits()) {
    //             System.out.println(hit.getSourceAsString());
    //         }
    //     } catch (IOException e) {
    //         e.printStackTrace();
    //     } finally {
    //         // 关闭客户端
    //         try {
    //             client.close();
    //         } catch (IOException e) {
    //             e.printStackTrace();
    //         }
    //     }
    // }

    // ScheduledExecutorService executorService =
    // Executors.newScheduledThreadPool(2);
    // executorService.scheduleWithFixedDelay(() -> {
    // try {
    // pushFinance_W01001();
    // pushFinance_W01002();
    // pushFinance_W01004("202401");
    // pushFinance_W01004("202402");
    // pushFinance_W01004("202403");
    // pushFinance_W01004("202404");
    // pushFinance_W01004("202405");
    // pushFinance_W01004("202406");
    // pushFinance_W01004("202407");
    // pushFinance_W01004("202408");
    // pushFinance_W01003();
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }, 0, 20, TimeUnit.SECONDS);
}