package com.brilliance.isc.common.context;

import com.brilliance.isc.bo.*;
import com.brilliance.isc.common.api.bch.service.BchService;
import com.brilliance.isc.common.cache.atpbch.AtpBchCacheService;
import com.brilliance.isc.common.cache.pta.PtaCacheService;
import com.brilliance.isc.common.component.DyncDaoService;
import com.brilliance.isc.common.component.PtsptaToolComponent;
import com.brilliance.isc.common.exception.CommonServiceException;
import com.brilliance.isc.common.transaction.TransactionService;
import com.brilliance.isc.common.transaction.vo.BaseTransactionVo;
import com.brilliance.isc.common.user.service.UserService;
import com.brilliance.isc.common.util.StringUtils;
import com.brilliance.isc.common.util.Utils;
import com.brilliance.isc.common.vo.BizInfoVo;
import com.brilliance.isc.common.vo.PtsptaVo;
import com.brilliance.isc.mda.dao.*;
import com.brilliance.isc.vo.manager.SessionUserVo;
import com.brilliance.isc.vo.manager.UserVo;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

@Component
public class SettleContext {

//    private final String ETY_EXTKEY = "CEB";
//    private final String ETG_EXTKEY = "CEBGRP";

    private final static List<String> US_LOCALE_LIST = Arrays.asList("LE", "LI", "BE", "BR");

//    private Ety ety;
//    private Etg etg;

    @Autowired
    private EtyMapper etyMapper;

    @Autowired
    private EtgMapper etgMapper;

    @Autowired
    private AtpMapper atpMapper;

    @Autowired
    private PtaCacheService ptaCacheService;

    @Autowired
    private PtsptaToolComponent ptsptaToolComponent;
    @Autowired
    private SptMapper sptMapper;

    @Resource
    private UserService userService;

    @Resource
    private BchService bchService;

    @Resource
    private AtpbchMapper atpbchMapper;

    @Autowired
    private DyncDaoService dyncDaoService;

    @Autowired
    private AtpBchCacheService atpBchCacheService;

//    @PostConstruct
//    public void loadEtyAndEtg() {
//        ety = etyMapper.getEtyByExtkey(ETY_EXTKEY);
//        etg = etgMapper.getEtgByExtkey(ETG_EXTKEY);
//    }

    private static ThreadLocal<SettleSession> userSessionThreadLocal = new ThreadLocal<>();

    private static ThreadLocal<SessionUserVo> sessionUserVoThreadLocal = new ThreadLocal<>();


    private static ThreadLocal<Integer> TRANS_STA = ThreadLocal.withInitial(() -> 0);

    public static int getTransSta() {
        return TRANS_STA.get();
    }

    public static void setTransSta(int status) {
        TRANS_STA.set(status);
    }

    public static void setInitTransSta() {
        setTransSta(0);
    }

    public static void setHoldTransSta() {
        setTransSta(1);
    }

    public static void setSavTransSta() {
        setTransSta(2);
    }

    public static void setViewDocTransSta() {
        setTransSta(3);
    }

    public static void setViewTextTransSta() {
        setTransSta(4);
    }


    public static void setCheckTransSta() {
        setTransSta(4);
    }

    public static boolean isInitTransSta() {
        return getTransSta() == 0;
    }

    public static boolean isPedTransSta() {
        return getTransSta() == 1;
    }

    public static boolean isSavTransSta() {
        return getTransSta() == 2;
    }

    public static boolean isViewDocTransSta() {
        return getTransSta() == 3;
    }

    public static boolean isViewTextTransSta() {
        return getTransSta() == 4;
    }


    public static void setUserSession(SettleSession userSession) {
        userSessionThreadLocal.set(userSession);
    }

    public static void removeUserSession() {
        userSessionThreadLocal.remove();
        TRANS_STA.remove();
    }

    public static SettleSession getUserSession() {
        return userSessionThreadLocal.get();
    }

    public static void setSessionUserVo(SessionUserVo sessionUserVo) {
        sessionUserVoThreadLocal.set(sessionUserVo);
    }

    public static void removeSessionUserVo() {
        sessionUserVoThreadLocal.remove();
    }

    public static SessionUserVo getSessionUserVo() {
        return sessionUserVoThreadLocal.get();
    }

