package com.java110.api.components.uploadFile;

import com.alibaba.fastjson.JSONObject;
import com.java110.api.smo.file.IAddFileSMO;
import com.java110.core.context.IPageData;
import com.java110.core.context.PageData;
import com.java110.core.log.LoggerFactory;
import com.java110.utils.util.Base64Convert;
import com.java110.utils.util.StringUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

/**
 * 添加活动组件
 */
@Component("uploadFile")
public class UploadFileComponent {

    private static Logger logger = LoggerFactory.getLogger(UploadFileComponent.class);

    @Autowired
    private IAddFileSMO addFileSMOImpl;



    /**
     * 上传图片
     *
     * @param pd 页面数据封装
     * @return ResponseEntity 对象
     */
    public ResponseEntity<String> uploadImage(IPageData pd, MultipartFile uploadFile) throws Exception {
        JSONObject paramIn = JSONObject.parseObject(pd.getReqData());
        paramIn.put("suffix", "jpeg");
        IPageData newPd = PageData.newInstance().builder(pd.getUserId(), pd.getUserName(), pd.getToken(), paramIn.toJSONString(), pd.getComponentCode(), pd.getComponentMethod(), "",
                pd.getSessionId(), pd.getAppId(), pd.getHeaders());
        return addFileSMOImpl.saveFile(newPd, uploadFile);
    }

    /**
     * 上传APK文件
     */
    public ResponseEntity<String> uploadApk(IPageData pd, MultipartFile uploadFile) throws Exception {
        JSONObject paramIn = JSONObject.parseObject(pd.getReqData());
        String originalFilename = uploadFile.getOriginalFilename();
        String suffix = "apk";
        if (originalFilename != null && originalFilename.contains(".")) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        }
        paramIn.put("suffix", suffix);
        IPageData newPd = PageData.newInstance().builder(pd.getUserId(), pd.getUserName(), pd.getToken(), paramIn.toJSONString(), pd.getComponentCode(), pd.getComponentMethod(), "",
                pd.getSessionId(), pd.getAppId(), pd.getHeaders());
        return addFileSMOImpl.saveFile(newPd, uploadFile);
    }

    /**
     * 上传图片（兼容 base64 JSON 和 multipart 文件两种方式）
     *
     * @param pd 页面数据封装
     * @return ResponseEntity 对象
     */
    public ResponseEntity<String> uploadPhotoImage(IPageData pd) throws Exception {
        String reqData = pd.getReqData();
        JSONObject paramIn;

        // 尝试从 multipart 请求中提取文件（app端上传场景）
        if (StringUtil.isEmpty(reqData)) {
            ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attrs != null) {
                HttpServletRequest req = attrs.getRequest();
                if (req.getContentType() != null && req.getContentType().startsWith("multipart/form-data")) {
                    try {
                        Part part = req.getPart("uploadFile");
                        if (part != null && part.getSize() > 0) {
                            String base64 = Base64Convert.ioToBase64(part.getInputStream());
                            paramIn = new JSONObject();
                            paramIn.put("uploadFile", base64);
                            paramIn.put("suffix", "jpeg");
                            paramIn.put("fileName", part.getSubmittedFileName());
                            IPageData newPd = PageData.newInstance().builder(pd.getUserId(), pd.getUserName(), pd.getToken(),
                                    paramIn.toJSONString(), pd.getComponentCode(), pd.getComponentMethod(), "",
                                    pd.getSessionId(), pd.getAppId(), pd.getHeaders());
                            return addFileSMOImpl.savePhotoFile(newPd);
                        }
                    } catch (Exception e) {
                        logger.error("multipart解析失败: {}", e.getMessage(), e);
                    }
                }
            }
            return new ResponseEntity<>("上传文件失败: 未找到上传文件", org.springframework.http.HttpStatus.BAD_REQUEST);
        } else {
            paramIn = JSONObject.parseObject(reqData);
            // 兼容 base64 JSON 方式
            if (!paramIn.containsKey("uploadFile") || StringUtil.isEmpty(paramIn.getString("uploadFile"))) {
                return new ResponseEntity<>("上传文件失败: uploadFile 参数为空", org.springframework.http.HttpStatus.BAD_REQUEST);
            }
        }
        paramIn.put("suffix", "jpeg");
        IPageData newPd = PageData.newInstance().builder(pd.getUserId(), pd.getUserName(), pd.getToken(), paramIn.toJSONString(), pd.getComponentCode(), pd.getComponentMethod(), "",
                pd.getSessionId(), pd.getAppId(), pd.getHeaders());
        return addFileSMOImpl.savePhotoFile(newPd);
    }

    /**
     * 上传图片（multipart文件方式）
     *
     * @param pd 页面数据封装
     * @param uploadFile 上传文件
     * @return ResponseEntity 对象
     */
    public ResponseEntity<String> uploadPhotoImage(IPageData pd, MultipartFile uploadFile) throws Exception {
        JSONObject paramIn = new JSONObject();
        paramIn.put("suffix", "jpeg");
        IPageData newPd = PageData.newInstance().builder(pd.getUserId(), pd.getUserName(), pd.getToken(), paramIn.toJSONString(), pd.getComponentCode(), pd.getComponentMethod(), "",
                pd.getSessionId(), pd.getAppId(), pd.getHeaders());
        return addFileSMOImpl.saveFile(newPd, uploadFile);
    }
}
