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

import com.brilliance.mda.runtime.mda.util.Dates;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.mda.runtime.mda.util.Strings;
import com.brilliance.isc.bo.Auzlvl;
import com.brilliance.isc.bo.Bch;
import com.brilliance.isc.bo.Trn;
import com.brilliance.isc.bo.Usr;
import com.brilliance.isc.common.api.bch.service.BchService;
import com.brilliance.isc.common.cbsmod.service.XrtmodService;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.sysmod.SysmodService;
import com.brilliance.isc.common.trnsig.service.TrnsigService;
import com.brilliance.isc.common.trnsig.vo.TrnsigVo;
import com.brilliance.isc.common.util.Utils;
import com.brilliance.isc.mda.dao.AuzlvlMapper;
import com.brilliance.isc.mda.dao.UsrMapper;
import com.brilliance.isc.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

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

@Service
public class TrnsigServiceImpl implements TrnsigService {

    @Autowired
    private SysmodService sysmodService;
    @Autowired
    private XrtmodService xrtmodService;

    @Autowired
    UsrMapper usrMapper;

    @Autowired
    AuzlvlMapper auzlvlMapper;

    @Autowired
    BchService bchService;



    public String sigUsrRelFlg(Trn trn, String user, String iniuser, BigDecimal amt, String fromcur, TrnsigVo trnisg) {
        // Determine maximum release code for user for specified amount
        Bch orgbch=SettleContext.getUserSession().getOrgBch();
        Usr orgUsr=SettleContext.getUserSession().getUsr();
        if( MdaUtils.compareTo(user,trnisg.getUsr().getExtkey()) != 0 ) {
//            Platform.sdbEtyRead(this.getUsr(),user,"EXTKEY");
            trnisg.setUsr(SettleContext.getUserSession().getUsr());
        }
        // If user not found no authorisation
//        if( ctx.getErrorCode() != 0 ) {
//            return " ";
//        }
        String sql=NULLSTR;
        String relGrp = trnisg.getUsr().getRelgrp();
        String relCur = trnisg.getUsr().getRelcur();
        BigDecimal relAmt = trnisg.getUsr().getRelamt();
        BigDecimal relAmt2nd = trnisg.getUsr().getRelamt2nd();
        Auzlvl auzlvl =null;
        Bch bch=bchService.getByBchInr(trn.getBchkeyinr());
        if(sysmodService.isSdhBusiness(trn.getInifrm(),bch.getBranch())){
            //收单行上收复核岗无需校验金额及权限
            return "A";
        }
        Bch selBch=bchService.getByBchInr(trn.getBranchinr());
        // check for UBR record by TRNCOD
        ubrdone:
        while(true) {
            boolean ubrFlg = false;
            sql = Utils.sdbEtyGenSql("auzlvl",String.format("cod = '%s' and (branch = '%s' or branch = '') ",
                    trn.getInifrm(),selBch.getBranch()));
            Auzlvl argLvl= new Auzlvl();
            argLvl.setAuthlevel(orgUsr.getAuthlevel());
            argLvl.setBranch(orgbch.getBranch());
            argLvl.setCode(trn.getInifrm());
            argLvl.setType("1");
            List<Auzlvl> auzlvlList = auzlvlMapper.listByUniqueKey(argLvl);
            if(auzlvlList != null && auzlvlList.size() > 0){
                auzlvl = auzlvlList.get(0);
            }
            if( auzlvl!=null ) {
                trnisg.setAuzlvl(auzlvl);
              //  relGrp = trnisg.getAuzlvl().getRelgrp();
                relCur = trnisg.getAuzlvl().getRelcur();
                relAmt = trnisg.getAuzlvl().getRelamt();
              //  relAmt2nd = trnisg.getAuzlvl().getRelamt2nd();
                ubrFlg = true;
                //add by zt
                //如果查到了交易代码就不用在去查BUSSEC了
                break ; // #######TODO 改写 LABEL与GOTO  ####   goto ubrdone
                //----end------------
            }
            // check for UBR record by BUSSEC
            if( MdaUtils.compareTo(ubrFlg,false) == 0 ) {
                sql = Utils.sdbEtyGenSql("auzlvl",String.format(" TYPE = '%s' and (branch = '%s' or branch = '') ",
                        Strings.mid(trn.getObjtyp(),1,2),selBch.getBranch()));
                Auzlvl argLvl2= new Auzlvl();
                argLvl2.setAuthlevel(orgUsr.getAuthlevel());
                argLvl2.setBranch(orgbch.getBranch());
                argLvl2.setCode(Strings.mid(trn.getObjtyp(),1,2));
                auzlvlList = auzlvlMapper.listByUniqueKey(argLvl2);
               // auzlvlList = auzlvlMapper.selectByBranchAndCodeAndType(orgbch.getBranch(),Strings.mid(trn.getObjtyp(),1,2),"");
                if(auzlvlList != null && auzlvlList.size() > 0){
                    auzlvl = auzlvlList.get(0);
                }
                if( auzlvl !=null ) {
                    trnisg.setAuzlvl(auzlvl);
                    relCur = auzlvl.getRelcur();
                    relAmt = auzlvl.getRelamt();
                }
            }
            break;
        }
        // #######TODO 改写 LABEL与GOTO   ####    label ubrdone
        // specific for PAC ( Clerks have no authorisation to sign)
        if( MdaUtils.compareTo(relGrp,"N") == 0 ) {
            return " ";
        }
        // Compute amount in USR\\RELCUR ( middlerate)
//        BigDecimal checkamt = Dynamic.amtConvTypes( fromcur, amt, "M", relCur, "M", Dates.today() );
        BigDecimal checkamt = xrtmodService.amtConvTypes( fromcur, amt, "M", relCur, "M", Dates.today() );
        // if own transaction, sign only posssible if amount not exceeding 2nd amount
        if( MdaUtils.compareTo(user,iniuser) == 0 ) {
            if( MdaUtils.compareTo(relAmt2nd,0)<=0 ) {
                // if no own amount, user cannot sign own transactions at all
                return " ";
            } else {
                if( MdaUtils.compareTo(checkamt,relAmt2nd)<=0 ) {
                    return "A";
                } else {
                    return "B";
                }
            }
        } else {
            // signature is qualified ( =A) if amount does not exceed USR\\RELAMT amount
            // otherwise signature is unqualified ( =B)
            if("1000".equals(orgbch.getBranch()) && relAmt==null){
                return " ";
            }
            if( MdaUtils.compareTo(checkamt,relAmt)<=0 ) {
                return "A";
            } else {
                return "B";
            }
        }
    }