    // 后台服务使用改方法，用于初始化 SessionUserVo
    public static void setSessionUserVo(String logName, String ownOrgDepartmentNumber) {
        SessionUserVo sessionUserVo = new SessionUserVo();
        sessionUserVo.setLogName(logName);
        sessionUserVo.setOwnOrgDepartmentNumber(ownOrgDepartmentNumber);
        setSessionUserVo(sessionUserVo);
    }

    public static Etg getUserEtg() {
        return getUserSession().getEtg();
    }

    public static Ety getUserEty() {
        return getUserSession().getEty();
    }

    public static PtsptaVo getOwnPts() {
        if (getUserSession().getOwnpts() != null) {
            return getUserSession().getOwnpts();
        }
        //重新加载位置进行同步控制
        synchronized (SettleContext.class) {
            //double check
            if (getUserSession().getOwnpts() != null) {
                return getUserSession().getOwnpts();
            }
            PtsptaVo ptsptaVo = SpringEnvContext.getBean(SettleContext.class).loadOwnPts();
            getUserSession().setOwnpts(ptsptaVo);
            return ptsptaVo;
        }
    }

    public static String getTransName() {
        return getUserSession() == null ? "" : getUserSession().getTransName();
    }

    public static String getDirectTransName() {
        String directTransName = getUserSession() == null ? "" : getUserSession().getDirectTransName();
        if (StringUtils.isEmpty(directTransName)) {
            directTransName = getTransName();
        }
        return directTransName;
    }

    public void simpleLoadSettleSession() {
        loadSettleSession("", "", "");
    }

    public void loadSettleSession(SettleSession settleSession) {
        setUserSession(settleSession);
    }

    public void loadSettleSession(String transName, String logName, BizInfoVo bizInfoVo, List<PtsptaVo> ptsList) {
        SettleSession settleSession = new SettleSession();
        settleSession.setTransName(transName.toUpperCase());
        loadSettleSessionInfo(logName, bizInfoVo, ptsList, settleSession);
        setUserSession(settleSession);
        setDirectTransName(settleSession);
    }

    public void loadSettleSession(String transName, String logName, BizInfoVo bizInfoVo, List<PtsptaVo> ptsList, String sptinr) {
        SettleSession settleSession = new SettleSession();
        settleSession.setTransName(transName.toUpperCase());
        loadSettleSessionInfo(logName, bizInfoVo, ptsList, settleSession);
        setUserSession(settleSession);
        loadSpt(settleSession, sptinr);
        setDirectTransName(settleSession);
    }

