package com.java110.api.smo.file.impl;

import com.alibaba.fastjson.JSONObject;
import com.java110.api.smo.DefaultAbstractComponentSMO;
import com.java110.api.smo.file.IAddFileSMO;
import com.java110.config.properties.code.Java110Properties;
import com.java110.core.client.CosUploadTemplate;
import com.java110.core.client.FtpUploadTemplate;
import com.java110.core.client.OssUploadTemplate;
import com.java110.core.context.IPageData;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.file.FileDto;
import com.java110.intf.common.IFileInnerServiceSMO;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.MappingConstant;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.COSUtil;
import com.java110.utils.util.DateUtil;
import com.java110.utils.util.OSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.java110.vo.ResultVo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 添加项目服务实现类
 * add by wuxw 2019-06-30
 */
@Service("addFileSMOImpl")
public class AddFileSMOImpl extends DefaultAbstractComponentSMO implements IAddFileSMO {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IFileInnerServiceSMO fileInnerServiceSMOImpl;

    @Autowired
    private Java110Properties java110Properties;

    @Autowired
    private OssUploadTemplate ossUploadTemplate;

    @Autowired
    private CosUploadTemplate cosUploadTemplate;

    @Autowired
    private FtpUploadTemplate ftpUploadTemplate;

    private static final String ROOT_PATH = "hc/";
    private static final String IMAGE_DEFAULT_PATH = "img/";

    @Override
    public ResponseEntity<String> saveFile(IPageData pd, MultipartFile uploadFile) throws IOException {
        InputStream is = null;
        try {
            JSONObject paramIn = JSONObject.parseObject(pd.getReqData());
            if (uploadFile.getSize() > 200 * 1024 * 1024) {
                throw new IllegalArgumentException("上传文件超过200兆");
            }
            Assert.hasKeyAndValue(paramIn, "suffix", "必填，请填写文件类型");

            String suffix = paramIn.getString("suffix");

            // APK 文件保存到本地磁盘 /park/apk/
            if ("apk".equalsIgnoreCase(suffix)) {
                String apkFileName = UUID.randomUUID().toString() + ".apk";
                String apkDir = "/park/apk/";
                File dir = new File(apkDir);
                if (!dir.exists()) {
                    boolean created = dir.mkdirs();
                    if (!created) {
                        throw new IOException("无法创建APK存储目录: " + apkDir);
                    }
                }
                File apkFile = new File(apkDir + apkFileName);
                is = uploadFile.getInputStream();
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(apkFile);
                    byte[] buf = new byte[8192];
                    int len;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                } finally {
                    if (fos != null) { try { fos.close(); } catch (Exception ignored) {} }
                    if (is != null) { try { is.close(); } catch (Exception ignored) {} }
                    is = null; // 防止外层 finally 重复关闭
                }

                JSONObject outParam = new JSONObject();
                outParam.put("fileId", "apk/" + apkFileName);
                outParam.put("url", "/app/downloadApk?file=apk/" + apkFileName);
                return new ResponseEntity<>(outParam.toJSONString(), HttpStatus.OK);
            }

            String datePath = DateUtil.getNowII();
            String urlPath = IMAGE_DEFAULT_PATH + datePath + "/" + UUID.randomUUID().toString() + "." + suffix;

            String ossSwitch = MappingCache.getValue(MappingConstant.FILE_DOMAIN, OSSUtil.OSS_SWITCH);
            is = uploadFile.getInputStream();
            if (OSSUtil.OSS_SWITCH_OSS.equals(ossSwitch)) {
                ossUploadTemplate.upload(is, ROOT_PATH + urlPath);
            } else if (COSUtil.COS_SWITCH_COS.equals(ossSwitch)) {
                cosUploadTemplate.upload(is, ROOT_PATH + urlPath);
            } else {
                String ftpServer = MappingCache.getValue(FtpUploadTemplate.FTP_DOMAIN, FtpUploadTemplate.FTP_SERVER);
                int ftpPort = Integer.parseInt(MappingCache.getValue(FtpUploadTemplate.FTP_DOMAIN, FtpUploadTemplate.FTP_PORT));
                String ftpUserName = MappingCache.getValue(FtpUploadTemplate.FTP_DOMAIN, FtpUploadTemplate.FTP_USERNAME);
                String ftpUserPassword = MappingCache.getValue(FtpUploadTemplate.FTP_DOMAIN, FtpUploadTemplate.FTP_USERPASSWORD);
                ftpUploadTemplate.upload(is, ftpServer, ftpPort, ftpUserName, ftpUserPassword, ROOT_PATH + urlPath);
            }

            JSONObject outParam = new JSONObject();
            outParam.put("fileId", urlPath);
            String imgUrl = MappingCache.getValue(MappingConstant.FILE_DOMAIN, "IMG_PATH");
            outParam.put("url", imgUrl + urlPath);

            return new ResponseEntity<>(outParam.toJSONString(), HttpStatus.OK);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
        }
    }

    @Override
    public ResponseEntity<String> savePhotoFile(IPageData pd) {

        String images = pd.getReqData();
        JSONObject imageObj=JSONObject.parseObject(images);
        JSONObject paramIn = new JSONObject();
        paramIn.put("context", imageObj.getString("uploadFile"));
        paramIn.put("fileName", "upload.jpg");

        FileDto fileDto = BeanConvertUtil.covertBean(paramIn, FileDto.class);

        fileDto.setFileId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_file_id));
//        String file = paramIn.getString("fileName");
//        if (file.contains("mp4") || file.contains("MP4") || file.contains("AVI") || file.contains("avi")
//                || file.contains("WMV") || file.contains("wmv")) {
//            fileDto.setFlag("");
//        } else {
//            fileDto.setFlag("0");
//        }

        String fileName = fileInnerServiceSMOImpl.saveFile(fileDto);

        JSONObject data = new JSONObject();
        data.put("fileId", fileName);
        String imgUrl = MappingCache.getValue(MappingConstant.FILE_DOMAIN,"IMG_PATH");
        data.put("url", imgUrl + fileName);

        return ResultVo.createResponseEntity(data);
    }



    public RestTemplate getRestTemplate() {
        return restTemplate;
    }

    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
}
