package com.brilliance.isc.common.bop.bopdec.service.imp;

import com.brilliance.mda.runtime.mda.util.MdaUtils;
import com.brilliance.isc.bo.bop.bopprint.BopTrnBo;
import com.brilliance.isc.bo.model.Dbegrp;
import com.brilliance.isc.common.bopset.service.IBopPrintService;
import com.brilliance.isc.common.codetable.service.CodetableService;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.util.Utils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("dbe.print")
public class DbePrintServiceImpl implements IBopPrintService<Dbegrp> {

    private static Logger log = LoggerFactory.getLogger(DbePrintServiceImpl.class);

    private String bgimg;

    @Autowired
    Pntmod pntmod;

    @Autowired
    CodetableService codetableService;

    @PostConstruct
    public  void loadBgImg() throws IOException {
        //获取背景图片
        String base64 = new BASE64Encoder().encode(IOUtils.resourceToByteArray("images/BOPCOMDBE.jpg", DbaPrintServiceImpl.class.getClassLoader()));
        bgimg = "data:image/jpg;base64,"+base64;
    }

    @Override
    public Map<String, Object> getInputMapData(Dbegrp bopGroup, Date credat,String alonflg) {
        //新申请一个空的Map
        Map<String, Object> data = new HashMap<String, Object>();
        //赋值背景图片
        data.put("bgImg",bgimg);

        String checkedSign = pntmod.getCheckedChar();//勾选符
        BigDecimal zero = new BigDecimal(0);
        //下面将要向Map中输入数据
        pntmod.setSplitCodeNumber(data,
                bopGroup.getBas().getRptno(), "rptno");			//! 申报号码
        data.put("buscode",bopGroup.getBas().getBuscode());     //银行业务编号
        data.put("custnm",bopGroup.getBas().getCustnm());
        String custypeCode =bopGroup.getBas().getCustype();
        if("C".equals(custypeCode))
        {
            data.put("custype_c", checkedSign);					//! 勾选对公
            pntmod.setSplitCodeNumber(data,
                    bopGroup.getBas().getCustcod(), "custcod");//! 组织机构代码
        }//对公
        else if("D".equals(custypeCode))
        {
            data.put("custype_df", checkedSign);				//! 对私
            data.put("custype_d", checkedSign);					//! 中国居民个人
            data.put("idcode", bopGroup.getBas().getIdcode());		  //! 对私将加入个人身份证号码
        }
        //对私非中国居民
        else if("F".equals(custypeCode))
        {
            data.put("custype_df", checkedSign);				//! 对私
            data.put("custype_f", checkedSign);					//! 非中国居民个人
            data.put("idcode", bopGroup.getBas().getIdcode());			//! 对私将加入个人身份证号码
        }
        //直接忽视掉其他情况（属于异常）
        else{
            log.error("data incorrect in 'dbapt',custype not recognized:"+ custypeCode);//对私
        }
        String methodsCode = bopGroup.getBas().getMethod();
        pntmod.setCodetableData(data, methodsCode,
                "methods", "T:D:M");							//结算方式
        if(bopGroup.getBas().getTxamt().compareTo(zero) == 0){
            data.put("txccy_amt","");
        }
        else
        {
            BigDecimal tx_amt = bopGroup.getBas().getTxamt();
            data.put("txccy_amt",pntmod.getFormatedMoney(bopGroup.getBas().getTxccy(),tx_amt));//收入款币种及金额
            //
            //金额大写
            String amtCn = pntmod.covCnAmt(tx_amt);
            //币种中文
            String curtxt = codetableService.getTblLabel(bopGroup.getBas().getTxccy(),"curtxt");
            data.put("amtcpt", curtxt + amtCn);
        }
        //
        if(bopGroup.getBas().getFcyamt().compareTo(zero) == 0){
            data.put("fcyamt","");
        }
        else
        {
            BigDecimal fcyamt = bopGroup.getBas().getFcyamt();
            data.put("fcyamt",
                    pntmod.getFormatedMoney(bopGroup.getBas().getTxccy(),fcyamt));		//现汇金额
        }
        if(bopGroup.getBas().getLcyamt().compareTo(zero) == 0){
            data.put("lcyamt","");
        }
        else
        {
            BigDecimal lcyamt = bopGroup.getBas().getLcyamt();
            data.put("lcyamt",
                    pntmod.getFormatedMoney(bopGroup.getBas().getTxccy(),lcyamt));		//购汇金额
        }
        if(bopGroup.getBas().getOthamt().compareTo(zero) == 0){
            data.put("othamt","");
        }
        else
        {
            BigDecimal othamt = bopGroup.getBas().getOthamt();
            data.put("othamt",
                    pntmod.getFormatedMoney(bopGroup.getBas().getTxccy(),othamt));		//其它金额
        }
        data.put("lcyacc", bopGroup.getBas().getLcyacc());	  //账号1
        data.put("fcyacc", bopGroup.getBas().getFcyacc());		//账号2
        data.put("othacc", bopGroup.getBas().getOthacc());		//账号3
        data.put("custnm",bopGroup.getBas().getCustnm());//汇款人名称
        //收款行之代理行名称及地址 rcvbnknam_add
        //收款人开户银行在其代理行账号  benbnkno
        //收款人开银行名称及地址  benbnknam_add
        //收款人账号 benacno
        data.put("oppacc",bopGroup.getBas().getOppacc());//收款人账号oppacc
        data.put("oppuser",bopGroup.getBas().getOppuser());//收款人名称
        //判断是否需要打印全部信息
        if("1".equals(alonflg)){
            //国内外费用承担（汇款人、收款人、共同）  our ben  sha
            pntmod.setSplitCodeNumber(data,bopGroup.getVrf().getCountry(), "country");//收款人常驻国家（地区）名称呢个及代码//收款人常驻国家名称及代码  ctyname
            //收款人常驻国家代码
            String paytypeCode = bopGroup.getVrf().getPaytype();
            pntmod.setCodetableData(data, paytypeCode,
                    "paytype", "A:P:R:O");	//付款类型：预付货款、货到付款、退款、其它  paytype "A:D:R:O"
            String payttrCode = bopGroup.getVrf().getPayattr();
            pntmod.setCodetableData(data, payttrCode,
                    "payttr", "X:E:D:A:M:O");
            pntmod.setSplitCodeNumber(data,
                    bopGroup.getVrf().getTxcode(), "txcode");  //! 交易编码1
            if(!MdaUtils.isEmpty(bopGroup.getVrf().getTxcode()))
            {
                BigDecimal tc1_amt = new BigDecimal(0);;
                if(!MdaUtils.isEmpty(bopGroup.getVrf().getTc1amt())){
                    tc1_amt = bopGroup.getVrf().getTc1amt();
                }
                log.debug("-----------------------E");
                data.put("txccy_amt1",
                        pntmod.getFormatedMoney( bopGroup.getBas().getTxccy(),tc1_amt));//! 币种及金额
            }
            else
            {
                data.put("txccy_amt1","");
            }
            pntmod.setSplitCodeNumber(data,
                    bopGroup.getVrf().getTxcode2(), "txcode2"); //! 交易编码2
            if(!MdaUtils.isEmpty(bopGroup.getVrf().getTxcode2()))
            {
                BigDecimal tc2_mt = new BigDecimal(0);;
                if(!MdaUtils.isEmpty(bopGroup.getVrf().getTc2amt())){
                    tc2_mt = bopGroup.getVrf().getTc2amt();
                }
                data.put("txccy_amt2",
                        pntmod.getFormatedMoney( bopGroup.getBas().getTxccy(),tc2_mt));//! 币种及金额2
            }
            else
            {
                data.put("txccy_amt2","");
            }
            pntmod.setCodetableData(data, bopGroup.getVrf().getIsref(),
                    "isref", "Y:N");												//本笔贷款是否为保税货物下付款：是、否  isref_y  isref_n
            data.put("contrno",bopGroup.getVrf().getContrno());//合同号contrno
            data.put("invoino",bopGroup.getVrf().getInvoino());//发票号invoino
            data.put("regno",bopGroup.getVrf().getRegno()); //外汇局批件号/备案表号/业务编号regno

            data.put("rptdate",Utils.fmtDate(bopGroup.getVrf().getRptdate(), "yyyy-MM-dd"));//购汇汇率   exrate
            //等值人民币  rmbval
            //手续费  oprcost
            //电报费 telcost
            //合计totalcost
            //支付费用方式（现金、支票、账户） "A:B:C" pay_A~C
            data.put("crtuser",bopGroup.getVrf().getCrtuser());//申请人姓名
            data.put("inptelc",bopGroup.getVrf().getInptelc());
            //银行签章（核准人签字、日期）
            //核印？？
            //经办？？？
            //复核？？
            data.put("tx1rem",bopGroup.getVrf().getTxrem());
            data.put("tx2rem",bopGroup.getVrf().getTx2rem());
        }

        pntmod.setCodetableData(data, bopGroup.getBas().getMethod(),
                "method", "T:D:M");

        //购汇汇率   exrate
            if(bopGroup.getBas().getExrate().compareTo(zero) <= 0){
                data.put("exrate","");
            }else
            {
                BigDecimal exrateStr = bopGroup.getBas().getExrate();
                data.put("exrate", exrateStr.toPlainString());
            }


        
        return data;
    }

