package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.base;

import cn.estsh.i3plus.ext.mes.pcn.api.base.IFileManageService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.ISxPcnHttpService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.util.PcnHttpUtil;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.JsonUtilTool;
import cn.estsh.i3plus.platform.common.tool.SerializeTool;
import cn.estsh.i3plus.pojo.base.bean.BaseResultBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesConfig;
import cn.estsh.i3plus.pojo.mes.bean.MesFile;
import cn.estsh.i3plus.pojo.platform.bean.SysFile;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author wangjie
 * @version 1.0
 * @date 2021/1/13 9:28
 **/
@Slf4j
@Service
public class FileManageService implements IFileManageService {

    @Autowired
    private ISxPcnHttpService pcnHttpService;

    @Override
    public SysFile uploadFile(MultipartFile file, String organizeCode) {
        SysFile sysFile;
        try {
            sysFile = doUploadFileByHttpToMes(file, organizeCode);
        } catch (IOException e) {
            log.error("FastDFS上传文件出错：{}", e.getMessage() + "\r" + e.getStackTrace());
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                    .setErrorDetail("上传文件至文件服务器出错了。信息为:%s", e.getMessage())
                    .build();
        }
        if (null == sysFile) {
            log.error("FastDFS上传文件出错");
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                    .setErrorDetail("FastDFS上传文件出错")
                    .build();
        }
        if (StringUtils.isEmpty(sysFile.getFileTypeId())) {
            log.error("FastDFS上传文件出错：{}", "未在字典中定义该文件类型，无法上传成功，请先添加file_type字典");
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                    .setErrorDetail("未在字典中定义该文件类型，无法上传成功，请先添加file_type字典")
                    .build();
        }
        return sysFile;
    }

    private SysFile doUploadFileByHttpToMes(MultipartFile file, String organizeCode) throws IOException {
        SysFile sysFile = null;
        String requestUrl = pcnHttpService.getRequestUrl(organizeCode, MesPcnExtConstWords.UPLOAD_FILE_URL);

        Map<String, String> params = new HashMap<>();
        params.put(MesPcnExtConstWords.FILE_BYTE, SerializeTool.serialization(file.getBytes()));
        params.put(MesPcnExtConstWords.ORIGINAL_FILE_NAME, file.getOriginalFilename());
        params.put(MesPcnExtConstWords.FILE_NAME, file.getName());
        String data = PcnHttpUtil.doPost(requestUrl, params);
        BaseResultBean baseResultBean = null;
        if (!StringUtils.isEmpty(data)) {
            baseResultBean = JsonUtilTool.decode(data, BaseResultBean.class);
        } else {
            log.error("HTTP[{}]调用主接口失败", requestUrl);
        }
        if (null != baseResultBean && baseResultBean.success) {
            LinkedHashMap resultObject = (LinkedHashMap) baseResultBean.getResultObject();
            sysFile = JsonUtilTool.decode(JSONObject.toJSONString(resultObject), SysFile.class);
        }
        return sysFile;
    }

    @Override
    public String getFileUrl(MesConfig config, MesFile fileDb) {
        String fileUrl = getLocalFileUrl(config, fileDb);
        if (StringUtils.isEmpty(fileUrl)) {
//            HttpURLConnection urlcon = null;
//            try {
//                URL url = new URL(fileDb.getFileUrl());
//                urlcon = (HttpURLConnection) url.openConnection();
//                urlcon.setConnectTimeout(1000);
//                if (urlcon.getResponseCode() < 400) {
//                    fileUrl = fileDb.getFileUrl();
//                }
//            } catch (Exception e) {
//            } finally {
//                if (null != urlcon) {
//                    urlcon.disconnect();
//                }
//            }
            fileUrl = fileDb.getFileUrl();
        }
        return fileUrl;
    }

    private String getLocalFileUrl(MesConfig config, MesFile fileDb) {
        if (null != config && !StringUtils.isEmpty(config.getCfgValue())) {
            String pathName = getPathName(config.getCfgValue(), fileDb);
            File file = new File(pathName);
            if (null != file) {
                return pathName;
            }
        }
        return null;
    }

    private String getPathName(String cfgValue, MesFile fileDb) {
        return new StringBuilder().append(cfgValue)
                .append(File.separator).append(fileDb.getGroupName())
                .append(File.separator).append(fileDb.getFileName()).toString();
    }


}
