package com.brilliance.isc.common.component;

import com.brilliance.isc.bo.Bch;
import com.brilliance.isc.bo.model.Mcdgrp;
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 MctmodComponent {
    @Autowired
    private CounterService counterService;
    @Autowired
    private TrnmodService trnmodService;

    public String getRef(String subref,String mcttyp) {
        Bch wrkbch = SettleContext.getUserSession().getWrkbch();
        if(MdaUtils.isEmpty(subref)){
            subref = generateDefaultRef(mcttyp);
        }
        if(Strings.len(Strings.trim(subref)) != 13){
            subref = Strings.mid(subref,1,12) + wrkbch.getBchflg();
        }
        return subref;
    }

    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), -4));

        return ownRefBufferBuilder.toString();
    }

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

    public void sav(Mcdgrp mcdgrp){
        //! saves contract including texts. CBS resp. of transaction
        if(MdaUtils.isEmpty(mcdgrp.getRec().getCredat())){
            mcdgrp.getRec().setCredat(Dates.today());
        }
        trnmodService.trnStoreContract(mcdgrp);
    }



}