    private void loadSettleSessionInfo(String logName, BizInfoVo bizInfoVo, List<PtsptaVo> ptsList, SettleSession settleSession) {
        SessionUserVo sessionUserVo = getSessionUserVo();
        if (sessionUserVo == null) {
            throw new CommonServiceException("未登录");
        }
        UserVo userVo = userService.getUserByLogName(sessionUserVo.getLogName());
        if (userVo == null) {
            throw new CommonServiceException("找不到 " + sessionUserVo.getLogName() + " 用户信息!");
        }
//        userVo.setEty(userVo.getEtyextkey());

        // 填充用户信息
        settleSession.setUserVo(userVo);
        Usr usr = getUsr(userVo);
        if (StringUtils.isEmpty(usr.getExtkey())) {
            if (userVo.getLogName().length() > 8) {
                usr.setExtkey(userVo.getLogName().substring(0, 8));
            } else {
                usr.setExtkey(userVo.getLogName());
            }
        }
        if (StringUtils.isEmpty(usr.getNam())) {
            usr.setNam(userVo.getNam());
        }
        settleSession.setUsr(usr);

        // 填充用户当前选择的归属机构
//        Bch orgBch = userService.getOrgBch();
        Bch orgBch = bchService.getByBranch(sessionUserVo.getOwnOrgDepartmentNumber());
        settleSession.setOrgBch(orgBch);


        Atp atp = atpMapper.getAtpByCod(settleSession.getTransName());
        settleSession.setAtp(atp);

        Ety ety = etyMapper.getEtyByExtkey(usr.getEtyextkey());
        Etg etg = etgMapper.getEtgByExtkey(ety.getEtg());

        settleSession.setEty(ety);
        settleSession.setEtg(etg);


        //如果wrkbchinr有值，则读取wrkbch，并读取对应的记账机构
        String wrkbchinr = bizInfoVo == null ? "" : bizInfoVo.getBranchInr();
        if (!MdaUtils.isEmpty(wrkbchinr)) {
            Bch bch = new Bch();
            bch.setInr(wrkbchinr);
//            bch = bchMapper.selectByPrimaryKey(bch);
            bch = bchService.selectByPrimaryKey(bch);
            settleSession.setWrkbch(bch);
            String branch = bch.getBranch();
            //自贸区业务，当前记账机构就是自贸区
            if (orgBch != null && "X".equalsIgnoreCase(orgBch.getZmqflg())) {
                branch = orgBch.getBranch();
            }
            Bch accBch = bchService.getDirectAccBch(branch);
            settleSession.setBch(accBch);
        } else {
            PtsptaVo ptsptaVo = getWrkbchPtspta(bizInfoVo, ptsList);
            if (ptsptaVo != null) {
                Pta pta = ptaCacheService.getPtaByInr(ptsptaVo.getPtainr());
                Bch wrkbch = new Bch();
                wrkbch.setInr(pta.getBranchinr());
//                wrkbch = bchMapper.selectByPrimaryKey(wrkbch);
                wrkbch = bchService.selectByPrimaryKey(wrkbch);
                settleSession.setWrkbch(wrkbch);
                if (wrkbch != null) {
                    //如果wrkbchinr有值，则读取wrkbch，并读取对应的记账机构
                    String branch = wrkbch.getBranch();
                    //自贸区业务，当前记账机构就是自贸区
                    if (orgBch != null && "X".equalsIgnoreCase(orgBch.getZmqflg())) {
                        branch = orgBch.getBranch();
                    }
                    Bch accBch = bchService.getDirectAccBch(branch);
                    settleSession.setBch(accBch);
                }
            }
            if (settleSession.getBch() == null) {
                // 填充当前用户选择的记账机构，有默认取默认值，没有默认的取记账机构列表第一条,可能为空
                Bch accBch = bchService.getDirectAccBch(sessionUserVo.getOwnOrgDepartmentNumber());
                settleSession.setBch(accBch);
            }
            String hndtyp = Utils.getFieldValue(bizInfoVo, "hndtyp");
            String segtyp = Utils.getFieldValue(bizInfoVo, "segtyp");
            String gartyp = Utils.getFieldValue(bizInfoVo, "gartyp");
            if ("OT".equals(hndtyp) && ("02".equals(segtyp) || "F".equalsIgnoreCase(gartyp))) {
                //海关保函转开模式的wrkbch应该取当前记账机构
                settleSession.setWrkbch(settleSession.getBch());
            }
            //BPTOPN二级市场福费廷放款 FIA选择bank，归属机构应该取当前记账机构
            if ("BPTOPN".equals(settleSession.getTransName())) {
                String fortyp = Utils.getFieldValue(bizInfoVo, "fortyp", "");
                if ("2".equals(fortyp)) {
                    Bch wrkbch = settleSession.getWrkbch();
                    if (wrkbch != null && "1000".equals(wrkbch.getBranch())) {
                        settleSession.setWrkbch(settleSession.getBch());
                    }
                }
            }
        }
        //HLJ matbut.getWrkBranch
        //进交易时业务所属行默认为业务经办行
        if (Objects.nonNull(settleSession.getBch()) &&
                (Objects.isNull(settleSession.getWrkbch()) || StringUtils.isEmpty(settleSession.getWrkbch().getInr()))
        ) {
            Bch wrkbch = MdaUtils.deepClone(settleSession.getBch());
            settleSession.setWrkbch(wrkbch);
        }
        //20240131 满足海口自贸区上收到总行的业务
        setAccBch4Zmq(settleSession, bizInfoVo, ptsList);

        Bch bch = settleSession.getBch();
        String inifrm = settleSession.getTransName();
        String branch = "";
        if (bch != null) {
            branch = bch.getBranch();
        }
        Atpbch atpbch = atpbchMapper.selectByBranchAndInifrm(branch, inifrm);
        if (atpbch != null && Objects.equals(atpbch.getNegflg(), "X")) {
            settleSession.setSdhTransaction(true);
        } else {
            settleSession.setSdhTransaction(false);
        }
        //设置经办机构
        setHandleBch(settleSession);
    }

    //请使用loadSettleSession(String transName, String wrkbchinr, String bchinr)
    @Deprecated
    public void loadSettleSession(String transName, String logName, String branchInr, List<PtsptaVo> ptsList) {
        SettleSession settleSession = new SettleSession();
        settleSession.setTransName(transName.toUpperCase());
        loadSettleSessionInfo(logName, branchInr, ptsList, settleSession);
        setUserSession(settleSession);
    }