    public String sigUsrRelFlg(Trn trn) {
        // Determine maximum release code for user for specified amount
        Bch orgbch=SettleContext.getUserSession().getOrgBch();
        Usr orgUsr=SettleContext.getUserSession().getUsr();
        String relGrp = orgUsr.getRelgrp();
        String relCur = orgUsr.getRelcur();
        BigDecimal relAmt = orgUsr.getRelamt();
        BigDecimal relAmt2nd = orgUsr.getRelamt2nd();
        Bch bch=bchService.getByBchInr(trn.getBchkeyinr());
        if(sysmodService.isSdhBusiness(trn.getInifrm(),bch.getBranch())){
            //收单行上收复核岗无需校验金额及权限
            return "A";
        }
        Auzlvl argLvl= new Auzlvl();
        argLvl.setAuthlevel(orgUsr.getAuthlevel());
        argLvl.setBranch(orgbch.getBranch());
        argLvl.setCode(trn.getInifrm());
        argLvl.setType("1");
        List<Auzlvl> auzlvlList = auzlvlMapper.listByUniqueKey(argLvl);
        if(auzlvlList == null || (auzlvlList!=null && auzlvlList.size() == 0)){
            Auzlvl argLvl2 = new Auzlvl();
            argLvl2.setAuthlevel(orgUsr.getAuthlevel());
            argLvl2.setBranch(orgbch.getBranch());
            argLvl2.setCode(Strings.mid(trn.getObjtyp(), 1, 2));
            auzlvlList = auzlvlMapper.listByUniqueKey(argLvl2);
        }
        if (auzlvlList != null && auzlvlList.size() > 0) {
            relCur = auzlvlList.get(0).getRelcur();
            relAmt = auzlvlList.get(0).getRelamt();
        }
        if( MdaUtils.compareTo(relGrp,"N") == 0 ) {
            return " ";
        }
        BigDecimal checkamt = xrtmodService.amtConvTypes(trn.getRelcur(), trn.getRelamt(), "M", relCur, "M", Dates.today() );
        if( MdaUtils.compareTo(orgUsr.getExtkey(),trn.getIniusr()) == 0 ) {
            if( MdaUtils.compareTo(relAmt2nd,0)<=0 ) {
                return " ";
            } else {
                if( MdaUtils.compareTo(checkamt,relAmt2nd)<=0 ) {
                    return "A";
                } else {
                    return "B";
                }
            }
        } else {
            if("1000".equals(orgbch.getBranch()) && relAmt==null){
                return " ";
            }
            if( MdaUtils.compareTo(checkamt,relAmt)<=0 ) {
                return "A";
            } else {
                return "B";
            }
        }
    }

