package com.fs.qwApi.service.impl;

import com.alibaba.fastjson.JSON;
import com.fs.common.utils.uuid.UUID;
import com.fs.qwApi.config.QwWorkApiConfig;
import com.fs.qwApi.domain.QwWorkExternalContactListResult;
import com.fs.qwApi.domain.QwWorkExternalSendApp;
import com.fs.qwApi.domain.QwWorkLoginStatus;
import com.fs.qwApi.domain.QwWorkMsgResult;
import com.fs.qwApi.service.QwWorkApiService;
import org.apache.hc.core5.net.URIBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;

@Service
public class QwWorkApiServiceImpl implements QwWorkApiService {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(QwWorkApiService.class);

    @Override
    public QwWorkExternalContactListResult getUserList() {
        HashMap<String, Integer> map= new HashMap<>();
        map.put("type",2000);
        map.put("page_num",1);
        map.put("page_size",100);
        String send = sendPost(map);
        log.info(send);
        QwWorkExternalContactListResult qwWorkExternalContactListResult = JSON.parseObject(send, QwWorkExternalContactListResult.class);
        return qwWorkExternalContactListResult;
    }

    @Override
    public QwWorkMsgResult sendMsg(String userId, String msg) {
        HashMap<String, Object> map= new HashMap<>();
        map.put("type",3000);
        map.put("user_id",userId);
        map.put("msg",msg);
        String send = sendPost(map);
        log.info(send);
        QwWorkMsgResult qwWorkMsgResult = JSON.parseObject(send, QwWorkMsgResult.class);
        return qwWorkMsgResult;
    }

    @Override
    public QwWorkMsgResult sendImageMsg(String userId, String imgUrl) {
        HashMap<String, Object> map= new HashMap<>();
        map.put("type",3001);
        map.put("user_id",userId);
        String path="";
        try {
            URL url = new URL(imgUrl);
            String saveDirectory = "C:\\fs\\uploadPath\\";
            String fileExtension = imgUrl.substring(imgUrl.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + fileExtension;
            path = saveDirectory + fileName;

            File directory = new File(saveDirectory);
            if (!directory.exists()) {
                directory.mkdirs(); // 如果目录不存在则创建
            }
            InputStream in = url.openStream();
            Files.copy(in, Paths.get(path));

        } catch (IOException e) {
            e.printStackTrace();
        }
        map.put("path",path);
        String send = sendPost(map);
        log.info(send);
        Path imagePath = Paths.get(path);
        try {
            Files.deleteIfExists(imagePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        QwWorkMsgResult qwWorkMsgResult = JSON.parseObject(send, QwWorkMsgResult.class);
        return qwWorkMsgResult;
    }

    @Override
    public QwWorkMsgResult sendAppMsg(QwWorkExternalSendApp app) {
        String path="";
        try {
            URL url = new URL(app.getCover_path());
            String saveDirectory = "C:\\fs\\uploadPath\\";
            String fileExtension = app.getCover_path().substring(app.getCover_path().lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + fileExtension;
            path = saveDirectory + fileName;

            File directory = new File(saveDirectory);
            if (!directory.exists()) {
                directory.mkdirs(); // 如果目录不存在则创建
            }
            InputStream in = url.openStream();
            Files.copy(in, Paths.get(path));

        } catch (IOException e) {
            e.printStackTrace();
        }
        app.setType(3006);
        app.setCover_path(path);
        String send = sendPost(app);
        log.info(send);
//        try {
//            Path imagePath = Paths.get(path);
//            Files.deleteIfExists(imagePath);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        QwWorkMsgResult qwWorkMsgResult = JSON.parseObject(send, QwWorkMsgResult.class);
        return qwWorkMsgResult;

    }

    @Override
    public QwWorkLoginStatus loginStatus() {
        HashMap<String, Object> map= new HashMap<>();
        map.put("type",1000);
        String send = sendPost(map);
        QwWorkLoginStatus qwWorkLoginStatus = JSON.parseObject(send, QwWorkLoginStatus.class);
        log.info(send);
        return qwWorkLoginStatus;
    }
    @Override
    public QwWorkMsgResult login() {
        HashMap<String, Object> map= new HashMap<>();
        map.put("type",1001);
        String saveDirectory = "C:\\fs\\uploadPath\\"+"login" + ".png";

        map.put("path",saveDirectory);
        String send = sendPost(map);
        log.info(send);
        QwWorkMsgResult qwWorkMsgResult = JSON.parseObject(send, QwWorkMsgResult.class);
        return qwWorkMsgResult;
    }

    @Override
    public QwWorkMsgResult LogOut() {
        HashMap<String, Object> map= new HashMap<>();
        map.put("type",1003);
        String send = sendPost(map);
        log.info(send);
        QwWorkMsgResult qwWorkMsgResult = JSON.parseObject(send, QwWorkMsgResult.class);

        return qwWorkMsgResult;
    }

    @Override
    public QwWorkMsgResult code(String code) {
        HashMap<String, Object> map= new HashMap<>();
        map.put("type",1005);
        map.put("code",code);
        String send = sendPost(map);
        log.info(send);
        QwWorkMsgResult qwWorkMsgResult = JSON.parseObject(send, QwWorkMsgResult.class);

        return qwWorkMsgResult;
    }

    public  String sendPost(Object param){
        HttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder builder = new URIBuilder(QwWorkApiConfig.api);
            URI uri = builder.build();
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("Content-Type", "application/json"); // 设置Content-Type为"application/json"
            httpPost.setEntity(new StringEntity(JSON.toJSONString(param), StandardCharsets.UTF_8));
            HttpResponse response = httpClient.execute(httpPost);
            String reJson = EntityUtils.toString(response.getEntity());
            return reJson;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
