package com.zcloud.basic.info.command;

import cn.hutool.json.JSONObject;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.jjb.saas.framework.auth.model.SSOUser;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.zcloud.basic.info.command.convertor.ImgFilesCoConvertor;
import com.zcloud.basic.info.domain.config.DaHuaConfig;
import com.zcloud.basic.info.domain.gateway.ImgFilesGateway;
import com.zcloud.basic.info.domain.model.ImgFilesE;
import com.zcloud.basic.info.domain.utils.ImageCompressUtil;
import com.zcloud.basic.info.dto.ImgFilesAddCmd;
import com.zcloud.basic.info.dto.clientobject.ImgFilesCO;
import com.zcloud.basic.info.dto.clientobject.ImgFilesInfoCO;
import com.zcloud.basic.info.persistence.dataobject.ImgFilesDO;
import com.zcloud.basic.info.persistence.repository.ImgFilesRepository;
import com.zcloud.gbscommon.utils.FileUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * web-app
 *
 * @Author zhangyue
 * @Date 2025-10-30 16:10:00
 */
@Component
@AllArgsConstructor
@Slf4j
public class ImgFilesAddExe {
    private final ImgFilesGateway imgFilesGateway;
    private final ImgFilesCoConvertor imgFilesCoConvertor;
    private final ImgFilesRepository imgFilesRepository;
    private final DaHuaConfig daHuaConfig;
    @Transactional(rollbackFor = Exception.class)
    public SingleResponse<ImgFilesCO> execute(ImgFilesAddCmd cmd) {
        if (daHuaConfig.getDockFlag() == 1 && (cmd.getType() == 608 || cmd.getType() == 13)){
            try {
                for (MultipartFile multipartFile : cmd.getFiles()){
                    String base64ImgStr = FileUtil.multipartFileToBase64(multipartFile);
                    JSONObject resultJsonObject = daHuaConfig.uploadPersonAvatar(base64ImgStr);
                    // 如果不合格，直接返回不合格
                    if (resultJsonObject.getBool("success")){
                        cmd.setDaHuaFilePath(resultJsonObject.getJSONObject("data").getStr("fileUrl"));
                    } else {
                        return SingleResponse.buildFailure(resultJsonObject.toString());
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        SSOUser ssoUser = AuthContext.getCurrentUser();
        Long tenantId = 1L;
        if (ssoUser != null && ssoUser.getTenantId() != null){
            tenantId = ssoUser.getTenantId();
        }
        ImgFilesE imgFilesE = new ImgFilesE();
        BeanUtils.copyProperties(cmd, imgFilesE);
        boolean res = false;
        ImgFilesCO imgFilesCO = new ImgFilesCO();
        try {
            String filePath = imgFilesE.initAdd(daHuaConfig.getDockFlag(), tenantId, imgFilesE);
            imgFilesCO.setFilePath(filePath);
            res = true;
        } catch (Exception e) {
            log.error("保存失败", e);
            throw new RuntimeException(e);
        }
        if (!res) {
            throw new BizException("保存失败");
        }
        return SingleResponse.of(imgFilesCO);
    }


    @Transactional(rollbackFor = Exception.class)
    public SingleResponse<ImgFilesInfoCO> batchExecute(ImgFilesAddCmd cmd) {

        if (daHuaConfig.getDockFlag() == 1 && (cmd.getType() == 608 || cmd.getType() == 13)){
            Map<String, MultipartFile> filesMap = new HashMap<>();
            try {
                for (MultipartFile multipartFile : cmd.getFiles()){
                    String base64ImgStr = FileUtil.multipartFileToBase64(multipartFile);
                    JSONObject resultJsonObject = daHuaConfig.uploadPersonAvatar(base64ImgStr);
                    // 如果不合格，直接返回不合格
                    if (resultJsonObject.getBool("success")){
                        filesMap.put(resultJsonObject.getJSONObject("data").getStr("fileUrl"), multipartFile);
                    } else {
                        return SingleResponse.buildFailure(resultJsonObject.toString());
                    }
                }
                cmd.setFilesMap(filesMap);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        SSOUser ssoUser = AuthContext.getCurrentUser();
        Long tenantId = 1L;
        if (ssoUser != null && ssoUser.getTenantId() != null){
            tenantId = ssoUser.getTenantId();
        }
        ImgFilesE imgFilesE = new ImgFilesE();
        BeanUtils.copyProperties(cmd, imgFilesE);
        boolean res = false;
        ImgFilesInfoCO imgFilesCO = new ImgFilesInfoCO();
        try {
            List<ImgFilesE> imgFilesEList = new ArrayList<>();
            if (daHuaConfig.getDockFlag() == 1 && (cmd.getType() == 608 || cmd.getType() == 13)){
                imgFilesEList = imgFilesE.initDaHuaBatchAdd(tenantId, imgFilesE);
            } else {
                imgFilesEList = imgFilesE.initBatchAdd(tenantId, imgFilesE);
            }
            List<ImgFilesDO> imgFilesDOList = imgFilesCoConvertor.converEsToDOs(imgFilesEList);
            imgFilesRepository.saveBatch(imgFilesDOList);
            List<ImgFilesCO> imgFilesCOList = imgFilesCoConvertor.converDOsToCOs(imgFilesDOList);
            imgFilesCO.setFileList(imgFilesCOList);
            imgFilesCO.setForeignKey(imgFilesE.getForeignKey());
            res = true;
        } catch (Exception e) {
            log.error("保存失败", e);
            throw new RuntimeException(e);
        }
        if (!res) {
            throw new BizException("保存失败");
        }
        return SingleResponse.of(imgFilesCO);
    }

}

