package com.zcloud.basic.info.facade;

import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.jjb.saas.framework.auth.model.SSOUser;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.zcloud.basic.info.api.ImgFilesServiceI;
import com.zcloud.basic.info.command.convertor.ImgFilesCoConvertor;
import com.zcloud.basic.info.domain.utils.Smb;
import com.zcloud.basic.info.dto.ImgFilesAddCmd;
import com.zcloud.basic.info.dto.ImgFilesQryCmd;
import com.zcloud.basic.info.dto.clientobject.ImgFilesCO;
import com.zcloud.gbscommon.utils.DateUtil;
import com.zcloud.gbscommon.utils.Tools;
import com.zcloud.gbscommon.zcloudimgfiles.facade.ZcloudImgFilesFacade;
import com.zcloud.gbscommon.zcloudimgfiles.request.ZcloudImgFilesAddCmd;
import com.zcloud.gbscommon.zcloudimgfiles.request.ZcloudImgFilesQryCmd;
import com.zcloud.gbscommon.zcloudimgfiles.response.ZcloudImgFilesCO;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

/**
 * @author zhangyue
 * @date 2025/12/3 10:43
 */
@DubboService
public class ZcloudImgFilesFacadeImpl implements ZcloudImgFilesFacade {
    @Resource
    private ImgFilesServiceI imgFilesService;
    @Resource
    private ImgFilesCoConvertor imgFilesCoConvertor;
    @Override
    public MultiResponse<ZcloudImgFilesCO> listAll(ZcloudImgFilesQryCmd zcloudImgFilesQryCmd) {
        ImgFilesQryCmd imgFilesQryCmd = new ImgFilesQryCmd();
        BeanUtils.copyProperties(zcloudImgFilesQryCmd, imgFilesQryCmd);
        MultiResponse<ImgFilesCO> response = imgFilesService.listAll(imgFilesQryCmd);
        List<ZcloudImgFilesCO> zcloudImgFilesCo = imgFilesCoConvertor.converCOsToDubboCOs(response.getData());
        return MultiResponse.of(zcloudImgFilesCo);
    }

    @Override
    public String saveFile(String multipartFile, String fileName, String path) {
        SSOUser ssoUser = AuthContext.getCurrentUser();
        String filePath = ssoUser.getTenantId().toString() + "/" + DateUtil.getMonth() + "/" + path;
        // 文件上传并获取上传路径
        String resultFilePath = null;
        try {
            resultFilePath = Smb.saveFile(base64ToInputStream(multipartFile),fileName, filePath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return  resultFilePath;
    }

    @Override
    public String saveFile(byte[] bytes, String fileName, String path) {
        SSOUser ssoUser = AuthContext.getCurrentUser();
        String filePath = ssoUser.getTenantId().toString() + "/" + DateUtil.getMonth() + "/" + path;
        // 文件上传并获取上传路径
        String resultFilePath = null;
        try {
            resultFilePath = Smb.saveFile(new ByteArrayInputStream(bytes),fileName, filePath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return  resultFilePath;
    }

    @Override
    public String saveFile(byte[] bytes, String fileName, String path, Long corpinfoId) {
        String filePath = corpinfoId.toString() + "/" + DateUtil.getMonth() + "/" + path;
        // 文件上传并获取上传路径
        String resultFilePath = null;
        try {
            resultFilePath = Smb.saveFile(new ByteArrayInputStream(bytes),fileName, filePath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return  resultFilePath;
    }

    @Override
    public String saveFileNoCorpinfoId(byte[] bytes, String fileName, String path) {
         String filePath =  DateUtil.getMonth() + "/" + path;
        // 文件上传并获取上传路径
        String resultFilePath = null;
        try {
            resultFilePath = Smb.saveFile(new ByteArrayInputStream(bytes),fileName, filePath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return  resultFilePath;
    }


    @Override
    public Response deleteFiles(String foreignKey, String type) {
        if (ObjectUtils.isEmpty(foreignKey)){
            return Response.buildFailure("文件foreignKey不能为空");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("eqForeignKey", foreignKey);
        if (!ObjectUtils.isEmpty(type)){
            params.put("eqType", type);
        }
        params.put("eqDeleteEnum", "FALSE");
        imgFilesService.removeBatch(params);
        return Response.buildSuccess();
    }

    @Override
    public Response deleteFiles(List<String> foreignKeyList, String type) {
        if (foreignKeyList == null || foreignKeyList.size() == 0){
            return Response.buildFailure("文件foreignKey不能为空");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("inForeignKey", foreignKeyList);
        if (!ObjectUtils.isEmpty(type)){
            params.put("eqType", type);
        }
        params.put("eqDeleteEnum", "FALSE");
        imgFilesService.removeBatch(params);
        return Response.buildSuccess();
    }

    @Override
    public Response deleteFileList(List<String> filePathList) {
        if (filePathList == null || filePathList.size() == 0){
            return Response.buildFailure("文件路径不能为空");
        }
        filePathList.forEach(filePath -> {
            imgFilesService.removeFile(filePath);
        });
        return Response.buildSuccess();
    }


    public static InputStream base64ToInputStream(String base64String) {
        if (base64String == null || base64String.isEmpty()) {
            throw new IllegalArgumentException("Base64 string is null or empty");
        }

        String data = base64String;
        if (base64String.contains(",")) {
            data = base64String.substring(base64String.indexOf(",") + 1);
        }

        byte[] bytes = Base64.getDecoder().decode(data);
        return new ByteArrayInputStream(bytes);
    }
}
