package com.brilliance.isc.common.component;

import com.brilliance.isc.bo.Bch;
import com.brilliance.isc.bo.model.Cpdgrp;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.counter.service.CounterService;
import com.brilliance.isc.common.trnmod.service.TrnmodService;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class CptmodComponent {

    @Autowired
    private CounterService counterService;
    @Autowired
    private TrnmodService trnmodService;


    public String getRef(String ownref){
        String tbl = NULLSTR;
        String trn = NULLSTR;
        String transName = SettleContext.getTransName();
        Bch wrkbch = SettleContext.getUserSession().getWrkbch();
        if(MdaUtils.compareTo(transName,"CPTOPN") == 0 || MdaUtils.compareTo(transName,"CPTATO") == 0 || MdaUtils.compareTo(transName,"CPTECO") == 0 || MdaUtils.compareTo(transName,"CPTHYF") == 0){
            tbl = "TT";
            trn = "CPO";
        } else {
            tbl = "IT";
            trn = "CPI";
        }
        if (MdaUtils.isEmpty(ownref)) {
            ownref = generateDefaultRef(trn);
            ownref = tbl + Strings.mid(ownref,4);
        }
        if (Strings.len(ownref) != 14) {
            ownref = Strings.mid(ownref,1,13) + wrkbch.getBchflg();
        }
        return ownref;
    }

    public void sav(Cpdgrp cpdgrp){
        if (MdaUtils.isEmpty(cpdgrp.getRec().getCredat())) {
            cpdgrp.getRec().setCredat(Dates.today());
        }
        trnmodService.trnStoreContract(cpdgrp);
    }

    // setObjName方法放在了公共方法中，具体交易component中不用再实现


    private String generateDefaultRef(String trn) {
        StringBuilder ownRefBufferBuilder = new StringBuilder();
        String branch = getBranchRef();
        // 交易代码 比如 TT
        ownRefBufferBuilder.append(trn);

        // 4位分行编码
        ownRefBufferBuilder.append(branch);

        // 2位年份
        ownRefBufferBuilder.append(Strings.mid(MdaUtils.toString(Dates.getYear(Dates.today()), 4), 3, 2));

        // 5位流水号
        ownRefBufferBuilder.append(MdaUtils.toString(counterService.dbCounter(trn + branch), -5));

        return ownRefBufferBuilder.toString();
    }

    private String getBranchRef() {
        Bch bch = SettleContext.getUserSession().getBch();
        if (bch != null) {
            return bch.getBranch();
        }
        return NULLSTR;
    }
}
