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

import com.brilliance.isc.bo.Ntf;
import com.brilliance.isc.bo.Ssn;
import com.brilliance.isc.bo.Usr;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.counter.service.CounterService;
import com.brilliance.isc.common.exception.CommonServiceException;
import com.brilliance.isc.common.ntfmod.service.NtfmodService;
import com.brilliance.isc.mda.dao.NtfMapper;
import com.brilliance.isc.mda.dao.SsnMapper;
import com.brilliance.isc.mda.dao.UsrMapper;
import com.brilliance.mda.runtime.mda.util.Dates;
import com.brilliance.mda.runtime.mda.util.Inis;
import com.brilliance.mda.runtime.mda.util.Strings;
import com.google.common.collect.ImmutableBiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

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

@Service
public class NtfmodServiceImpl implements NtfmodService {

    @Autowired
    private NtfMapper ntfMapper;
    @Autowired
    private SsnMapper ssnMapper;
    @Autowired
    private UsrMapper usrMapper;
    @Autowired
    private CounterService counterService;

    public void ntfSetExp(Ntf ntf) {
        //取得上下文
//        IContext ctx = MdaEnv.getContext();
//        ctx.setErrorCode(NO_ERROR);
        //! Setting of the Expiration date and time of
        //! a notify message.
        //! The implemented basic logic is, that notify messages below
        //! a certain type / prio are set to an expiration time of 1 day.
        //! Session control entries are set to an expiration of 1 hour.
        int expTim = 0;
        switch (ntf.getTyp()) {
            case "1":
                expTim = 0;  // Emergency
                break;
            case "2":
                expTim = 0;  // Alert
                break;
            case "3":
                expTim = 0;  // Critical
                break;
            case "4":
                expTim = 24; // Error
                break;
            case "5":
                expTim = 24; // Warning
                break;
            case "6":
                expTim = 24; // Notice
                break;
            case "7":
                expTim = 24; // Info
                break;
            case "8":
                expTim = 24; // Hint
                break;
            case "9":
                expTim = 24; // Debug
                break;
            case "0":
                expTim = 0;  // No Icon
                break;
            case "C":
                expTim = 1;  // Close/Cancel transaction (LnkReturnToFirst)
                break;
            case "U":
                expTim = 1;  // Update Session status
                break;
            case "X":
                expTim = 1;  // Terminate session (LnkExit)
                break;
            default:
                expTim = 0; // Unknown codes -> no expiry
        }
        if (expTim > 0) {
            ntf.setExpdattim(Dates.dateTimeAdd(ntf.getDattim(), 0, expTim));
        } else {
            ntf.setExpdattim(null);
        }

    }