    //请使用loadSettleSession(String transName, String wrkbchinr, String bchinr, String sptinr)
    @Deprecated
    public void loadSettleSession(String transName, String logName, String branchInr, List<PtsptaVo> ptsList, String sptinr) {
        SettleSession settleSession = new SettleSession();
        settleSession.setTransName(transName.toUpperCase());
        loadSettleSessionInfo(logName, branchInr, ptsList, settleSession);
        setUserSession(settleSession);
        loadSpt(settleSession, sptinr);
    }

    @Deprecated
    private void loadSettleSessionInfo(String logName, String wrkbchinr, List<PtsptaVo> ptsList, SettleSession settleSession) {
        SessionUserVo sessionUserVo = getSessionUserVo();
        if (sessionUserVo == null) {
            throw new CommonServiceException("未登录");
        }
        UserVo userVo = userService.getUserByLogName(sessionUserVo.getLogName());
        if (userVo == null) {
            throw new CommonServiceException("找不到 " + sessionUserVo.getLogName() + " 用户信息!");
        }
//        userVo.setEty(ETY_EXTKEY);

        // 填充用户信息
        settleSession.setUserVo(userVo);
        Usr usr = getUsr(userVo);
        if (StringUtils.isEmpty(usr.getExtkey())) {
            if (userVo.getLogName().length() > 8) {
                usr.setExtkey(userVo.getLogName().substring(0, 8));
            } else {
                usr.setExtkey(userVo.getLogName());
            }
        }
        if (StringUtils.isEmpty(usr.getNam())) {
            usr.setNam(userVo.getNam());
        }
        settleSession.setUsr(usr);

        // 填充用户当前选择的归属机构
//        Bch orgBch = userService.getOrgBch();
        Bch orgBch = bchService.getByBranch(sessionUserVo.getOwnOrgDepartmentNumber());
        settleSession.setOrgBch(orgBch);


        Atp atp = atpMapper.getAtpByCod(settleSession.getTransName());
        settleSession.setAtp(atp);

        Ety ety = etyMapper.getEtyByExtkey(usr.getEtyextkey());
        Etg etg = etgMapper.getEtgByExtkey(ety.getEtg());
        settleSession.setEty(ety);
        settleSession.setEtg(etg);


        //如果wrkbchinr有值，则读取wrkbch，并读取对应的记账机构
        if (!MdaUtils.isEmpty(wrkbchinr)) {
            Bch bch = new Bch();
            bch.setInr(wrkbchinr);
            bch = bchService.selectByPrimaryKey(bch);
            settleSession.setWrkbch(bch);
            String branch = bch.getBranch();
            //自贸区业务，当前记账机构就是自贸区
            if (orgBch != null && "X".equalsIgnoreCase(orgBch.getZmqflg())) {
                branch = orgBch.getBranch();
            }
            Bch accBch = bchService.getDirectAccBch(branch);
            settleSession.setBch(accBch);
        } else {
            // 填充当前用户选择的记账机构，有默认取默认值，没有默认的取记账机构列表第一条,可能为空
            Bch accBch = bchService.getDirectAccBch(sessionUserVo.getOwnOrgDepartmentNumber());
            settleSession.setBch(accBch);
        }
        //20240131 满足海口自贸区上收到总行的业务
        setAccBch4Zmq(settleSession, null, ptsList);

        Bch bch = settleSession.getBch();
        String inifrm = settleSession.getTransName();
        String branch = "";
        if (bch != null) {
            branch = bch.getBranch();
        }
        Atpbch atpbch = atpbchMapper.selectByBranchAndInifrm(branch, inifrm);
        if (atpbch != null && Objects.equals(atpbch.getNegflg(), "X")) {
            settleSession.setSdhTransaction(true);
        } else {
            settleSession.setSdhTransaction(false);
        }
        //设置经办机构
        setHandleBch(settleSession);
    }