    @Override
    public Map<String, Object> getInputMapDataForTrn(Dbegrp bopGroup, Date credate, String alonflg, BopTrnBo bopTrnBo) {
        //先打印申报数据
        Map<String, Object> data = this.getInputMapData(bopGroup,credate,alonflg);
        //补充打印业务信息
        //补充汇款人地址
        String orcadrblk = bopGroup.getBas().getCustnm()+"."+bopTrnBo.getBnkrem1();
        data.put("custnm",orcadrblk);

        //补充收款人地址
        if(!MdaUtils.isEmpty(bopTrnBo.getRcvbnkadr())){
            String rcvbnkadr = bopGroup.getBas().getOppuser()+ " "+bopTrnBo.getRcvbnkadr();
            data.put("oppuser",rcvbnkadr);
        }

        //收款银行名称地址
        data.put("rcvrptbnk",bopTrnBo.getBnkrem2());

        //收款行账号
        data.put("accbnk",bopTrnBo.getBnkrem3());

        //收款行及代理行名称地址
        data.put("accbnkadd",bopTrnBo.getBnkrem4());


        //收款人账号
       // data.put("oppacc",bopTrnBo.getDocdis());

        //汇款附言
        data.put("txrem",bopTrnBo.getPrbref());

        //费用承担方
        String checkedSign = pntmod.getCheckedChar();//勾选符
        String feerol = bopTrnBo.getContrno();
        if("OUR".equals(feerol)){
            data.put("tx_o",checkedSign);
        }else if("BEN".equals(feerol)){
            data.put("tx_b",checkedSign);
        }else if("SHA".equals(feerol)){
            data.put("tx_s",checkedSign);
        }

        return data;
    }

}
