package yem.wmc.imc.formplugin.botp;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.ExtendedDataEntitySet;
import kd.bos.entity.botp.plugin.AbstractConvertPlugIn;
import kd.bos.entity.botp.plugin.args.AfterConvertEventArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.util.StringUtils;
import java.math.BigDecimal;

/**
 * @author 金亮
 * @date 2024/5/30 10:34
 * @relevantfile 单一窗口报关单 下推 开票申请单（下推插件）
 * @description
 * @versions 1.0 测试阶段代码
 */
public class CaCusdecToOriginalBotp extends AbstractConvertPlugIn {

    @Override
    public void afterConvert(AfterConvertEventArgs e) {
        super.afterConvert(e);
        ExtendedDataEntitySet entitySet = e.getTargetExtDataEntitySet();
        ExtendedDataEntity[] entitys = entitySet.FindByEntityKey(this.getTgtMainType().toString());
        for (int i = 0; i < entitys.length; ++i) {
            ExtendedDataEntity extend = entitys[i];
            DynamicObject bill = extend.getDataEntity();
            String yemSourcebilltype = bill.getString("yem_sourcebilltype");//来源单据标识
            String yemSourcebillid = bill.getString("yem_sourcebillid");// 来源单据id

            bill.set("yem_drawer", RequestContext.get().getUserName());//开票人

            //根据销售方名称携带相关信息
            DynamicObject org = bill.getDynamicObject("org");
            if(org != null){
                org = BusinessDataServiceHelper.loadSingle(org.getPkValue(),org.getDynamicObjectType().getName());
                String name = org.getDataEntityType().getName();
                if (null != org) {
                    bill.set("yem_salertaxno", org.get("ftaxregnum")); //纳税人识别号
                    String faddress = org.getLocaleString("faddress").getLocaleValue();
                    String phone = org.getString("phone");
                    bill.set("yem_addresssell",faddress);
                    bill.set("yem_phonesell",phone);
                    bill.set("yem_saleraddr", faddress + phone);//地址及电话
                    String depositbank = org.getLocaleString("depositbank").getLocaleValue();
                    String bankaccount = org.getString("bankaccount");
                    bill.set("yem_banksell",depositbank);
                    bill.set("yem_accountsell",bankaccount);
                    bill.set("yem_salerbank", depositbank+ bankaccount); //开户行及账号
                }
            }

            //根据物料编码名称携带出物料基础资料
            DynamicObjectCollection yemImcOriginalItem = bill.getDynamicObjectCollection("yem_imc_original_item");
            for (DynamicObject dyobj : yemImcOriginalItem) {
                String yemGoodsnum = dyobj.getString("yem_goodsnum");//商品编号文本（工具）
                if (!yemGoodsnum.isEmpty()) {
                    QFilter qFilter = new QFilter("number", QCP.equals, yemGoodsnum);
                    DynamicObject material = BusinessDataServiceHelper.loadSingle("bd_material", "id", new QFilter[]{qFilter});
                    if (material != null) {
                        dyobj.set("yem_materielfield", material);
                    }
                }
            }

            //  申报状态未结关时设置发票备注
            if (yemSourcebilltype.equals("yem_ca_cusdec") && !yemSourcebillid.isEmpty()) {
                DynamicObject cusdecBill = BusinessDataServiceHelper.loadSingle(Long.valueOf(yemSourcebillid), "yem_ca_cusdec");
                if (cusdecBill != null){
                        billingnote(bill,cusdecBill);
                }
            }
        }
    }

    /**
     * 开票备注
     * @return
     */
    public void billingnote(DynamicObject bill,DynamicObject customsBill) {
        DynamicObject yem_transmodbase = bill.getDynamicObject("yem_transmodbase"); //成交方式
        if (yem_transmodbase != null) {
            QFilter qFilter = new QFilter("yem_isdefault", QCP.equals, true);
            qFilter.and(new QFilter("yem_transmodbase.name", QCP.equals, yem_transmodbase.getString("name")));
            // 根据开票备注单
            DynamicObject[] invoicingremarks = BusinessDataServiceHelper.load("yem_imc_invoicingr",
                    "id,name,number",
                    new QFilter[]{qFilter}, null);
            if (invoicingremarks.length > 0) {
                long InvoicingRemarksId = invoicingremarks[0].getLong("id");
                String yem_billingnote = getRemarks(InvoicingRemarksId, customsBill.getLong("id"), customsBill.getDataEntityType().getName());
//                bill.set("yem_invoicingremarks", invoicingremarks[0]);
                bill.set("yem_invoiceremarks", yem_billingnote.trim()); //开票备注
            }
        }
    }