    private void loadSettleSessionInfo(String wrkbchinr, String bchinr, SettleSession settleSession) {
        SessionUserVo sessionUserVo = getSessionUserVo();
        if (sessionUserVo == null) {
            throw new CommonServiceException("未登录");
        }
        UserVo userVo = userService.getUserByLogName(sessionUserVo.getLogName());
        if (userVo == null) {
            throw new CommonServiceException("找不到 " + sessionUserVo.getLogName() + " 用户信息!");
        }
//        userVo.setEty(ETY_EXTKEY);

        // 填充用户信息
        settleSession.setUserVo(userVo);
        Usr usr = getUsr(userVo);
        if (StringUtils.isEmpty(usr.getExtkey())) {
            if (userVo.getLogName().length() > 8) {
                usr.setExtkey(userVo.getLogName().substring(0, 8));
            } else {
                usr.setExtkey(userVo.getLogName());
            }
        }
        if (StringUtils.isEmpty(usr.getNam())) {
            usr.setNam(userVo.getNam());
        }
        settleSession.setUsr(usr);

        // 填充用户当前选择的归属机构
//        Bch orgBch = userService.getOrgBch();
        Bch orgBch = bchService.getByBranch(sessionUserVo.getOwnOrgDepartmentNumber());
        settleSession.setOrgBch(orgBch);


        Atp atp = atpMapper.getAtpByCod(settleSession.getTransName());
        settleSession.setAtp(atp);

        Ety ety = etyMapper.getEtyByExtkey(usr.getEtyextkey());
        Etg etg = etgMapper.getEtgByExtkey(ety.getEtg());
        settleSession.setEty(ety);
        settleSession.setEtg(etg);


        //如果wrkbchinr有值，则读取wrkbch，并读取对应的记账机构
        if (!MdaUtils.isEmpty(wrkbchinr)) {
            Bch bch = new Bch();
            bch.setInr(wrkbchinr);
            bch = bchService.selectByPrimaryKey(bch);
            settleSession.setWrkbch(bch);
            Bch accBch = null;
            if (StringUtils.isNotEmpty(bchinr)) {
                accBch = bchService.getByBchInr(bchinr);
            } else {
                accBch = bchService.getDirectAccBch(bch.getBranch());
            }
            settleSession.setBch(accBch);
        } else {
            // 填充当前用户选择的记账机构，有默认取默认值，没有默认的取记账机构列表第一条,可能为空
            Bch accBch = bchService.getDirectAccBch(sessionUserVo.getOwnOrgDepartmentNumber());
            settleSession.setBch(accBch);
        }

        Bch bch = settleSession.getBch();
        String inifrm = settleSession.getTransName();
        String branch = "";
        if (bch != null) {
            branch = bch.getBranch();
        }
        Atpbch atpbch = atpbchMapper.selectByBranchAndInifrm(branch, inifrm);
        if (atpbch != null && Objects.equals(atpbch.getNegflg(), "X")) {
            settleSession.setSdhTransaction(true);
        } else {
            settleSession.setSdhTransaction(false);
        }
        //设置经办机构
        setHandleBch(settleSession);
    }

    /**
     * 加载归属机构 经办机构 登录机构
     */
    public void loadSettleSession(String transName, String wrkbchinr, String bchinr) {
        SettleSession settleSession = new SettleSession();
        settleSession.setTransName(transName.toUpperCase());
        loadSettleSessionInfo(wrkbchinr, bchinr, settleSession);
        setUserSession(settleSession);
        setDirectTransName(settleSession);
    }

    /**
     * 加载归属机构 经办机构 登录机构 来报数据
     */
    public void loadSettleSession(String transName, String wrkbchinr, String bchinr, String sptinr) {
        SettleSession settleSession = new SettleSession();
        settleSession.setTransName(transName.toUpperCase());
        loadSettleSessionInfo(wrkbchinr, bchinr, settleSession);
        setUserSession(settleSession);
        loadSpt(settleSession, sptinr);
        setDirectTransName(settleSession);
    }

    /**
     * 查询当前柜面所在机构信息
     *
     * @return 当前柜员机构信息ptspta
     */
    public PtsptaVo loadOwnPts() {
        String ptyExtkey = SettleContext.getUserSession().getBch().getSwfcod();
        Pta pta = ptaCacheService.selectByPtyextkeyAndUsg(ptyExtkey, "MAA");
        //Pta pta = ptaMapper.selectByPtyExtkey(ptyExtkey);
        if (pta != null) {
            return ptsptaToolComponent.getPtsptaFromPtaINR(pta.getInr());
        }
        return null;
    }

    public void loadSpt(SettleSession settleSession, String sptInr) {
        //如果有值,表示业务数据是从经办夹过来的
        Spt spt = sptMapper.getSptByInr(sptInr);
        settleSession.setSpt(spt);
    }

