package com.keyware.shandan.system.utils;

import cn.hutool.core.date.DateUtil;
import com.keyware.shandan.frame.properties.CustomProperties;
import com.keyware.shandan.system.entity.SysFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 调用二部文件解析服务的类
 */
@Slf4j
@Component
public class ErbuCaller {
    @Autowired
    private AsyncRestTemplate asyncRestTemplate;

    @Autowired
    private CustomProperties customProperties;

    private String[] jnaType = {"dat", "jin", "mis", "zls"};

    private final String JNA_ADDRESS_KEY = "erbu_jna_address";

    public String call(SysFile file, String result) {
        if (checkFileType(file)) {
            String jnaUrl = getJnaAddress();
            Map<String, Object> param = buildParam(file, result);
            String response = asyncRestTemplate.sendPost(jnaUrl, param);
            return "ok".equalsIgnoreCase(response)?file.getFileName()+"文件挖掘成功;": file.getFileName()+response;
        }
        return "";

    }

    /**
     * 参数封装
     *
     * @param file
     * @return
     */
    private Map<String, Object> buildParam(SysFile file, String result) {
        Map<String, Object> param = new HashMap<>();
        param.put("name", file.getFileName());
        param.put("fileName", getFileLocalPath(file));
        param.put("sourceText", file.getSource());
        param.put("taskCodeText", file.getTaskCode());
        param.put("taskNatureText", file.getTaskNature());
        param.put("troopCodeText", file.getTroopCode());
        param.put("entryStaffText", file.getEntryStaff());
        param.put("equipmentText", file.getEquipmentModel());
        param.put("result", result);
        param.put("dateText", DateUtil.format(file.getInputDate(), "yyyyMMddHHmmssSSS"));
        return param;
    }

    /**
     * 获取文件本地路径
     *
     * @param file
     * @return
     */
    private String getFileLocalPath(SysFile file) {
        return customProperties.getFileStorage().getPath() + File.separator + file.getPath();
    }

    /**
     * 获取服务地址
     *
     * @return
     */
    private String getJnaAddress() {
        return DictUtil.getPublicDict(JNA_ADDRESS_KEY);
    }

    /**
     * 检查文件格式是否符合要求
     *
     * @param file
     * @return
     */
    private boolean checkFileType(SysFile file) {
        String fileName = file.getFileName().replace("(无水印)", "").replace("（无水印）", "").toLowerCase();
        return Arrays.stream(jnaType).anyMatch(str -> str.equalsIgnoreCase(file.getFileType()))
                || fileName.startsWith("rm")
                || fileName.startsWith("rt")
                || fileName.startsWith("rmins");
    }
}
