package com.brilliance.isc.swift.objmtconvert.util;

import com.brilliance.swift.exception.SwiftException;
import com.brilliance.isc.swift.objmtconvert.ext.OrderedProperties;
import com.brilliance.isc.swift.objmtconvert.result.MtResult;
import com.brilliance.swift.util.StringUtil;
import com.prowidesoftware.swift.model.SwiftBlock3;
import com.prowidesoftware.swift.model.mt.AbstractMT;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author gechengyang
 * @date 2023/2/14
 */
public class MTUtil {

    private static String BIC_PREFIX = "AXXX";
    private static final String pattern = "yyyyMMdd";

    public static Date getCurrentDate() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String transformDate = simpleDateFormat.format(new Date());
        try {
            return simpleDateFormat.parse(transformDate);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getDateStr() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String transformDate = simpleDateFormat.format(new Date());
        return transformDate;
    }

    public static String processBicCode(String bicCode) {
        String processedBicCode = "";
        if (!StringUtil.isEmpty(bicCode)) {
            if (bicCode.length() == 8) {
                processedBicCode = bicCode + BIC_PREFIX;
            } else if (bicCode.length() == 11) {
                processedBicCode = bicCode.substring(0, 8) + "A" + bicCode.substring(8);
            } else {
                throw new SwiftException("BicCode length is invalid.");
            }
        }
        return processedBicCode;
    }


    public static String getRandomNumber(int length) {
        String randomNumber = "";
        for (int i = 0; i < length; i++) {
            randomNumber += "0";
        }
        return randomNumber;
    }

    public static Map<String, String> loadVm(String propertyFilePath) {

        Properties mappingProperties = new OrderedProperties();
        // 使用InPutStream流读取properties文件
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(propertyFilePath));
            mappingProperties.load(bufferedReader);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        Map<String, String> map = new LinkedHashMap<>();
        Set<String> set = mappingProperties.stringPropertyNames();
        // 迭代器遍历
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String key = it.next();
            String value = mappingProperties.getProperty(key);
            map.put(key, value);
        }

        return map;
    }


    public static void makeFileDir(String path) {
        File f = new File(path);
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
    }


    public String formatDate(Date date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(date);
    }

    public String formatDate(Date date, String pattern) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(date);
    }


    public static String getTagBefore(String clsName) {
        String str = clsName;
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        String result = m.replaceAll("").trim();
        return result;
    }

    public static String getSwiftType(String jsonData) {
        Map map = JsonUtil.json2Map(jsonData);
        String msgType = (String) map.get(Constans.MSG_TYPE);
        return msgType;
    }

    public static String getType(String jsonData) {
        Map map = JsonUtil.json2Map(jsonData);
        String msgType = (String) map.get(Constans.TYPE);
        return msgType;
    }

    public static String getSwiftMtType(MtResult mtResult) {
        AbstractMT abstractMT = mtResult.getAbstractMT();
        String msgType = abstractMT.getMessageType();
        SwiftBlock3 block3 = abstractMT.getSwiftMessage().getBlock3();
        if (block3 != null) {
            Map<String, String> tagMap = block3.getTagMap();
            if (tagMap.containsKey("119") && "COV".equals(tagMap.get("119"))) {
                msgType = msgType + "COV";
                mtResult.setMsgType(msgType);
            }
            if (tagMap.containsKey("119") && "STP".equals(tagMap.get("119"))) {
                msgType = msgType + "STP";
                mtResult.setMsgType(msgType);
            }
            if (tagMap.containsKey("119") && "REMIT".equals(tagMap.get("119"))) {
                msgType = msgType + "REMIT";
                mtResult.setMsgType(msgType);
            }

        }
        return msgType;
    }

    public static List<String> strToList(String src, int length) {
        List<String> list = new LinkedList<String>();
        //检查参数是否合法
        if (null == src || src.equals("")) {
            return null;
        }

        if (length <= 0) {
            return null;
        }
        int n = (src.length() + length - 1) / length; //获取整个字符串可以被切割成字符子串的个数
        String[] split = new String[n];
        for (int i = 0; i < n; i++) {
            if (i < (n - 1)) {
                // split[i] = src.substring(i * length, (i + 1) * length);
                list.add(src.substring(i * length, (i + 1) * length));
            } else {
                // split[i] = src.substring(i * length);
                list.add(src.substring(i * length));
            }
        }
        return list;
    }

    public static String strToStanderdStr(String src, int length) {
        StringBuffer stringBuffer = new StringBuffer();
        List<String> list = strToList(src, length);
        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i);
            if (i != (list.size() - 1)) {
                stringBuffer.append(str + Constans.CRLF);
            } else {
                stringBuffer.append(str);
            }
        }
        return stringBuffer.toString();

    }
}
