package tech.easyflow.ai.node;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.IdUtil;
import com.easyagents.core.util.StringUtil;
import com.mybatisflex.core.tenant.TenantManager;
import com.easyagents.flow.core.chain.Chain;
import com.easyagents.flow.core.chain.Parameter;
import com.easyagents.flow.core.node.BaseNode;
import tech.easyflow.ai.entity.Resource;
import tech.easyflow.ai.service.ResourceService;
import tech.easyflow.ai.utils.DocUtil;
import tech.easyflow.ai.utils.WorkFlowUtil;
import tech.easyflow.common.constant.enums.EnumResourceOriginType;
import tech.easyflow.common.entity.LoginAccount;
import tech.easyflow.common.filestorage.FileStorageManager;
import tech.easyflow.common.util.SpringContextUtil;

import java.io.ByteArrayInputStream;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DownloadNode extends BaseNode {

    private Integer resourceType;

    public DownloadNode() {
    }

    public DownloadNode(Integer resourceType) {
        this.resourceType = resourceType;
    }

    @Override
    public Map<String, Object> execute(Chain chain) {
        Map<String, Object> map = chain.getState().resolveParameters(this);
        Map<String, Object> res = new HashMap<>();

        String originUrl = map.get("originUrl").toString();

        byte[] bytes = DocUtil.downloadFile(originUrl);

        String suffix = FileTypeUtil.getType(new ByteArrayInputStream(bytes));

        if (suffix == null) {
            suffix = "unknown";
        }

        String fileName = IdUtil.simpleUUID() + "." + suffix;

        FileStorageManager manager = SpringContextUtil.getBean(FileStorageManager.class);

        String resourceUrl = manager.save(new CustomFile(fileName, bytes));

        Resource resource = new Resource();

        LoginAccount account = WorkFlowUtil.getOperator(chain);

        resource.setDeptId(account.getDeptId());
        resource.setTenantId(account.getTenantId());
        resource.setResourceType(this.resourceType);
        resource.setResourceName(DocUtil.getFileNameByUrl(resourceUrl).split("\\.")[0]);
        resource.setSuffix(suffix);
        resource.setResourceUrl(resourceUrl);
        resource.setOrigin(EnumResourceOriginType.GENERATE.getCode());
        resource.setCreated(new Date());
        resource.setCreatedBy(account.getId());
        resource.setModified(new Date());
        resource.setModifiedBy(account.getId());
        resource.setFileSize(BigInteger.valueOf(bytes.length));
        try {
            TenantManager.ignoreTenantCondition();
            ResourceService service = SpringContextUtil.getBean(ResourceService.class);
            service.save(resource);
        } finally {
            TenantManager.restoreTenantCondition();
        }

        String key = "resourceUrl";
        List<Parameter> outputDefs = getOutputDefs();
        if (outputDefs != null && !outputDefs.isEmpty()) {
            String defName = outputDefs.get(0).getName();
            if (StringUtil.hasText(defName)) key = defName;
        }
        res.put(key, resourceUrl);
        return res;
    }

    public Integer getResourceType() {
        return resourceType;
    }

    public void setResourceType(Integer resourceType) {
        this.resourceType = resourceType;
    }
}