    /**
     * 根据开票备注ID、报关单ID，构建开票备注
     * @param InvoicingRemarksId 开票备注ID
     * @param customsBillid 报关单ID
     * @param customsBillType 报关单标识
     * @return
     */
    public static String getRemarks(long InvoicingRemarksId,long customsBillid,String customsBillType){
        String remarks = "";
        if(0L != InvoicingRemarksId && 0L != customsBillid){
               DynamicObject customsBill = BusinessDataServiceHelper.loadSingle(customsBillid,customsBillType);
            if(null == customsBill){
                return remarks;
            }
            DynamicObject yemImcInvoicingr = BusinessDataServiceHelper.loadSingle(InvoicingRemarksId, "yem_imc_invoicingr");//开票备注
            DynamicObjectCollection yem_ir_entry_s = yemImcInvoicingr.getDynamicObjectCollection("yem_ir_entry");
                StringBuffer remarks_s = new StringBuffer();
                for(int i=0;i<yem_ir_entry_s.size();i++){
                    DynamicObject yem_ir_entry = yem_ir_entry_s.get(i);
                    //第一段
                    String yem_display = yem_ir_entry.getString("yem_display"); //开票备注显示信息
                    if(StringUtils.isNotEmpty(yem_display)){
                        remarks_s.append(yem_display);
                    }
                    String yem_delimiter = yem_ir_entry.getString("yem_delimiter");//间隔符
                    if(StringUtils.isNotEmpty(yem_delimiter)){
                        remarks_s.append(yem_delimiter);
                    }
                    String yem_customsfield = yem_ir_entry.getString("yem_customsfield");//报关单字段
                    if(StringUtils.isNotEmpty(yem_customsfield)){
                        String yem_precision = yem_ir_entry.getString("yem_precision");//精度
                        int scale = 0;
                        if(!(null == yem_precision || "".equals(yem_precision) || "无".equals(yem_precision))){
                            scale = toBigDecimal(yem_precision).intValue();
                        }
                        String val = "";
                        if(customsBill.get(yem_customsfield) instanceof BigDecimal){
                            val = toBigDecimal(customsBill.get(yem_customsfield),scale).toPlainString();
                        }else{
                            if(customsBill.get(yem_customsfield)==null){
                                remarks = "Err"+customsBill.getString("yem_entryid"); // 海关编号
                            }else{
                                val = customsBill.get(yem_customsfield).toString();
                            }
                        }
                        remarks_s.append(val);
                    }
                    //第二段
                    String yem_display1 = yem_ir_entry.getString("yem_display1"); // 开票备注显示信息
                    if(StringUtils.isNotEmpty(yem_display1)){
                        remarks_s.append(yem_display1);
                    }
                    String yem_delimiter1 = yem_ir_entry.getString("yem_delimiter1");//间隔符
                    if(StringUtils.isNotEmpty(yem_delimiter1)){
                        remarks_s.append(yem_delimiter1);
                    }
                    String yem_customsfield1 = yem_ir_entry.getString("yem_customsfield1");//报关单字段
                    if(StringUtils.isNotEmpty(yem_customsfield1)){
                        String yem_precision1 = yem_ir_entry.getString("yem_precision1");//精度
                        int scale1 = 0;
                        if(!(null == yem_precision1 || "".equals(yem_precision1) || "无".equals(yem_precision1))){
                            scale1 =toBigDecimal(yem_precision1).intValue();
                        }
                        String val1 = "";
                        if(customsBill.get(yem_customsfield1) instanceof BigDecimal){
                            val1 = toBigDecimal(customsBill.get(yem_customsfield1),scale1).toPlainString();
                        }else{
                            val1 = customsBill.get(yem_customsfield1).toString();
                        }
                        remarks_s.append(val1);
                    }
                    //第三段
                    String yem_display2 = yem_ir_entry.getString("yem_display2");
                    if(StringUtils.isNotEmpty(yem_display2)){
                        remarks_s.append(yem_display2);
                    }
                    String yem_delimiter2 = yem_ir_entry.getString("yem_delimiter2");
                    if(StringUtils.isNotEmpty(yem_delimiter2)){
                        remarks_s.append(yem_delimiter2);
                    }
                    String yem_customsfield2 = yem_ir_entry.getString("yem_customsfield2");
                    if(StringUtils.isNotEmpty(yem_customsfield2)){
                        String yem_precision2 = yem_ir_entry.getString("yem_precision2");
                        int scale2 = 0;
                        if(!(null == yem_precision2 || "".equals(yem_precision2) || "无".equals(yem_precision2))){
                            scale2 = toBigDecimal(yem_precision2).intValue();
                        }
                        String val2 = "";
                        if(customsBill.get(yem_customsfield2) instanceof BigDecimal){
                            val2 = toBigDecimal(customsBill.get(yem_customsfield2),scale2).toPlainString();
                        }else{
                            val2 = customsBill.get(yem_customsfield2).toString();
                        }
                        remarks_s.append(val2);
                    }

                    remarks_s.append("\n");
                }
                remarks = remarks_s.toString();

        }
        return remarks;
    }

    /***
     * 金额格式转换
     * @param obj
     * @return
     */
    public static BigDecimal toBigDecimal(Object obj) {
        if (obj == null)
            return BigDecimal.ZERO;
        if (obj instanceof BigDecimal)
            return (BigDecimal) obj;
        if (obj instanceof Integer)
            return new BigDecimal(((Integer) obj).toString());
        if (obj instanceof Long)
            return new BigDecimal(((Long) obj).toString());
        if (obj instanceof Double)
            return new BigDecimal(((Double) obj).doubleValue());
        if (obj.toString() == null)
            return BigDecimal.ZERO;
        String str = obj.toString().trim();
        if (str.toLowerCase().indexOf("e") > -1)
            try {
                return new BigDecimal(str);
            } catch (NumberFormatException e) {
                return new BigDecimal("0.00");
            }
        if (str.matches("^[+-]?\\d+[\\.\\d]?\\d*+$"))
            return new BigDecimal(str);
        else
            return BigDecimal.ZERO;
    }
    /*
     * 四舍五入
     */
    public static BigDecimal toBigDecimal(Object obj, int scale) {

        BigDecimal aVal = toBigDecimal(obj);
        aVal = aVal.setScale(scale, BigDecimal.ROUND_HALF_UP);
        return aVal;
    }
}