    public int getUseIdx(Trn trn,String argTrnRelFlg) {
        String bchlev= SettleContext.getUserSession().getOrgBch().getLev();
        String relres0 = trn.getRelres0();
        String relreq0 = trn.getRelreq0();
        String relres1 = trn.getRelres1();
        String relreq1 = trn.getRelreq1();
        String relres2 = trn.getRelres2();
        String relreq2 = trn.getRelreq2();
        String relres = trn.getRelres();
        String relreq = trn.getRelreq();
        if (MdaUtils.isEmpty(argTrnRelFlg)) {
            return 0;
        }
        //CENTER RELEASE
        if ("0".equals(bchlev)) {
            if ("A".equals(argTrnRelFlg)) {
                for (int i = 1; i < 4; i++) {
                    if ("N".equals(StringUtils.substring(relres0,i-1, i ))) {
                        if ("A".equals(StringUtils.substring(relreq0,i-1, i))) {
                            return i;
                        }
                    }
                }
            }
            for (int i = 1; i < 4; i++) {
                if ("N".equals(StringUtils.substring(relres0,i-1,i))) {
                    if ("B".equals(StringUtils.substring(relreq0,i-1, i))) {
                        return i;
                    }
                }
            }
        }
        //BRANCH RELEASED
        String c = "";
        if ("-A-B-1-".indexOf(bchlev)>0) {//A 一级分行全辖 B 二级分行全辖 1 一级经办行 2 二级经办行
            if ("A".equals(argTrnRelFlg)) {
                for (int i = 1; i < 4; i++) {
                    if ("N".equals(StringUtils.substring(relres1,i-1, i))) {
                        if ("A".equals(StringUtils.substring(relreq1,i-1, i))) {
                            return i;
                        }
                    }
                }
                for (int i = 1; i < 4; i++) {
                    if ("N".equals(StringUtils.substring(relres2,i-1, i))) {
                        if ("A".equals(StringUtils.substring(relreq2,i-1, i))) {
                            return i;
                        }
                    }
                }
            }
            for (int i = 1; i < 4; i++) {
                if ("N".equals(StringUtils.substring(relres1,i-1, i))) {
                    if ("B".equals(StringUtils.substring(relreq1,i-1, i))) {
                        return i;
                    }
                }
                if ("N".equals(StringUtils.substring(relres2,i-1, i))) {
                    if ("B".equals(StringUtils.substring(relreq2,i-1, i))) {
                        return i;
                    }
                }
            }
        }
        //SUB BRANCH RELEASED
        if ("-B-2-".indexOf(bchlev)>0) {//B 二级支行全辖 1 一级分行
            if ("A".equals(argTrnRelFlg)) {
                for (int i = 1; i < 4; i++) {
                    if ("N".equals(StringUtils.substring(relres2,i-1, i))) {
                        if ("A".equals(StringUtils.substring(relreq2,i-1, i))) {
                            return i;
                        }
                    }
                }
            }
            for (int i = 1; i < 4; i++) {
                if ("N".equals(StringUtils.substring(relres2,i-1, i))) {
                    if ("B".equals(StringUtils.substring(relreq2,i-1, i))) {
                        return i;
                    }
                }
            }
        }
        //NOT NEED HIGH RELEASE
        if ("A".equals(argTrnRelFlg)) {
            for (int i = 1; i < 4; i++) {
                if (" ".equals(StringUtils.substring(relres,i-1, i))) {
                    if ("A".equals(StringUtils.substring(relreq,i-1, i))) {
                        return i;
                    }
                }
            }
        }
        for (int i = 1; i < 4; i++) {
            if (" ".equals(StringUtils.substring(relres,i-1, i))) {
                if ("B".equals(StringUtils.substring(relreq,i-1, i))) {
                    return i;
                }
            }
        }
        return 0;

    }

    public boolean sigUsrConfirm(Trn argTrn, String user, Usr usr) {
        // Determine wether user can enter confirmation
        if (user.equals(usr.getExtkey())) {
            Utils.setFieldValue(usr, "extkey", user);
        }
        // If user not found no authorisation
        String relGrp = usr.getRelgrp();
        // check for UBR record
        String sql = String.format(" TYPE = %s", Strings.mid(argTrn.getObjtyp(), 1, 2));
        Bch bch =bchService.getByBchInr(argTrn.getBranchinr());
        List<Auzlvl> auzlvlList = auzlvlMapper.selectByBranchAndCodeAndType(bch.getBranch(),"",Strings.mid(argTrn.getObjtyp(), 1, 2));
        if (auzlvlList != null && auzlvlList.size() > 0) {
            Auzlvl auzlvl = auzlvlList.get(0);
            //relGrp = auzlvl.getRelgrp();
        }
        // specific for PAC ( Clerks have no authorisation to sign)
//        if ("N".equals(relGrp)) {
//            return false;
//        }
        return true;
    }

}