    private Usr getUsr(UserVo userVo) {
        Usr usr = new Usr();
        usr.setInr(userVo.getInr());
        usr.setExtkey(userVo.getExtkey());
        usr.setNam(userVo.getNam());
        usr.setLgiflg(userVo.getLgiflg());
        usr.setSsnbegdattim(userVo.getSsnbegdattim());
        usr.setSsninr(userVo.getSsninr());
        usr.setVer(userVo.getVer());
        usr.setPri(userVo.getPri());
        usr.setEty(userVo.getEty());
        usr.setUsg(userVo.getUsg());
        usr.setLstdiadat(userVo.getLstdiadat());
        usr.setRelcur(userVo.getRelcur());
        usr.setRelamt(userVo.getRelamt());
        usr.setRelamt2nd(userVo.getRelamt2nd());
        usr.setRelgrp(userVo.getRelgrp());
        usr.setTel(userVo.getTel());
        usr.setFax(userVo.getFax());
        usr.setEml(userVo.getEml());
        usr.setLetoenr(userVo.getLetoenr());
        usr.setQuepow(userVo.getQuepow());
        usr.setEtyextkey(userVo.getEtyextkey());
        usr.setOenr(userVo.getOenr());
        usr.setEtaextkey(userVo.getEtaextkey());
        usr.setResusrflg(userVo.getResusrflg());
        usr.setSecsta(userVo.getSecsta());
        usr.setUserdetailsid(userVo.getUserdetailsid());
        usr.setAuthlevel(userVo.getAuthlevel());
        usr.setAuthority(userVo.getAuthority());
        return usr;
    }

    /**
     * 找到交易的wrkbch相关的Ptspta
     * 代码出处 Mtabut.getWrkBranch
     *
     * @param bizInfoVo
     * @param ptsList
     * @return
     */
    private PtsptaVo getWrkbchPtspta(BizInfoVo bizInfoVo, List<PtsptaVo> ptsList) {
        if (bizInfoVo == null || ptsList == null) {
            return null;
        }
        String objtyp = bizInfoVo.getObjtyp();
        if (StringUtils.isEmpty(objtyp)) {
            return null;
        }
        String role = "";
        switch (objtyp.substring(0, 2)) {
            case "LI":
            case "BR":
            case "FX":
                role = "APL";
                break;
            case "FT":
                role = "TRO";
                break;
            case "LE":
            case "BE":
                role = "BEN";
                break;
            case "DI":
            case "BD":
                role = "APL";
                break;
            case "DE":
            case "BF":
                role = "BEN";
                break;
            case "GI":
                String hndtypG = Utils.getFieldValue(bizInfoVo, "hndtyp");
                String segtypG = Utils.getFieldValue(bizInfoVo, "segtyp");
                if ("OT".equals(hndtypG) && "02".equals(segtypG)) {
                    //海关保函转开模式的wrkbch应该取当前记账机构
                    return null;
                }
                if (StringUtils.isNotEmpty(hndtypG) && ("OT".equals(hndtypG) || hndtypG.startsWith("F"))) {
                    role = "BEN";
                } else {
                    if (ptsptaToolComponent.ptsIsRolSet(ptsList, "CTR")) {
                        role = "CTR";
                    } else {
                        role = "APL";
                    }
                }
                break;
            case "GC":
            case "NI":
            case "NC":
                String hndtyp = Utils.getFieldValue(bizInfoVo, "hndtyp");
                String segtyp = Utils.getFieldValue(bizInfoVo, "segtyp");
                if ("OT".equals(hndtyp) && "02".equals(segtyp)) {
                    //海关保函转开模式的wrkbch应该取当前记账机构
                    return null;
                }
                if (StringUtils.isNotEmpty(hndtyp) && ("OT".equals(hndtyp) || hndtyp.startsWith("F"))) {
                    role = "BEN";
                } else {
                    role = "APL";
                }
                break;
            case "BO":
                role = "DRR";
                break;
            case "BC":
                role = "DRE";
                break;
            case "CC":
                role = "PRE";
                break;
            case "CP":
                String paytyp = Utils.getFieldValue(bizInfoVo, "paytyp");
                if (MdaUtils.compareTo(paytyp, "O") == 0) {
                    role = "ORC";
                }
                if (MdaUtils.compareTo(paytyp, "I") == 0) {
                    role = "PYE";
                }
                break;
            case "MC":
                role = "ADE";
                break;
            case "TR":
                role = "FIP";
                break;
            case "BP":
                role = "FIA";
                break;
            case "LT":
                role = "BE1";
                break;
            case "BT":
                role = "BE1";
                break;
            case "FI":
                role = "APL";
                break;
            case "JS":
                role = "APL";
                break;
            case "FC":
                role = "APL";
                break;
        }
        return ptsptaToolComponent.getPtsFromListByRol(ptsList, role);
    }

