package com.brilliance.isc.common.docimm.service.impl;


import com.brilliance.isc.bo.Smh;
import com.brilliance.isc.common.context.AppEnv;
import com.brilliance.isc.common.docimm.service.DocimmService;
import com.brilliance.isc.common.docimm.vo.DocimmVo;
import com.brilliance.isc.common.util.Utils;
import com.brilliance.isc.mda.dao.OitMapper;
import com.brilliance.isc.mda.dao.PtaMapper;
import com.brilliance.isc.mda.dao.PtyMapper;
import com.brilliance.mda.runtime.mda.IStream;
import com.brilliance.mda.runtime.mda.impl.Argument;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.mda.runtime.mda.util.Streams;
import com.brilliance.mda.runtime.mda.util.Strings;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

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

@Service("docimmService")
public class DocimmServiceImpl implements DocimmService {

    @Autowired
    private AppEnv appEnv;
    @Resource
    private PtyMapper ptyMapper;
    @Resource
    private PtaMapper ptaMapper;
    @Resource
    private OitMapper oitMapper;

    public String getDocumentFdr(Smh argSMH)
    {
        return  appEnv.getFullName("DATA",appEnv.addNodeToPath(argSMH.getDocpth(),argSMH.getDocfil() + "." + argSMH.getDocfxt()));
    }

    public void splitFileName(String file, Argument<String> dir, Argument<String> fil, Argument<String> fxt) {
        // splits filename into directory, basename and extension
//        int fillen = Systems.getAttribute(docimmVo.getSmh(),"docfil",tdAttrLength);
//        int fxtlen = Systems.getAttribute(docimmVo.getSmh(),"docfxt",tdAttrLength);
        String filename = Utils.getFileWithoutPrefix(file);
        dir.value = "";
        int pos = 0;
        int pos1 = 0;
        do
        {
            pos = Strings.pos(filename,"\\");
            pos1 = Strings.pos(filename,"/");
            if( pos1 > 0 && ( pos1 < pos || pos == 0 ) )
            {
                pos = pos1;
            }
            if( pos > 0 )
            {
                dir.value = dir.value + Strings.mid(filename,1,pos);
                filename = Strings.mid(filename,pos + 1,Strings.len(filename));
            }
        }
        while (!( pos == 0 ));
        String datapath = Strings.getAbsPath("DATA");
        if( MdaUtils.compareTo(Strings.toUpper(Strings.mid(dir.value,1,Strings.len(datapath))),Strings.toUpper(datapath)) == 0 )
        { // strip leading DataPath (including "\\\\")
            dir.value = Strings.mid(dir.value,Strings.len(datapath) + 1,Strings.len(dir.value));
        }
        if( MdaUtils.compareTo(Strings.mid(dir.value,1,1),"\\") == 0 )
        { // strip leading "\\\\"
            dir.value = Strings.mid(dir.value,2,Strings.len(dir.value) - 1);
        }
        dir.value = Strings.trim(dir.value);
        if( MdaUtils.compareTo(Strings.mid(dir.value,Strings.len(dir.value),1),"\\") == 0 )
        { // strip trailing \\
            dir.value = Strings.mid(dir.value,1,Strings.len(dir.value) - 1);
        }
        if( MdaUtils.compareTo(Strings.mid(dir.value,Strings.len(dir.value),1),"/") == 0 )
        { // strip trailing /
            dir.value = Strings.mid(dir.value,1,Strings.len(dir.value) - 1);
        }
        pos = Strings.pos(filename,".");
        int p1 = pos;
        while( p1 > 0 )
        {
            p1 = Strings.pos(Strings.mid(filename,pos + 1),".");
            if( p1 > 0 )
            {
                pos = pos + p1;
            }
        }
        String vfil = NULLSTR;
        String vfxt = NULLSTR;
        if( pos > 0 )
        {
            vfil = Strings.mid(filename,1,pos - 1);
            vfxt = Strings.mid(filename,pos + 1);
        }
        else
        {
            vfil = filename;
            vfxt = "";
        }
        fil.value = vfil;
        fxt.value = vfxt;
//        if( Strings.len(vfil) > fillen )
//        {
//            ctx.setErrorCode(521,Strings.formatText("File name too long (> $1 characters)",fillen));
//            return;
//        }
//        if( Strings.len(vfxt) > fxtlen )
//        {
//            ctx.setErrorCode(522,Strings.formatText("Extension too long (> $1 characters)",fxtlen));
//            return;
//        }
//        if( Strings.len(vfil) + Strings.len(vfxt) > fillen )
//        {
//            ctx.setErrorCode(523,Strings.formatText("File + Extension too long (> $1 characters)",fillen));
//            return;
//        }
    }


