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

import com.brilliance.isc.bo.Gidcxm;
import com.brilliance.isc.bo.Pts;
import com.brilliance.isc.bo.Pty;
import com.brilliance.isc.bo.model.Giacbs;
import com.brilliance.isc.common.gidcxm.service.GidcxmService;
import com.brilliance.isc.common.sysmod.SysmodService;
import com.brilliance.isc.common.util.StringUtils;
import com.brilliance.isc.common.util.Utils;
import com.brilliance.isc.common.vo.PtsptaVo;
import com.brilliance.isc.mda.dao.GidcxmMapper;
import com.brilliance.isc.mda.dao.PtyMapper;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;

@Service
public class GidcxmServiceImpl implements GidcxmService {

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

    @Autowired
    private GidcxmMapper gidcxmMapper;
    @Autowired
    private SysmodService sysmodService;
    @Autowired
    private PtyMapper ptyMapper;

    /**
     * 保存查询码流水表
     * @param objgrp nidgrp/gidgrp
     * @param transName 交易名
     * @param trnInr 交易主键
     * @param cxmflg 是否展示查询码
     */
    @Override
    public void savGidCxm(Object objgrp, String transName, String trnInr, Boolean cxmflg) {
        Object rec = Utils.getFieldValue(objgrp, "rec");
        if (MdaUtils.isEmpty(Utils.getFieldValue(rec, "quycod"))) {
            return;
        }
        Gidcxm gidcxm = new Gidcxm();
        //保函成功开立后，将数据保存到查询码表(gidcxm)中
        gidcxm.setQuycod(Utils.getFieldValue(rec, "quycod"));
        gidcxm.setOwnref(Utils.getFieldValue(rec, "ownref"));
        Giacbs cbs = Utils.getFieldValue(objgrp, "cbs");
        gidcxm.setCur(cbs.getMax().getCur());
        gidcxm.setAmt(cbs.getMax().getAmt());
        gidcxm.setOpndat(Utils.getFieldValue(rec, "opndat"));
        gidcxm.setExpdat(Utils.getFieldValue(rec, "expdat"));
        if (MdaUtils.isEmpty(Utils.getFieldValue(rec, "fenlishi")) && MdaUtils.compareTo(Utils.getFieldValue(rec, "hndtyp"), "OT") != 0) {
            PtsptaVo aplPtspta = Utils.getFieldValue(objgrp, "apl");
            String ptyinr = aplPtspta.getPtyinr();
            Pty pty = new Pty();
            if (StringUtils.isNotEmpty(ptyinr)) {
                pty.setInr(ptyinr);
                pty = ptyMapper.selectByPrimaryKey(pty);
                if(pty != null){
                    String warran = pty.getNam1();
                    if(StringUtils.isNotEmpty(warran)){
                        //E计算查询接口syncxm该字段最多支持40字符即20个汉字
                        warran = getSubString(warran,40);
                    }
                    gidcxm.setWarran(warran);
                }
            }
        }
        // 针对于分离式保函来说，warran取值被担保人名称
        if (!MdaUtils.isEmpty(Utils.getFieldValue(rec, "fenlishi"))) {
            PtsptaVo bdbPtspta = Utils.getFieldValue(objgrp, "bdb");
            String giduil = Utils.getFieldValue(rec, "giduil");
            if (bdbPtspta != null) {
                Pts pts = bdbPtspta.getPts();
                if (pts != null) {
                    if ("CN".equalsIgnoreCase(giduil) && StringUtils.isNotEmpty(pts.getCnnam())) {
                        gidcxm.setWarran(getSubString(pts.getCnnam(), 40));
                    }
                    if ("EN".equalsIgnoreCase(giduil) && StringUtils.isNotEmpty(pts.getEnnam())) {
                        gidcxm.setWarran(getSubString(pts.getEnnam(), 40));
                    }
                }
            }
        }
        String benNam = "";
        PtsptaVo benPtspta = Utils.getFieldValue(objgrp, "ben");
        if (benPtspta != null && benPtspta.getPts() != null && StringUtils.isNotEmpty(benPtspta.getPts().getAdrblk())) {
            benNam = benPtspta.getPts().getNam();
        } else {
            if (benPtspta != null && StringUtils.isNotEmpty(benPtspta.getDbfadrblkcn())) {
                benNam = benPtspta.getDbfadrblkcn();
            }
        }
        benNam = Utils.replaceCRtoChar(benNam, " ");
        gidcxm.setBenefi(benNam);
        gidcxm.setGidinr(Utils.getFieldValue(rec, "inr"));
        gidcxm.setTrninr(trnInr);
        gidcxm.setInifrm(transName);
        gidcxm.setRelflg("W");
        gidcxm.setCxmflg(cxmflg ? "Y" : "N");
        sysmodService.sdbInsertWithLog(gidcxm);
    }

    /**
     * 复核后更新查询码流水表状态
     * @param trnInr 交易主键
     * @param flag 通过true;打回false
     */
    @Override
    public void reviewGidcxm(String trnInr, Boolean flag) {
        Gidcxm gidcxm = gidcxmMapper.selectGidcxmByTrnInr(trnInr);
        if(gidcxm == null){
            log.error("查询码流水表查询失败，trnInr:{}",trnInr);
        }else{
            if (flag) {
                //复核通过
                gidcxm.setRelflg("R");
                gidcxm.setComdat(new Date());
                sysmodService.sdbUpdateWithLog(gidcxm);
            } else {
                //打回
                sysmodService.sdbDeleteWithLog(gidcxm);
            }
        }
    }

    public String getSubString(String str, int length) {
        try {
            int i;
            int n;
            byte[] bytes = str.getBytes("Unicode");      //使用Unicode字符集将字符串编码成byte序列
            i = 2;      //bytes的前两个字节是标志位，bytes[0] = -2, bytes[1] = -1, 故从第二位开始
            n = 0;
            for(; i < bytes.length && n < length; i++) {
                if(i % 2 == 1) {
                    n++;
                } else {
                    if(bytes[i] != 0) {
                        n++;
                    }
                }
            }
            //去掉半个汉字
            if(i % 2 == 1) {
                if(bytes[i-1] != 0) {
                    i = i -1;
                } else {
                    i = i + 1;
                }
            }
            return new String(bytes, 0, i, "Unicode");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("查询码流水表warran字段赋值失败！");
            return "";
        }
    }
}
