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

import cn.hutool.core.lang.Assert;
import com.brilliance.isc.bo.*;
import com.brilliance.isc.common.api.bch.service.BchService;
import com.brilliance.isc.common.codetable.service.CodetableService;
import com.brilliance.isc.common.contants.CommonContants;
import com.brilliance.isc.common.context.AppEnv;
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.quemod.service.QuemodService;
import com.brilliance.isc.common.quemod.vo.QueClaStatus;
import com.brilliance.isc.common.quemod.vo.TaskFlowStatus;
import com.brilliance.isc.common.quemod.vo.TaskStatus;
import com.brilliance.isc.common.quemod.vo.TrnRelflgStatus;
import com.brilliance.isc.common.sysmod.SysmodService;
import com.brilliance.isc.common.taskdistributor.service.TaskDistService;
import com.brilliance.isc.common.tools.service.ObjectStroeToolService;
import com.brilliance.isc.common.util.StringUtils;
import com.brilliance.isc.common.util.Utils;
import com.brilliance.isc.mda.dao.*;
import com.brilliance.mda.runtime.mda.util.Dates;
import com.brilliance.mda.runtime.mda.util.Formats;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.mda.runtime.mda.util.Strings;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Objects;

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

@Service
public class QuemodServiceImpl implements QuemodService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private SysmodService sysmodService;

    @Resource
    private CounterService counterService;

    @Resource
    private QueMapper queMapper;

    @Resource
    private TrnMapper trnMapper;

    @Resource
    private SmhMapper smhMapper;

    @Resource
    private OrdMapper ordMapper;

    @Resource
    private TrsMapper trsMapper;

    @Resource
    private SptMapper sptMapper;

    @Resource
    private BchService bchService;

    @Resource
    private ErsMapper ersMapper;

    @Resource
    private EcmMapper ecmMapper;

    @Resource
    private TaskDistService taskDistService;

    @Autowired
    private AppEnv appEnv;

    @Autowired
    private CodetableService codetableService;

    @Autowired
    private ObjectStroeToolService objectStroeToolService;


    @Override
    public void updateBySpt(Spt spt) {

    }

    public void deleteAllByTrn(Trn trn){
        //更新对应trn下的que状态
        List<Trn> trnList=trnMapper.selectByOrdinr(trn.getOrdinr());
        if(trnList!=null) {
            for (int i = 0; i < trnList.size(); i++) {
                queMapper.updateHldflgByObjtypAndObjinr("D", "TRN", trnList.get(i).getInr());
            }
        }
        //更新对应spt下的que状态
        List<Spt> sptList=sptMapper.selectByOrdinr(trn.getOrdinr());
        if(sptList!=null) {
            for (int i = 0; i < sptList.size(); i++) {
                queMapper.updateHldflgByObjtypAndObjinr("D", "SPT", sptList.get(i).getInr());
            }
        }

        //更新收单行上收SPT的记录delflg=‘X’
        Spt spt =sptMapper.selectByCreobjtypAndCreobjinrAndHldflg("TRN",trn.getInr(),"Y");
        if(spt!=null) {
            spt.setDelflg("X");
            sptMapper.updateByPrimaryKey(spt);
        }
    }

    @Override
    public void insertBySpt(Spt argSpt,Trn argTrn,String status) {
        Date today =new Date();
        Que que = queMapper.selectByObjTypeInrSubId("SPT", argSpt.getInr(), null);
        if (que == null) {
            que = new Que();
            que.setObjtyp("SPT");
            que.setObjinr(argSpt.getInr());
        }
        que.setObjnam(argSpt.getObjnam());
        que.setObjref(argSpt.getObjref());
        switch (argSpt.getSta()) {
            case "CIU":
            case "CIV":
            case "CIW":
                que.setChannel("CIP");//CIPS
                break;
            case "FMT":
            case "FXPS":
                que.setChannel("FMT");//境内外币
                break;
            case "HVP":
            case "HVQ":
            case "HVR":
            case "BEP":
            case "BEQ":
            case "BES":
            case "CMX":
            case "CMY":
            case "HVT":
            case "CMT":
                que.setChannel("HVP");//二代支付
                break;
            case "EJS":
                que.setCla("INC");
                que.setHldflg("");
                que.setChannel("EJS");
                /*if(Objects.equals(status,TaskStatus.INCOMING.getValue())) {
                    que.setObjref(argSpt.getObjnam());
                }*/
                break;
            case "YPT":
                que.setCla("INC");
                que.setHldflg("");
                que.setChannel("YPT");
                break;
            case "INC":
                que.setCla("INC");
                que.setHldflg("");
                que.setChannel("SWT");
                if (null != argSpt.getMsgtyp() && argSpt.getMsgtyp().toUpperCase().contains("ELCS")) {
                    que.setChannel("ELC");
                }
                break;
            case "COR":
            case "REG":
            case "PEN":
            case "CMB":
            case "PUR":
                que.setCla(argSpt.getSta());
                que.setHldflg("");
                break;
            default:
                que.setHldflg("");
        }
        if (!MdaUtils.isEmpty(argSpt.getDelflg())) {
            que.setHldflg("D");
        }
        que.setBalflg("A");
        que.setBalcla("zzz");
        Utils.sdbEtySetRec(que, "QUE", argSpt.getEtgextkey(), argSpt.getEtyextkey());
        que.setConobjtyp(argSpt.getObjtyp());
        que.setConobjinr(argSpt.getObjinr());
        que.setTxt(argSpt.getTxt());
        que.setFrm(argSpt.getFrm());
        que.setRelamt(argSpt.getRelamt());
        que.setRelcur(argSpt.getRelcur());
        que.setUsg(argSpt.getOwnusg());
        que.setTardattim(today);
        que.setCtmnam(argSpt.getCtmnam());
        que.setRemark(argSpt.getInftxt());
        Bch accBch=SettleContext.getUserSession().getBch();
        que.setAccbchinr(accBch!=null?accBch.getInr():"");
        if(argTrn!=null) {
            que.setCreobjtyp("TRN");
            que.setCreobjinr(argTrn.getInr());
//            que.setTardattim(argTrn.getInidattim());
            que.setAccbchinr(argTrn.getAccbchinr());
        }else{
            if(StringUtils.isEmpty(que.getAccbchinr())){
                que.setAccbchinr(argSpt.getBchkeyinr());
            }
        }
        if(StringUtils.isNotEmpty(argSpt.getMsgtyp())){
            que.setMsgtyp(argSpt.getMsgtyp());
            Smh smh =smhMapper.getSmhInfoBySptSmhinr(argSpt.getSmhinr());
            if(smh!=null){
                que.setChlflg(smh.getChlflg());

                if("ERX".equals(smh.getCortyp()) && "TRN".equals(smh.getTrntyp())){
                    que.setChannel("EJS");
                }
                if("YPT".equals(smh.getCortyp()) && "TRN".equals(smh.getTrntyp())){
                    que.setChannel("YPT");
                }
            }
        }
        que.setChannel(argSpt.getChannel());
        que.setFrontchannel(argSpt.getFrontchannel());
        que.setCortyp(argSpt.getCortyp());
        que.setBranchinr(argSpt.getBranchinr());
        que.setBchkeyinr(argSpt.getBchkeyinr());
        que.setEciflg(argSpt.getEciflg());
        que.setChnref(argSpt.getChnref());
        Bch bch =bchService.getByBranch("1000");//总行机构
        if(StringUtils.isEmpty(que.getBchkeyinr())){
            que.setBchkeyinr(bch.getInr());
        }
        if(StringUtils.isEmpty(que.getBranchinr())){
            que.setBranchinr(que.getBchkeyinr());
        }
        que.setCreateTime(today);
        que.setUpdateTime(today);
        if(StringUtils.isNotEmpty(argSpt.getOrdinr())) {
            Ord ord = ordMapper.selectByOrdInr(argSpt.getOrdinr());
            que.setSdhflg(ord.getSdhflg());
            que.setOrdinr(ord.getInr());
        }
        que.setRelusr(SettleContext.getUserSession().getUsr().getExtkey());
        if("Y".equals(argSpt.getHldflg())){//隐藏
            que.setStatus(TaskStatus.NEW.getValue());
            que.setCla("RIM");  //注册中心
        }else{
            que.setUsrcon(argSpt.getUsr());
            que.setStatus(TaskStatus.PENDING.getValue());
            que.setCla("PEN");
        }
        if(!StringUtils.isEmpty(status)){//状态不为空
            que.setStatus(status);
            que.setCla(argSpt.getSta());
        }
        if (MdaUtils.isEmpty(que.getInr())) {
            if (!(MdaUtils.compareTo(que.getHldflg(), "D") == 0)) {
                if (MdaUtils.compareTo(que.getCla(), "INC") == 0) {
                    if (!MdaUtils.isEmpty(argSpt.getSmhinr())) {
                        Smh smh = new Smh();
                        smh.setInr(argSpt.getSmhinr());
                        smh = smhMapper.selectByPrimaryKey(smh);
                        if (smh != null) {
                            que.setAddref("MT " + smh.getMsgtyp());
                           /* if (MdaUtils.isEmpty(que.getObjref())) {
                                que.setObjref(smh.getSndkey());
                            }*/
                        }
                    }
                }
            }
            que.setInr(counterService.dbCounterFormat("QUE"));
            sysmodService.sdbInsert(que);
            if(!Objects.equals(que.getCla(),QueClaStatus.PEN.getValue())) {
                //非暂存时进行任务通知。
                taskDistService.handleTaskEnqueue(que);
            }
        } else {
            queMapper.updateByPrimaryKeySelective(que);
        }
    }

    public void saveEntryByDia(Dia argDia) {
        Que que =queMapper.selectByObjtypAndObjinr("DIA",argDia.getInr());
        if(que==null) {
            Date today =argDia.getDat();
            que =new Que();
            que.setObjtyp("DIA");
            que.setObjinr(argDia.getInr());
            que.setHldflg("");
            que.setBalflg("A");
            que.setBalcla("zzz");
            Utils.sdbEtySetRec(que, "QUE", "", argDia.getEtyextkey());
            que.setConobjtyp(argDia.getObjtyp());
            que.setConobjinr(argDia.getObjinr());
            que.setObjnam(argDia.getInfdsp());
            que.setObjref(argDia.getObjref());
            que.setTxt(argDia.getInfdsp());
            que.setFrm(argDia.getFrm());
            que.setRelamt(argDia.getPayamt());
            que.setRelcur(argDia.getPaycur());
            que.setUsg(argDia.getOwnusg());
            que.setTardattim(argDia.getDat());
            que.setBranchinr(argDia.getBranchinr());
            que.setBchkeyinr(argDia.getBchkeyinr());
            Bch bch =bchService.getByBranch("1000");//总行机构
            Bch accBch=SettleContext.getUserSession().getBch();
            que.setAccbchinr(accBch!=null?accBch.getInr():"");
            if(StringUtils.isEmpty(que.getBchkeyinr())){
                que.setBchkeyinr(bch.getInr());
            }
            if(StringUtils.isEmpty(que.getBranchinr())){
                que.setBranchinr(que.getBchkeyinr());
            }
            que.setObjref(argDia.getObjref());
            que.setCreateTime(today);
            que.setUpdateTime(today);
            que.setUsrcon(argDia.getUsr());
            que.setStatus(TaskStatus.PENDING.getValue());
            que.setCla(QueClaStatus.DIA.getValue());

            que.setInr(counterService.dbCounterFormat("QUE"));
            queMapper.insert(que);
            taskDistService.handleTaskEnqueue(que);
        }else{
            if("X".equals(argDia.getDonflg())){
                que.setHldflg("D");
                que.setHlddattim(new Date());
                que.setTardattim(argDia.getDat());
            } else {
                que.setHldflg("");
                que.setTardattim(argDia.getDat());
            }
            queMapper.updateByPrimaryKey(que);
        }
    }

    public void insertByTrn(Trn trn,String branch,String flowstatus) {
       Que que =new Que();
       Que oldque =queMapper.selectByObjtypAndObjinr("TRN",trn.getInr());
       Date date=new Date();
        que.setObjtyp("TRN");
        que.setObjinr(trn.getInr());
        que.setObjsubid("");
        que.setCla("REL");
        que.setConobjtyp(trn.getObjtyp());
        que.setConobjinr(trn.getObjinr());
        que.setObjnam(trn.getObjnam());
        que.setObjref(trn.getOwnref());
        que.setFrm(trn.getInifrm());
        que.setTxt(codetableService.getTblLabel(trn.getInifrm(), "ATPTXT"));
        que.setRelamt(trn.getReloriamt());
        que.setRelcur(trn.getReloricur());
        que.setXrfamt(trn.getRelamt());
        que.setXrfcur(trn.getRelcur());
        que.setStatus(CommonContants.QUE_STATUS_WAITING);
        que.setBranchinr(trn.getBranchinr());
        que.setCreateTime(date);
        que.setUpdateTime(date);
        que.setCtmnam(trn.getObjnam());
        if(Objects.equals(branch,"1000")){
            Bch bch =bchService.getByBranch(branch);
            que.setBchkeyinr(bch.getInr());
        }else {
            que.setBchkeyinr(trn.getBchkeyinr());
        }
        que.setAccbchinr(trn.getAccbchinr());
        que.setBalflg("C");
//        que.setSlacla(trn.getSlacla());
        que.setBalcla("zzz");
        que.setTardattim(trn.getInidattim());
        que.setUsg(trn.getUsg());
        que.setUsrcon(trn.getIniusr());
        que.setFlowstatus(flowstatus);
        que.setRelflg(trn.getRelflg());
        que.setRelreq(trn.getRelreq()+":"+trn.getRelreq0()+"-"+trn.getRelreq1()+"-"+trn.getRelreq2());
        que.setRelres(trn.getRelres()+":"+trn.getRelres0()+"-"+trn.getRelres1()+"-"+trn.getRelres2());
        Ord ord =ordMapper.selectByOrdInr(trn.getOrdinr());
        String usrtrs=trsMapper.selectAllUsrByTrninr(trn.getInr());
        que.setSdhflg(ord.getSdhflg());
        que.setOrdinr(ord.getInr());
        que.setRelusr(usrtrs);
        if(oldque!=null && StringUtils.isNotEmpty(oldque.getChannel())){
            que.setChannel(oldque.getChannel());
            que.setFrontchannel(oldque.getFrontchannel());
            que.setCortyp(oldque.getCortyp());
        }
        sysmodService.sdbInsert(que);
        taskDistService.handleTaskEnqueue(que);
    }

    public void insertByTrnCustomer(Trn trn,Trn creTrn,String branch) {
        Date date = new Date();
        Que que = queMapper.selectByObjtypAndObjinrAndStatus("TRN",trn.getInr(),TaskStatus.WAITING_CONFIRM.getValue());
        if(que!=null){
            que.setTardattim(date);
            que.setCreateTime(date);
            que.setUpdateTime(date);
            sysmodService.sdbUpdate(que);
        }else {
            que = new Que();
            que.setObjtyp("TRN");
            que.setObjinr(trn.getInr());
            que.setObjsubid("");
            que.setCla("REL");
            que.setConobjtyp(trn.getObjtyp());
            que.setConobjinr(trn.getObjinr());
            que.setObjnam(trn.getObjnam());
            que.setObjref(trn.getOwnref());
            que.setFrm(trn.getInifrm());
            que.setTxt(codetableService.getTblLabel(trn.getInifrm(), "ATPTXT"));
            que.setRelamt(trn.getReloriamt());
            que.setRelcur(trn.getReloricur());
            que.setXrfamt(trn.getRelamt());
            que.setXrfcur(trn.getRelcur());
            que.setStatus(TaskStatus.WAITING_CONFIRM.getValue());
            que.setBranchinr(trn.getBranchinr());
            que.setCreateTime(date);
            que.setUpdateTime(date);
            que.setRelflg(trn.getRelflg());
            que.setRelreq(trn.getRelreq() + ":" + trn.getRelreq0() + "-" + trn.getRelreq1() + "-" + trn.getRelreq2());
            que.setRelres(trn.getRelres() + ":" + trn.getRelres0() + "-" + trn.getRelres1() + "-" + trn.getRelres2());
            Ord ord = ordMapper.selectByOrdInr(trn.getOrdinr());
            String usrtrs = trsMapper.selectAllUsrByTrninr(trn.getInr());
            que.setSdhflg(ord.getSdhflg());
            que.setOrdinr(ord.getInr());
            que.setRelusr(usrtrs);
            if (Objects.equals(branch, "1000")) {
                Bch bch = bchService.getByBranch(branch);
                que.setBchkeyinr(bch.getInr());
            } else {
                que.setBchkeyinr(trn.getBchkeyinr());
            }
            que.setAccbchinr(trn.getAccbchinr());
            que.setBalflg("C");
            que.setBalcla("zzz");
            que.setTardattim(date);
            que.setUsg(trn.getUsg());
            que.setUsrcon(trn.getIniusr());
            que.setCreobjtyp("TRN");
            que.setCreobjinr(creTrn.getInr());
            que.setFlowstatus(TaskFlowStatus.BRANCH_FIRST_RELEASE.getValue());
            sysmodService.sdbInsert(que);
            taskDistService.handleTaskEnqueue(que);
        }
    }

    public void updateByTrn(Trn trn) {

    }

    public void updateQueStatus(Que que, String status) {
         que.setOldstatus(que.getStatus());
         que.setStatus(status);
         sysmodService.sdbUpdate(que);
    }

    public void sptQueUpdateStatus(Spt argSpt,String status) {
        if(argSpt==null)
            return;
        if(StringUtils.isEmpty(argSpt.getInr()))
            return;
        if(CommonContants.QUE_STATUS_DELETED.equals(status)) {
            argSpt.setDelflg("X");
        }else{
            argSpt.setSta(status);
        }
        sysmodService.sdbUpdate(argSpt);
        Que que = queMapper.selectByObjTypeInrSubId("SPT", argSpt.getInr(), null);
        que.setOldstatus(que.getStatus());
        que.setStatus(status);
        sysmodService.sdbUpdate(que);
    }

    public void trnQueUpdateStatus(Trn argTrn,String status) {
        if(argTrn==null)
            return;
        if(StringUtils.isEmpty(argTrn.getInr()))
            return;
        Que que = queMapper.selectByObjTypeInrSubId("TRN", argTrn.getInr(), null);
        if(que!=null) {
            que.setOldstatus(que.getStatus());
            que.setStatus(status);
            que.setRelflg(argTrn.getRelflg());
            sysmodService.sdbUpdate(que);
        }
    }

    @Deprecated
    @ApiOperation("未使用")
    public void sptQueUpdate(Spt argSpt) {
        Date today =new Date();
        Que que = queMapper.selectByObjTypeInrSubId("SPT", argSpt.getInr(), null);
        if (que == null) {
            que = new Que();
            que.setObjtyp("SPT");
            que.setObjinr(argSpt.getInr());
        }
        switch (argSpt.getSta()) {
            case "COR":
            case "INC":
            case "REG":
            case "PEN":
            case "CMB":
            case "PUR":
                que.setCla(argSpt.getSta());
                que.setHldflg("");
                break;
            default:
                que.setHldflg("");
        }
        if (!MdaUtils.isEmpty(argSpt.getDelflg())) {
            que.setHldflg("D");
        }
        que.setBalflg("A");
        que.setBalcla("zzz");
        Utils.sdbEtySetRec(que, "QUE", argSpt.getEtgextkey(), argSpt.getEtyextkey());
        que.setConobjtyp(argSpt.getObjtyp());
        que.setConobjinr(argSpt.getObjinr());
        que.setObjnam(argSpt.getObjnam());
        que.setObjref(argSpt.getObjref());
        que.setTxt(argSpt.getTxt());
        que.setFrm(argSpt.getFrm());
        que.setRelamt(argSpt.getRelamt());
        que.setRelcur(argSpt.getRelcur());
        que.setUsg(argSpt.getOwnusg());
        que.setTardattim(today);
        que.setBranchinr(argSpt.getBranchinr());
        que.setBchkeyinr(argSpt.getBchkeyinr());
        Bch accBch=SettleContext.getUserSession().getBch();
        que.setAccbchinr(accBch!=null?accBch.getInr():"");
        Bch bch =bchService.getByBranch("1000");//总行机构
        if(StringUtils.isEmpty(que.getBchkeyinr())){
            que.setBchkeyinr(bch.getInr());
        }
        if(StringUtils.isEmpty(que.getBranchinr())){
            que.setBranchinr(que.getBchkeyinr());
        }
        que.setObjref(argSpt.getObjref());
        que.setCreateTime(today);
        que.setUpdateTime(today);
        if("Y".equals(argSpt.getHldflg())){//隐藏
            que.setStatus(TaskStatus.NEW.getValue());
            que.setCla("RIM");  //注册中心
            que.setHldflg("D");
        }else{
            que.setUsrcon(argSpt.getUsr());
            que.setStatus(TaskStatus.PENDING.getValue());
            que.setCla("PEN");
        }
        if (MdaUtils.isEmpty(que.getInr())) {
            if (!(MdaUtils.compareTo(que.getHldflg(), "D") == 0)) {
                if (MdaUtils.compareTo(que.getCla(), "INC") == 0) {
                    if (!MdaUtils.isEmpty(argSpt.getSmhinr())) {
                        Smh smh = new Smh();
                        smh.setInr(argSpt.getSmhinr());
                        smh = smhMapper.selectByPrimaryKey(smh);
                        if (smh != null) {
                            que.setAddref("MT " + smh.getMsgtyp());
                           /* if (MdaUtils.isEmpty(que.getObjref())) {
                                que.setObjref(smh.getSndkey());
                            }*/
                        }
                    }
                }
            }
            que.setInr(counterService.dbCounterFormat("QUE"));
            que.setCreateTime(today);
            que.setUpdateTime(today);
            queMapper.insert(que);
        } else {
            queMapper.updateByPrimaryKeySelective(que);
        }

    }

    public void sptSaveEntryBySptRepair(Spt argSpt, Spt oriSpt, String argSta, String objName) {
        String sptLoaded = "";
        Assert.notNull(oriSpt);
        Bch bch =bchService.getByBchInr(argSpt.getBchkeyinr());
        if (StringUtils.isNotEmpty(argSpt.getInr())) {
            sptLoaded = "X";
        } else {
            sptLoaded = "";
        }
        String frm = sysmodService.getPreFrame(oriSpt.getFrm(),bch.getBranch());
        argSpt.setFrm(frm);
        argSpt.setCretrn(oriSpt.getFrm());
        if (!("COR".equals(argSta) || "CTR".equals(argSta) || "REJ".equals(argSta))) {
            argSpt.setUsr(SettleContext.getUserSession().getUsr().getExtkey());
        }
        if (StringUtils.isEmpty(argSpt.getOwnusg())) {
            // Load Workgroup, if field available in USR table
            argSpt.setOwnusg(SettleContext.getUserSession().getUsr().getUsg());
        }
        argSpt.setDattim(Dates.now());
        if (MdaUtils.isEmpty(argSpt.getObjtyp())) {
            if(!MdaUtils.isEmpty(oriSpt)) {
                argSpt.setObjtyp(oriSpt.getObjtyp());
            }
        }
        if (StringUtils.isNotEmpty(objName)) {
            argSpt.setObjnam(objName);
            argSpt.setCtmnam(objName);
        }
        Assert.notNull(oriSpt);
        if (MdaUtils.isEmpty(argSpt.getTxt()) && (StringUtils.isNotEmpty(oriSpt.getTxt()) && oriSpt.getTxt().length()==3)) {
            argSpt.setTxt(oriSpt.getTxt());
        }
        if (oriSpt != null) {
            argSpt.setChannel(oriSpt.getChannel());
            argSpt.setCortyp(oriSpt.getCortyp());
            argSpt.setFrontchannel(oriSpt.getFrontchannel());
            argSpt.setSta(argSta);
            argSpt.setEtgextkey(SettleContext.getUserEtg().getExtkey());
            argSpt.setEtyextkey(SettleContext.getUserEty().getExtkey());
            argSpt.setCreobjtyp("SPT");
            argSpt.setCreobjinr(oriSpt.getInr());
            //打回后注que的msgtyp类型
            argSpt.setMsgtyp(oriSpt.getMsgtyp());
            argSpt.setSmhinr(oriSpt.getSmhinr());
        }
        if (MdaUtils.isEmpty(argSpt.getInr())) {
            argSpt.setInr(counterService.dbCounterFormat("SPT"));
            sptMapper.insert(argSpt);
            sptWriteLog(argSpt, "I");
        } else {
            sptWriteLog(argSpt, "U");
            sptMapper.updateByPrimaryKeySelective(argSpt);
        }

        if(oriSpt!=null) {
            //更新打回 ERS来报ERS信息
            List<Ers> ersList = ersMapper.selectBySptinrAndDirList(oriSpt.getInr(), "<");
            if(ersList!=null && ersList.size()>0) {
                for(int i=0;i<ersList.size();i++) {
                    ersList.get(i).setSptinr(argSpt.getInr());
                    ersList.get(i).setTrninr("");
                    ersList.get(i).setObjinr("");
                    sysmodService.sdbUpdate(ersList.get(i));
                }
            }
            Ecm ecm =ecmMapper.selectOneBySptinr(oriSpt.getInr());
            if(ecm!=null){
                ecm.setSptinr(argSpt.getInr());
                ecmMapper.updateByPrimaryKey(ecm);
            }
        }
        Assert.notNull(oriSpt);
        if("TRN".equals(oriSpt.getCreobjtyp()) && StringUtils.isNotEmpty(oriSpt.getCreobjinr())){
            //押汇中心经办退回，取待经办业务的trn数据进行操作
            Trn argTRN=trnMapper.selectByTrninr(oriSpt.getCreobjinr());
            this.insertBySpt(argSpt, argTRN, TaskStatus.CORRECT.getValue());
        }else {
            this.insertBySpt(argSpt, null, TaskStatus.CORRECT.getValue());
        }
        try {
            String argDir = "delete/" + oriSpt.getInr().substring(0, 12);
            String filPath = appEnv.getSubDataPath(argDir, oriSpt.getInr() + ".bak");
            String newArgDir = "delete/" + argSpt.getInr().substring(0, 12);
            String newFilPath=appEnv.getSubDataPath(newArgDir, argSpt.getInr() + ".bak");
            File file = objectStroeToolService.getObjectFile(filPath);
            if(!MdaUtils.isEmpty(file)) {
                String dataString = FileUtils.readFileToString(file, "UTF-8");
                boolean bool = objectStroeToolService.saveObjectFileByString(dataString, newFilPath, "");
            }
        }catch(IOException e){
            throw new CommonServiceException("文件存储失败");
        }
    }

    public void sptSaveEntryForRepair(Spt argSpt, Trn argTrn, String argSta, String objName) {
        String sptLoaded = "";
        Assert.notNull(argSpt);
        if (StringUtils.isNotEmpty(argSpt.getInr())) {
            sptLoaded = "X";
        } else {
            sptLoaded = "";
        }
        String frm = SettleContext.getTransName();
        // transaction for 4-eye`s has to be set anew
        if (StringUtils.isEmpty(argSpt.getFrm())
                || SptWaitForProcessing.equals(argSpt.getSta())) {
            if (StringUtils.isNotEmpty(argSpt.getDelflg())) {
                argSpt.setFrm(Strings.mid(frm, 1, 2) + "A" + Strings.mid(frm, 4, 5));
            } else {
                argSpt.setFrm(frm);
            }
        }
        argSpt.setCretrn(frm);
        if (!("COR".equals(argSta) || "CTR".equals(argSta) || "REJ".equals(argSta))) {
            argSpt.setUsr(SettleContext.getUserSession().getUsr().getExtkey());
        }
        if (StringUtils.isEmpty(argSpt.getOwnusg())) {
            // Load Workgroup, if field available in USR table
            argSpt.setOwnusg(SettleContext.getUserSession().getUsr().getUsg());
        }
        argSpt.setDattim(Dates.now());
        // argSpt.setSsninr(SettleContext.getUserSession().getSsn().getInr());
        if (MdaUtils.isEmpty(argSpt.getObjtyp())) {

            if(!MdaUtils.isEmpty(argTrn)) {
                argSpt.setObjtyp(Utils.recGetObj(argTrn));
                argSpt.setObjinr(Utils.recGetInr(argTrn));
            }
        }
        if (StringUtils.isNotEmpty(objName)) {
            argSpt.setObjnam(objName);
            argSpt.setCtmnam(objName);
        }
        Assert.notNull(argTrn);
        if (MdaUtils.isEmpty(argSpt.getTxt()) || (StringUtils.isNotEmpty(argSpt.getTxt()) && argSpt.getTxt().length()>3)) {
            Que trnque = queMapper.selectByObjtypAndObjinr("TRN", argTrn.getInr());
            if(trnque!=null) {
                argSpt.setTxt(trnque.getChannel());
                argSpt.setChannel(trnque.getChannel());
                argSpt.setCortyp(trnque.getCortyp());
                argSpt.setFrontchannel(trnque.getFrontchannel());
            }
            //argSpt.setTxt(getTrnnam(frm));
        }
        argSpt.setSta(argSta);
        argSpt.setEtgextkey(SettleContext.getUserEtg().getExtkey());
        argSpt.setEtyextkey(SettleContext.getUserEty().getExtkey());
        argSpt.setCreobjinr("TRN");
        Assert.notNull(argTrn);
        argSpt.setCreobjinr(argTrn.getInr());
        if(argTrn!=null){
            //打回后注que的msgtyp类型
            String smhinr="";
            String msgtyp="";
            Ord ord =ordMapper.selectByOrdInr(argTrn.getOrdinr());
            if(ord!=null) {
                argSpt.setHldflg(ord.getSdhflg());
            }
            List<Smh> smhList =smhMapper.selectByTrninr(argTrn.getInr());
            if (smhList!=null) {
                for (int i = 0; i < smhList.size(); i++) {
                    if ("<".equals(smhList.get(i).getDir())) {
                        smhinr = smhList.get(i).getInr();
                        msgtyp = smhList.get(i).getMsgtyp();
                        break;
                    }
                }
                argSpt.setMsgtyp(msgtyp);
                argSpt.setSmhinr(smhinr);
            }
            //更新spt渠道
//            Que que =queMapper.selectByObjtypAndObjinr("TRN",argTrn.getInr());
//            if(que!=null && !StringUtils.isEmpty(que.getChannel())){
//                argSpt.setSta(que.getChannel());
//            }
        }
        if (MdaUtils.isEmpty(argSpt.getInr())) {
            argSpt.setInr(counterService.dbCounterFormat("SPT"));
            sptMapper.insert(argSpt);
            sptWriteLog(argSpt, "I");
        } else {
            sptWriteLog(argSpt, "U");
            sptMapper.updateByPrimaryKeySelective(argSpt);
        }

        if(argTrn!=null) {
            //更新打回 ERS来报ERS信息
            Ers ers = ersMapper.selectByTrninrAndDir(argTrn.getInr(), "<");
            if(ers!=null) {
                ers.setSptinr(argSpt.getInr());
                ers.setObjinr("");
                sysmodService.sdbUpdate(ers);
            }
            Ecm ecm =ecmMapper.selectOneByObjtypAndObjinr(argTrn.getObjtyp(),argTrn.getObjinr());
            if(ecm!=null){
                ecm.setSptinr(argSpt.getInr());
                ecmMapper.updateByPrimaryKey(ecm);
            }
        }
        Assert.notNull(argTrn);
        this.insertBySpt(argSpt,argTrn,TaskStatus.CORRECT.getValue());
        try {
            String argDir = "trndata" ;
            String filPath = appEnv.getSubDataPath(argDir, argTrn.getInr() + ".dat");
            String newArgDir = "delete/" + argSpt.getInr().substring(0, 12);
            String newFilPath=appEnv.getSubDataPath(newArgDir, argSpt.getInr() + ".bak");
            File file = objectStroeToolService.getObjectFile(filPath);
            if(!MdaUtils.isEmpty(file)) {
                String dataString = FileUtils.readFileToString(file, "UTF-8");
                boolean bool = objectStroeToolService.saveObjectFileByString(dataString, newFilPath, "");
            }
        }catch(IOException e){
            throw new CommonServiceException("文件存储失败");
        }
    }

    public void sptWriteLog(Spt argSpt, String argFu) {
        String lin = argSpt.getObjtyp() + TAB + sysmodService.midObjinr(argSpt.getObjinr()) + TAB + argSpt.getInr() + TAB + argFu + TAB + argSpt.getSta() + TAB + argSpt.getHldflg() + TAB + Formats.format(Dates.now(), "YY-MM-DD hh:mm:ss",/*Systems.getLang()*/"CN", tdContextTZSYSTEM) + TAB + "" + TAB + SettleContext.getTransName() + TAB + argSpt.getObjnam();
        log.info("sptWriteLog:{}", lin);
    }

    public String getTrnnam(String transName) {
        return codetableService.getTblLabel(transName, "ATPTXT");
    }

    public void insertByTrnConfirm(Trn argTrn){
        Trn confirmTrn= trnMapper.selectByOrdinrAndRelflg(argTrn.getOrdinr(), TrnRelflgStatus.CONFIRM.getValue());
        if(confirmTrn!=null) {
            this.insertByTrnCustomer(confirmTrn,argTrn, "");
        }
    }

    public void setAutoFlag(Spt spt,String autoFlag){
        //autoFlag 赋值为Y  自动， 赋值为“”,改为手动
        Que que = queMapper.selectByObjtypAndObjinr("SPT", spt.getInr());
        if(StringUtils.isEmpty(autoFlag)){
            que.setAuto("");
        }else{
            que.setAuto("Y");
        }
        queMapper.updateByPrimaryKeySelective(que);
    }

    public void setAutoFlagByQueinr(String queinr,String autoFlag){
        //autoFlag 赋值为Y  自动， 赋值为“”,改为手动
        Que que = queMapper.selectOneByInr(queinr);
        if(StringUtils.isEmpty(autoFlag)){
            que.setAuto("");
        }else{
            que.setAuto("Y");
        }
        queMapper.updateByPrimaryKeySelective(que);
    }
}