    public void ntfSendToUsr(String argUsr,String argTyp,String argTxt)
    {
        //取得上下文
//        IContext ctx = MdaEnv.getContext();
//        ctx.setErrorCode(NO_ERROR);
        //! The purpose of this routine is to send a Notify-msg to a user.
        //! Arg1: User-Id
        //! Arg2: Type of notify (Use NtfTypxxxx constants to select the type)
        //! Arg3: Text to be sent
        //! On case of success the routine sets the errorcode to 0.
        // As this routine is called within SysDump, all error`s have to be handled
        // and exported to avoid a recursive call of errorexit.
        // make the text fitting to the textfield in NTF which is 3 lines with 60 characters
        String vargTxt = Strings.convertBlock(argTxt,0,3,60);
        // replace " by ` in order to allow passing to `NtfSendToUsrCust` via `post`
        vargTxt = Strings.convertBlock(vargTxt,21);
        int pos = 0;
        while( Strings.pos(vargTxt,"\"") > 0 )
        {
            pos = Strings.pos(vargTxt,"\"");
            vargTxt = Strings.mid(vargTxt,1,pos - 1) + "'" + Strings.mid(vargTxt,pos + 1);
        }
        //! If `NtfSendToUsrCust(` exist and returns
        //! - with errorcode to 130, the normal notification via NTF will be used
        //! - with errorcode 0, the normal notification via NTF will be skipped
        //! - with any other errorcode, the normal notification via NTF will be used but the message precedeeded by the errorcode/text
        //TODO 实际发送事件信息
//        String cmd = "NtfSendToUsrCust( \"" + argUsr + "\", \"" + argUsr + "\", \"" + vargTxt + "\")";
//        Modules.invokeExpress(this,cmd,-1);
//        if( ctx.getErrorCode() == 0 )
//        {
//            if(1==1) return;
//        }
//        if( ctx.getErrorCode() != 130 )
//        {
//            argTxt = ctx.getErrorMessage() + "\n" + argTxt;
//        }
        // Check whether the passed user is available in any entity
        // $UsrSql = "Select INR from USR " + SdbEtyGenSql( \\SYSMOD\\USR, "where EXTKEY = " + SqlLit( ArgUsr ) )
        // $UsrSql = "Select INR from USR where EXTKEY = " + SqlLit( ArgUsr )
//        ctx.getDaoSession().dbExecuteSQL("Select INR from USR where EXTKEY = ?",argUsr);
//        if( ctx.getErrorCode() > 0 )
//        {
//            ctx.reraise();
//            if(1==1) return;
//        }
//        String inrFlg = "";
//        Argument<String> _inrFlgBox = Argument.box(inrFlg);
//        ctx.getDaoSession().dbFetchFields("INR",_inrFlgBox);
//        inrFlg = _inrFlgBox.value;
//        String usr = NULLSTR;
//        if( ctx.getErrorCode() <= 0 )
//        {
//            usr = argUsr;
//        }
//        else
//        {
//            if( ctx.getErrorCode() != tdOdbcNotFound )
//            {
//                ctx.reraise();
//                if(1==1) return;
//            }
//            else
//            {
//                usr = ctx.absGet(Sysmod.class).getEty().getAdmusr();
//                if( MdaUtils.isEmpty(usr) )
//                {
//                    usr = Inis.getIniStr(AppIniFile,"Defaults","Ety-ADMUSR");
//                }
//            }
//        }
//        ctx.getDaoSession().dbCloseCursor();

        String usrnam = Inis.getIniStr(AppIniFile,"Defaults","Ety-ADMUSR");
        String sql = "Select INR from USR where EXTKEY = '"+argUsr+"'";
        List<Usr> result = usrMapper.dyncRead(ImmutableBiMap.of("sql",sql));
        if(result.size() == 0){
            usrnam = argUsr;
        }
        // Ssn ssn = SettleContext.getUserSession().getSsn();
        Usr usr = SettleContext.getUserSession().getUsr();
        Ntf ntf = new Ntf();
        ntf.setInr(counterService.dbCounterFormat("NTF"));
        ntf.setUsr( usrnam);
        ntf.setSsninr( "");
        ntf.setTyp( argTyp);
        ntf.setTxt( argTxt);
        ntf.setDattim( Dates.now());
        ntf.setIniusr( usr.getExtkey());
        // ntf.setInissninr( ssn.getInr());
        ntfSetExp(ntf);
//        Platform.sdbInsert(ntf);
        ntfMapper.insert(ntf);
    }

    public void ntfSendToSsn(String argSsn, String argTyp, String argTxt) {
        //取得上下文
//        IContext ctx = MdaEnv.getContext();
//        ctx.setErrorCode(NO_ERROR);
        //! The purpose of this routine is to send a Notif-msg to a Session.
        //! Arg1: INR of target-session
        //! Arg2: Type of notify (Use NtfTypxxxx constants to select the type)
        //! Arg3: Text to be sent
        //! On case of success the routine sets the errorcode to 0.
        // check whether a fitting session exists in the session table.
        // No need to use multi-entity logic.
        //# SSN.USR SSN.EXTKEY
        // $UsrSql = "Select USR from SSN where INR = " + SqlLit( ArgSsn )
//        ctx.getDaoSession().dbExecuteSQL("Select USR from SSN where INR = ?",argSsn);
//        String usrFlg = "";
//        Argument<String> _usrFlgBox = Argument.box(usrFlg);
//        // Check whether a session was found.
//        ctx.getDaoSession().dbFetchFields("USR",_usrFlgBox);
//        usrFlg = _usrFlgBox.value;
        String sql = "Select * from SSN where INR = '" + argSsn + "'";
        List<Ssn> result = ssnMapper.dyncRead(ImmutableBiMap.of("sql", sql));
        if (result.size() == 0) {
            throw new CommonServiceException("查询不到登录用户信息！");
        }

        Usr usr = SettleContext.getUserSession().getUsr();
        // Ssn ssn = SettleContext.getUserSession().getSsn();
        Ntf ntf = new Ntf();
        ntf.setInr(counterService.dbCounterFormat("NTF"));
        ntf.setUsr("");
        ntf.setSsninr(argSsn);
        ntf.setTyp(argTyp);
        ntf.setTxt(Strings.convertBlock(argTxt, 0, 3, 60));
        ntf.setDattim(Dates.now());
        ntf.setIniusr(usr.getExtkey());
        // ntf.setInissninr(ssn.getInr());
        ntfSetExp(ntf);
//            Platform.sdbInsert(ntf);
        ntfMapper.insert(ntf);

    }

}