    public int checkMsgLength(String argMt, String argCorTyp, IStream argMsgTxt)
    {
//        //!checks, if the lenght of the ready created message is correct, according to the entry in [MAXLEN] section in tagsup.ini
//        // if no entry for message defined, maxlen is 10000
//        setTagSupFile( argCorTyp );
//        // errorcode 503 means, for this cortyp no tagsup defined - thus no electronic message and length has not to be checked
//        if( ctx.getErrorCode() > 0 )
//        {
//            if( ctx.getErrorCode() != 503 )
//            {
//                ctx.reraise();
//            }
//            else
//            {
//                ctx.setErrorCode(0,"");
//            }
//            if(1==1) return;
//        }
//        IStream msgstream = new StreamImpl();
//        Streams.streamSet(msgstream,argMsgTxt);
//        int total = splitMsg( msgstream ); // if message was split before (e.g. in outgoing services) SplitMsg will return 1
//        if( ctx.getErrorCode() > 0 )
//        {
//            ctx.reraise();
//            if(1==1) return;
//        }
//        if( ctx.getErrorCode() == -500 )
//        {
//            total = 1;
//        }
//        String ctlline = NULLSTR;
//        int startidx = 0;
//        int lastidx = 0;
//        String mt = NULLSTR;
//        IStream msg = new StreamImpl();
//        for(int  msgidx = 1;msgidx <= total;msgidx++)
//        {
//            ctlline = Strings.getLine(this.getMsgctl(),msgidx);
//            startidx = Strings.parseInt(Strings.mid(ctlline,1,8));
//            lastidx = Strings.parseInt(Strings.mid(ctlline,9,8));
//            mt = getNewMT( argMt, msgidx );
//            // check allowed length of message
//            if( total > 1 )
//            {
//                Streams.streamClear(msg);
//                for(int  linidx = startidx;linidx <= lastidx;linidx++)
//                {
//                    //dngdev.002545: Get single message from splitted $Msgstream insted of Raw msgtxt
//                    Streams.streamInsert(msg,0,Strings.getLine(msgstream,linidx));
//                }
//                checkMsgLengthInternal( mt, argCorTyp, msg );
//            }
//            else
//            {
//                checkMsgLengthInternal( mt, argCorTyp, msgstream );
//            }
//            if( ctx.getErrorCode() > 0 )
//            {
//                ctx.reraise();
//                 return;
//            }
//        }
        return 1;

    }

    @Override
    public void make999fromSwt(IStream doctxt, String mt, String cortyp) {

    }

    @Override
    public void makeStreamFromSwt(IStream doctxt) {

    }

    @Override
    public boolean isCORTYPTechnical(String argCORTYP, DocimmVo docimmVo) {
        if( Streams.streamSearch(docimmVo.getCortyptec(),argCORTYP) > 0 )
        {
            return  true;
        }
        else
        {
            return  false;
        }
    }

    /**
     * 读取通用配置，通过标签名获取描述
     * @param tag 标签名
     * @return    标签描述
     * @throws Exception
     */
    @Override
    public String sWTGetFIOTag(String tag) {
        //原TD逻辑获取 ini文件配置 tagsup.ini
        //新逻辑直接读取配置文件 swttag
        String key = tag;
        String taglabel = "";

        Properties properties = null;
        try {
            properties = PropertiesLoaderUtils.loadAllProperties("business/bgservice/swttag.properties");
        } catch (IOException e) {
            return null;
        }
        taglabel = properties.getProperty(key);
        if (StringUtils.isEmpty(taglabel)) {
            //剔除 seq 后缀
            String sequence = Strings.mid(tag, Strings.len(tag) - 1);
            if (".B".equals(sequence) || ".C".equals(sequence)) {
                key = Strings.mid(tag, 1, Strings.len(tag) - 2);
                taglabel = properties.getProperty(key);
            }
        }

        return taglabel;
    }

    /**
     * 获取 ptainr TODO  待 check
     * 原国结 DOCIMM.SWTGetAdrFromBIC
     */
    @Override
    public String swtGetAdrFromBIC(String iobic) {
        String ptainr = "";
        if (StringUtils.isBlank(iobic)) {
            return ptainr;
        }
        String biccod = iobic;

        //截取bic
        if (iobic.length() == 12) {
            biccod = StringUtils.join(Strings.mid(iobic,1,8), Strings.mid(iobic,10,3));
        } else if (iobic.length() == 9) {
            biccod = Strings.mid(iobic,1,8);
        }

        //获取ptainr
        ptainr = swtReadAdrByBICinternal(biccod);

        if (StringUtils.isBlank(ptainr)) {
            String searchbic = Strings.mid(biccod,1,8);
            ptainr = swtReadAdrByBICinternal(searchbic);
            if (StringUtils.isBlank(ptainr)) {
                searchbic = StringUtils.join(Strings.mid(biccod,1,8), "XXX");
                ptainr = swtReadAdrByBICinternal(searchbic);
            }
        }

        return ptainr;
    }

    /**
     * 通过 bic 获取 ptainr
     * 原国结 DOCIMM.SWTReadAdrByBICinternal
     */
    @Override
    public String swtReadAdrByBICinternal(String biccod) {
        String ptainr = "";
        String argbic = biccod;
        if (StringUtils.isBlank(biccod)) {
            return ptainr;
        }
        //有些报文只传8位bic代码，刘文清需求，将类报文匹配为总行
        if (biccod.length() == 8) {
            argbic = StringUtils.join(biccod, "XXX");
        }
        //todo ！！！！！！！！！！复杂逻辑简单化，只查询pta，不处理 adr  --待 check
        //光大存在同一BIC 多个pty，并且有停用的情况
        String oitptyinr = "";
        List<String> ptyinrlst = ptyMapper.selectInrListByExtkey(argbic.toUpperCase());
        for (String ptyinr : ptyinrlst) {
            oitptyinr = ptyinr;
            int oilcnt = oitMapper.selectCountByPtyinr(oitptyinr);
            if (oilcnt == 0) {
                ptainr = ptaMapper.selectInrByPtyinr(oitptyinr);
                if (!StringUtils.isBlank(ptainr)) {
                    break;
                }
            }
        }

        //都停用或pty没记录，直接用ptyinr查询
        if (StringUtils.isBlank(ptainr) && !StringUtils.isBlank(oitptyinr)) {
            ptainr = ptaMapper.selectInrByPtyinr(oitptyinr);
        }

        return ptainr;

    }


}
