package com.cftech.base.org.api;

import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.core.constants.MpApiConstants;
import com.cftech.core.constants.WxApiConstants;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.QyTokenUtil;
import com.cftech.core.util.SystemConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

/**
 * Created by liuling on 2017/2/28.
 */
@Slf4j
@Component
public class QyMediaUtil {

    private final QyTokenUtil qyTokenUtil;

    @Autowired
    private MpTokenUtil mpTokenUtil;

    // 图片目录
    public static final String USER_IMAGES_DIR = SystemConfig.p.getProperty("userfiles.imgdir");

    @Autowired
    public QyMediaUtil(QyTokenUtil qyTokenUtil) {
        this.qyTokenUtil = qyTokenUtil;
    }

    public static String getFileEndWitsh(String contentType) {
        String fileEndWitsh = "";
        if ("image/jpeg".equals(contentType))
            fileEndWitsh = ".jpg";
        else if ("audio/mpeg".equals(contentType))
            fileEndWitsh = ".mp3";
        else if ("audio/amr".equals(contentType))
            fileEndWitsh = ".amr";
        else if ("video/mp4".equals(contentType))
            fileEndWitsh = ".mp4";
        else if ("video/mpeg4".equals(contentType))
            fileEndWitsh = ".mp4";
        return fileEndWitsh;
    }

    public static String getRundomName(String moduleName) {
        String res = moduleName + "" + UUID.randomUUID().toString();
        return res;
    }

    /**
     * 下载媒体文件至磁盘(服务号)
     *
     * @param accountsId 微信账号
     * @param moduleName 模块名称，可不填
     * @param mediaId    媒体的Id
     * @return 形成的文件名称
     */
    public String downloadMpMediaToDisk(Long accountsId, String moduleName, String mediaId) {
        String finalFileName = "";
        MpAccountsEntity accountsEntity = mpTokenUtil.searchAccountsById(accountsId);
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        HttpURLConnection conn = null;

        String requestUrl = MpApiConstants.MEDIA_GET.replace("ACCESS_TOKEN", mpTokenUtil.getToken(accountsEntity))
                .replace("MEDIA_ID", mediaId);

        try {
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");

            //String fileExt = getFileEndWitsh(conn.getHeaderField("Content-Type"));
            String fileExt = ".jpg";
            String fileName = getRundomName(moduleName);
            finalFileName = fileName + fileExt;


            String dir = USER_IMAGES_DIR;
            File ff = new File(dir);
            if (!ff.exists()) {
                ff.mkdir();
            }
            String realPath = dir + File.separator + finalFileName;
            bis = new BufferedInputStream(conn.getInputStream());
            fos = new FileOutputStream(new File(realPath));
            byte[] buf = new byte[8096];
            int size = 0;
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            fos.close();
            bis.close();
            conn.disconnect();
        } catch (IOException e) {
            log.error("下载媒体文件失败：{}", e.getMessage());
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error("下载媒体文件失败 IOException：{}", e.getMessage());
                }
            }

            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    log.error("下载媒体文件失败 IOException：{}", e.getMessage());
                }
            }

            if (conn != null) {
                conn.disconnect();
            }
        }

        return finalFileName;
    }

    /**
     * 下载媒体文件至磁盘
     *
     * @param accountsId 微信账号
     * @param moduleName 模块名称，可不填
     * @param mediaId    媒体的Id
     * @return 形成的文件名称
     */
    public String downloadMediaToDisk(Long accountsId, String moduleName, String mediaId) {
        String finalFileName = "";
        MpAccountsEntity accountsEntity = qyTokenUtil.searchAccountsById(accountsId);
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        HttpURLConnection conn = null;

        String requestUrl = WxApiConstants.GET_MEDIA.replace("ACCESS_TOKEN", qyTokenUtil.getToken(accountsEntity))
                .replace("MEDIA_ID", mediaId);

        try {
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");

            String fileExt = getFileEndWitsh(conn.getHeaderField("Content-Type"));
            String fileName = getRundomName(moduleName);
            finalFileName = fileName + fileExt;


            String dir = USER_IMAGES_DIR + accountsId;
            File ff = new File(dir);
            if (!ff.exists()) {
                ff.mkdir();
            }
            String realPath = dir + File.separator + finalFileName;
            bis = new BufferedInputStream(conn.getInputStream());
            fos = new FileOutputStream(new File(realPath));
            byte[] buf = new byte[8096];
            int size = 0;
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            fos.close();
            bis.close();
            conn.disconnect();
        } catch (IOException e) {
            log.error("下载媒体文件失败：{}", e.getMessage());
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error("下载媒体文件失败 IOException：{}", e.getMessage());
                }
            }

            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    log.error("下载媒体文件失败 IOException：{}", e.getMessage());
                }
            }

            if (conn != null) {
                conn.disconnect();
            }
        }

        return finalFileName;
    }
}