    /**
     * 适用于：自贸区业务上收到总行的逻辑
     * 记账机构从数据库中获取
     */
    private void setAccBch4Zmq(SettleSession settleSession, BizInfoVo bizInfo, List<PtsptaVo> ptsList) {
        Bch orgbch = settleSession.getOrgBch();
        if (orgbch != null && "0".equalsIgnoreCase(orgbch.getLev())) {
            String objinr = "";
            String objtyp = "";
            if (bizInfo != null) {
                objinr = bizInfo.getObjinr();
                objtyp = bizInfo.getObjtyp();
            } else if (ptsList != null && ptsList.size() > 0) {
                Pts pts = ptsList.get(0).getPts();
                if (pts != null) {
                    objinr = pts.getObjinr();
                    objtyp = pts.getObjtyp();
                }
            }
            if (StringUtils.isNotEmpty(objinr) && StringUtils.isNotEmpty(objtyp)) {
                String bchkeyinr = "";
                try {
                    bchkeyinr = dyncDaoService.dyncReadFieldByInr(objtyp, objinr, "bchkeyinr");
                } catch (Exception e) {
                    //不处理异常
                }
                if (StringUtils.isNotEmpty(bchkeyinr)) {
                    Bch bch = bchService.getByBchInr(bchkeyinr);
                    settleSession.setBch(bch);
                }
            }
        }
    }

    public static Locale getLocale() {
        Atp atp = getUserSession().getAtp();
        if ("GI".equals(atp.getBus())) {
            return new Locale("en", "US");
        } else {
            // 国际信用证部分
            if (!MdaUtils.isEmpty(atp.getBus()) && US_LOCALE_LIST.contains(atp.getBus())) {
                return Locale.US;
            }
            return Locale.SIMPLIFIED_CHINESE;
        }
    }

    /**
     * 找到业务交易里面的bizinfo
     */
    public static BizInfoVo invokeBizInfo(BaseTransactionVo bo) {
        try {
            String transName = bo.getTransName().toLowerCase();
            TransactionService transactionService = SpringEnvContext.getBean(transName + ".transaction");
            if (transactionService == null) {
                throw new CommonServiceException("transactionService [" + transName + "] unknown");
            }
            Class<?> clazz = transactionService.getClass();
            String methodName = "buildBizInfo";
            Method method = clazz.getDeclaredMethod(methodName, bo.getClass());
            if (method != null) {
                method.setAccessible(true);
                return (BizInfoVo) method.invoke(transactionService, bo);
            }
            return null;
        } catch (NoSuchMethodException e) {
            throw new CommonServiceException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new CommonServiceException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new CommonServiceException(e.getMessage());
        }
    }

    /**
     * 获取收单行交易的非收单交易码
     *
     * @param settleSession
     * @return
     */
    public void setDirectTransName(SettleSession settleSession) {
        try {
            String directTransName = atpBchCacheService.getSdTransNameForRegister();
            settleSession.setDirectTransName(directTransName);
        } catch (Exception e) {
            //获取收单行非收单交易码出现错误，不予处理
            settleSession.setDirectTransName(settleSession.getTransName());
        }
    }

    /**
     * 设置经办机构
     *
     * @param settleSession
     */
    public void setHandleBch(SettleSession settleSession) {
        SessionUserVo sessionUserVo = getSessionUserVo();
        if (sessionUserVo == null) {
            throw new CommonServiceException("未登录");
        }
        Bch bch = bchService.getByBranch(sessionUserVo.getOwnOrgDepartmentNumber());
        if ("2".equalsIgnoreCase(bch.getLev()) && "7".equalsIgnoreCase(bch.getBchtyp())) {
            settleSession.setHldbch(bch);
        } else if ("1000".equals(bch.getBranch()) || "0".equals(bch.getLev())) {
            settleSession.setHldbch(bch);
        } else {
            Bch accbch = settleSession.getBch();
            if (accbch == null) {
                accbch = bchService.getDirectAccBch(bch.getBranch());
            }
            settleSession.setHldbch(accbch);
        }
    }
}
