package com.brilliance.isc.doc.convert;

import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.mda.runtime.mda.util.Strings;
import com.brilliance.isc.common.codetable.service.CodetableService;
import com.brilliance.isc.common.context.SettleContext;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.brilliance.mda.runtime.mda.Constants.NULLSTR;

@Component
@ConfigurationProperties(prefix = "allcode")
@PropertySource(value = "classpath:swift-tag-code.yml", factory = CompositePropertySourceFactory.class)
@Setter
@Getter
public class TagCodeFormater {

    @Resource
    private CodetableService codetableService;

    private List<TagCode> swtovr20;

    private List<TagCode> swtsup20;


    private Map<String, TagCode> swtovr20Map = new HashMap<>();

    private Map<String, TagCode> swtsup20Map = new HashMap<>();

    @PostConstruct
    public void build() {
        if (!swtovr20.isEmpty()) {
            swtovr20.forEach(tagCode -> {
                swtovr20Map.put(tagCode.getTagKey(), tagCode);
            });
        }

        if (!swtsup20.isEmpty()) {
            swtsup20.forEach(tagCode -> {
                swtsup20Map.put(tagCode.getTagKey(), tagCode);
            });
        }
    }

    public String formatCodeContent(String mt, String tag, String code) {
        //为swtovr20准备Key做准备
        String mtTag = tag;
        if (StringUtils.isNotEmpty(mt)) {
            mt = mt.toLowerCase();
            if (!mt.startsWith("mt")) {
                mt = "mt" + mt;
            }
            mtTag = mt + "-" + tag;
        }
        //寻找MT TAG
        TagCode tagCode = swtovr20Map.get(mtTag);
        if (tagCode == null) {
            tagCode = swtsup20Map.get(null + "-" + tag);
        }
        if (tagCode == null) {
            return swtGetTextForCode(tag, mt, code);
        }
        return formatCodeContent(mt, tagCode, code);
    }

    public String formatCodeContent(String mt, TagCode tag, String code) {
        String label = null;
        if (StringUtils.isNotEmpty(tag.getCode())) {
            label = codetableService.getTblLabel(code, tag.getCode());
        } else if (!tag.getDirectCode().isEmpty()) {
            label = tag.getDirectCode().get(code);

        }
        if (StringUtils.isNotEmpty(label)) {
            return code + " / " + label;
        }
        return code;

    }

    /**
     * //! Get long text for passed tag and code value type.
     * //! ArgTag   Mandatory   the tag for which a code longtext is seached
     * //! ArgMT    Optional      can be used to return different codes fo same tag in different messages
     * //! ArgCode  Mandatory  Codevalue for which a longtext is required
     **/
    public String swtGetTextForCode(String argTag, String argMT, String argCode) {
        //dngdev.002813
        String longtext = "";
        String tag = NULLSTR;
        int pos = 0;
        String sequence = NULLSTR;
        if (StringUtils.isNotEmpty(argTag) && StringUtils.isNotEmpty(argCode)) {
            // remove `:` from ArgTag-Content
            tag = argTag;
            pos = Strings.pos(tag, ".");
            if (pos > 0) {
                sequence = Strings.mid(tag, pos, 2);
                if (MdaUtils.compareTo(sequence, ".B") == 0 || MdaUtils.compareTo(sequence, ".C") == 0) {
                    tag = Strings.mid(tag, 1, pos - 1) + Strings.mid(tag, pos + 2);
                }
            }
            switch (tag) {
                case "12S":
                    switch (argCode) {
                        case "FLAT":
                            longtext = "Flat Amount";
                            break;
                        case "MINI":
                            longtext = "Minimum Amount";
                            break;
                        case "MAXI":
                            longtext = "Maximum Amount";
                            break;
                        case "BPOB":
                            longtext = "Payment with obligation to pay";
                            break;
                        case "NOOB":
                            longtext = "Payment without obligation to pay";
                            break;
                        default:
                    }
                    break;
                case "22A":
                    // For amendment use Codetable from SWIADD.
                    switch (SettleContext.getTransName()) {
                        case "GITAME":
                        case "GITRAM":
                            longtext = codetableService.getTblLabel(argCode, "PURPOSAME");
                            if (longtext == null) {
                                longtext = "";
                            }
                            break;
                    }
                    break;
                case "22G":
                    switch (argCode) {
                        case "PAEX":
                            longtext = "Pay or extend";
                            break;
                        case "PAYM":
                            longtext = "Pay only";
                            break;
                        default:
                            // no codes
                    }
                    // Tag :23R
                    break;
                case "23R":
                    switch (argCode) {
                        case "REJT":
                            longtext = "Rejected";
                            break;
                        case "ACCP":
                            longtext = "Accepted";
                            break;
                        default:
                            // no codes
                    }
                    break;
                case "24E":
                    if (argCode.contains("/")) {
                        String[] splitStr = argCode.split("/");
                        argCode = splitStr[0];
                        longtext = splitStr[1];
                    }
                    String delori = codetableService.getTblLabel(argCode, "DELORI");
                    longtext = StringUtils.isNotEmpty(longtext) ? delori + " / " + longtext : delori;
                    break;
                case "24G":
                    // 假设输入的字符串为inputString
                    String[] lines = argCode.split("\\r?\\n"); // 使用正则表达式拆分成每一行

                    // 假设输入的字符串为inputString
                    StringBuilder mergedLines = new StringBuilder();
                    if (lines.length > 1) { // 判断是否有多于1行的内容
                        for (int i = 1; i < lines.length; i++) { // 从第2行开始循环获取每一行
                            String currentLine = lines[i];
                            mergedLines.append(currentLine).append("\n"); // 将当前行追加到合并字符串中，并添加换行符
                        }
                    }

                    String mergedString = mergedLines.toString(); // 将StringBuilder对象转换为字符串
                    argCode = lines[0].trim();
                    switch (argCode) {
                        case "BENE":
                            longtext = "Beneficiary";
                            break;
                        case "OTHR":
                            longtext = "Specified address";
                            break;
                        default:
                            // no codes
                    }
                    if (StringUtils.isNotEmpty(mergedString)) {
                        longtext = longtext + "\n" + mergedString;
                    }
                    break;
                case "40C":
                    if (SettleContext.getUserSession() != null && SettleContext.getUserSession().getAtp() != null &&
                            MdaUtils.compareTo(SettleContext.getUserSession().getAtp().getBus(), "GI") == 0) {
                        longtext = codetableService.getTblLabel(argCode, "APPRUL");
                        if (longtext == null) {
                            longtext = "";
                        }
                    }
                    break;
                case "48D":
                    // no codes
                    if ("TRAN".equals(argCode)) {
                        longtext = "The Undertaking is transferable";
                    }
                    break;
            }
        }
        if (StringUtils.isNotEmpty(longtext)) {
            longtext = argCode + " / " + longtext;
        } else {
            longtext = argCode;
        }
        return longtext;
    }

}
