package shop.alien.util.webdav;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.NTCredentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * WebDav上传
 *
 * @author ssk
 * @version 1.0
 * @date 2023/3/30 14:52
 */
@Slf4j
public class WebDavUpload {

    private static String host;
    private static Integer port;
    private static String prefix;

    private static void init(String url) throws MalformedURLException {
        host = url.substring(url.indexOf("//") + 2, url.lastIndexOf(":"));
        URL hp = new URL(url);
        //获得对应的端口号
        port = hp.getPort();
        prefix = url.substring(0, url.indexOf(":"));
    }

    public static void main(String[] args) {
        String webDavUrl = "http://xiaokuihua.fun:5005/Cache/douyin/";
        String webDavUserName = "ssk";
        String webDavPassWord = "!@#ZyL021405";
        String filePath = "C:\\Users\\Administrator\\Pictures\\invite-bg.jpg";
//        System.out.println(upload("http://xiaokuihua.fun:5005/Cache/学长心很愁/", webDavUserName, webDavPassWord, "D:\\douyin\\每天跟我涨知识dou是知识点奇妙知识在抖音脑洞大开关注我每天坚持分享知识20230531145652862.mp4"));
        System.out.println(createFolder(webDavUrl, "1111", webDavUserName, webDavPassWord));
    }

    /**
     * 上传到WebDav
     *
     * @param webDavUrl      链接
     * @param webDavUserName 用户名
     * @param webDavPassWord 密码
     * @param filePath       文件路径
     * @return boolean
     */
    public static boolean upload(String webDavUrl, String webDavUserName, String webDavPassWord, String filePath) {
        try {
            File file = new File(filePath);
            String fileName = file.getName();
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            Credentials credentials = new UsernamePasswordCredentials(webDavUserName, webDavPassWord);
            credentialsProvider.setCredentials(AuthScope.ANY, credentials);
            ClientConnectionManager connManager = new PoolingClientConnectionManager();
            DefaultHttpClient client = new DefaultHttpClient(connManager);
            client.setCredentialsProvider(credentialsProvider);
            HttpPut put = new HttpPut(webDavUrl + fileName);
            ByteArrayEntity entity = new ByteArrayEntity(file2byte(file));
            put.setEntity(entity);
            client.execute(put);
//            CloseableHttpResponse response = client.execute(put);
//            System.out.println(covertEntityToJSON(response.getEntity()));
        } catch (Exception e) {
            log.error("WebDavUpload upload ERROR: {}", e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 创建文件夹
     *
     * @param destpath 服务器文件夹路径
     */

    public static boolean createFolder(String webDavUrl, String destpath, String webDavUserName, String webDavPassWord) {
        try {
            init(webDavUrl);
            String path = webDavUrl + destpath;
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            NTCredentials creds = new NTCredentials(webDavUserName, webDavPassWord, "", "");
            credsProvider.setCredentials(new AuthScope(host, port, null, "ntlm"), creds);
            CloseableHttpClient httpclient = HttpClients.custom()
                    .setDefaultCredentialsProvider(credsProvider)
                    .build();
            HttpHost target = new HttpHost(host, port, prefix);
            // 保证相同的内容来用于执行逻辑相关的请求
            HttpContext localContext = new BasicHttpContext();
            HttpMkcol httpMkcol = new HttpMkcol(path);
            httpclient.execute(target, httpMkcol, localContext);
            httpclient.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private static String covertEntityToJSON(HttpEntity entity) throws Exception {
        if (entity != null) {
            return EntityUtils.toString(entity, "UTF-8");
        } else {
            return null;
        }
    }

    private static byte[] file2byte(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer;
    }

}
