package com.yeejoin.amos.kgd.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yeejoin.amos.boot.core.utils.RestTemplateUtil;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.kgd.message.Constant;
import io.github.classgraph.json.JSONUtils;
import io.micrometer.core.instrument.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.context.SpringContextHelper;

import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: xl
 * @Description:
 * @Date: 2023/10/10 16:21
 */
@SuppressWarnings("UnnecessarySemicolon")
public class ClientHandler<path> implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(ClientHandler.class);

    private final Socket socket;

    private final String hostAndPort;

    public ClientHandler(Socket socket, String hostAndPort) {
        this.socket = socket;
        this.hostAndPort = hostAndPort;
    }

    @Override
    public void run() {
        try {
            // 获取输入流和输出流
            InputStream ips = socket.getInputStream();
            // 处理客户端请求
            log.info("收到客户端数据: ");
            String path = this.upload2Maas(ips, hostAndPort);
            log.info("调用maas服务返回结果: {}", path);
            // 关闭连接
            byte[] bytes = path.getBytes();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String upload2Maas(InputStream inputStream, String hostAndPort) throws IOException {
        AmosRequestContext robotAuthentication = SpringContextHelper.getBean(AmosRequestContext.class);
        if (Objects.nonNull(robotAuthentication)) {
            String token = robotAuthentication.getToken();
            String product = robotAuthentication.getProduct();
            String appKey = robotAuthentication.getAppKey();
            //上传maas


            //upload
            String uploadUrl = "http://" + hostAndPort + "/maas/dsm/excel/upload";
            MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
            Resource resource = new InputStreamResource(inputStream) {
                @Override
                public long contentLength() throws IOException {
                    long size = inputStream.available();
                    return size;
                }

                @Override
                public String getFilename() {
                    return "xlsx";
                }
            };
            params.add("file", resource);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, getHeader(token,product,appKey,hostAndPort,true));
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.exchange(uploadUrl, HttpMethod.POST, requestEntity, String.class);
            String body = responseEntity.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            String result = jsonObject.getString("result");
            String path = jsonObject.getString("path");
            if (jsonObject.getString("status").equals("200")){
                log.info("路径："+path+"/"+result);
            }else {
                throw new RuntimeException("返回状态码错误");
            }

            //sheets
            String sheetsUrl = "http://" + hostAndPort + "/maas/dsm/excel/sheets";
            Map<String, String> sheetsParams = new HashMap<>();
            sheetsParams.put("fileName", result);
            HttpEntity<Map<String, String>> sheetsRequestEntity = new HttpEntity<>(sheetsParams, getHeader(token,product,appKey,hostAndPort,false));
            ResponseEntity<String> sheetsResponseEntity = restTemplate.exchange(sheetsUrl, HttpMethod.POST, sheetsRequestEntity, String.class);
            String sheetsResponseEntityBody = sheetsResponseEntity.getBody();
            JSONObject sheetJsonObject = JSONObject.parseObject(sheetsResponseEntityBody);
            JSONArray sheetArray = sheetJsonObject.getJSONArray("result");
            //result可能有多个sheet
            String[] sheets = new String[sheetArray.size()];
            for (int i = 0; i < sheetArray.size(); i++) {
                sheets[i] = (String) sheetArray.getJSONObject(i).get("sheet");
            }
            log.info("sheets的结果是:" + sheetsResponseEntityBody);


            //datasource(name:excel+时间戳)
            // 获取当前时间的时间戳
            long timestamp = System.currentTimeMillis();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String timestampStr = sdf.format(new Date(timestamp));
            String datasourceUrl = "http://" + hostAndPort + "/maas/dsm/datasources";
            JSONObject all = new JSONObject();
            JSONObject oneJson = new JSONObject();
            all.put("filepath",result);
            for (int i = 0; i < sheetArray.size(); i++) {
                oneJson.put(sheets[i],sheetArray.get(i));
            }
            all.put("config",oneJson);

            Map<String, String> datasourceParams = new HashMap<>();
            datasourceParams.put("detail", all.toString());
            datasourceParams.put("groupid", "72684d79-5d28-4086-9f21-5b091b6675db");
            datasourceParams.put("subtype", "excel");
            datasourceParams.put("name", "excel"+timestampStr);
            datasourceParams.put("type", "File");
            HttpEntity<Map<String, String>> datasourceRequestEntity = new HttpEntity<>(datasourceParams, getHeader(token,product,appKey,hostAndPort,false));
            ResponseEntity<String> datasourceResponseEntity = restTemplate.exchange(datasourceUrl, HttpMethod.POST, datasourceRequestEntity, String.class);
            String datasourceResponseEntityBody = datasourceResponseEntity.getBody();
            log.info("datasourceResponseEntityBody:" + datasourceResponseEntityBody);
            return path + "/" + result;
        }
        return null;
    }

    private HttpHeaders getHeader(String token,String product,String appKey,String hostAndPort,Boolean isUpload){
        HttpHeaders header = new HttpHeaders();
        header.add(Constant.TOKEN, token);
        header.add(Constant.PRODUCT, product);
        header.add(Constant.APPKEY, appKey);
        if (isUpload){
            header.setContentType(MediaType.MULTIPART_FORM_DATA);
        }else {
            header.setContentType(MediaType.APPLICATION_JSON);
        }
        return header;
    }

    public static void main(String[] args) throws Exception {
        requestInfoToSocketServer();
    }

    private static void requestInfoToSocketServer() {
        try {
            Socket socket = new Socket("127.0.0.1", 7777);
            OutputStream ops = socket.getOutputStream();
            FileInputStream fis = new FileInputStream("D:\\SamData\\RecordXLS\\測試\\第一阶段任务与考核指标.xlsx");
            int len = 0;
            byte[] bs = new byte[20480];
            while ((len = fis.read(bs)) != -1) {
                ops.write(bs, 0, len);
            }
            socket.shutdownOutput();
            ops.flush();
            //开始接收服务端的消息
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            log.info("接收到服务端的回复:" + in.readLine());
        } catch (Exception e) {
            log.info("Socket传输数据异常!" + e.getMessage());
        }
    }
}