package com.yem.wm.im.delivernotice.botp;

import com.yem.wm.im.delivernotice.utils.AmountCalculation;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicProperty;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.botp.ConvertRuleElement;
import kd.bos.entity.botp.plugin.AbstractConvertPlugIn;
import kd.bos.entity.botp.plugin.args.AfterConvertEventArgs;
import kd.bos.exception.KDBizException;
import kd.bos.metadata.botp.ConvertRuleReader;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.basedata.BaseDataServiceHelper;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author zhouc
 * @date 2024/4/15 17:02
 * @className ShippingdetailsToDelivernotice
 * @description 出运明细下推发货通知单
 */
public class ShippingdetailsToDelivernotice extends AbstractConvertPlugIn {
    @Override
    public void afterConvert(AfterConvertEventArgs e) {
        String tgtName = this.getTgtMainType().getName();
        String name = this.getSrcMainType().getName();
        ExtendedDataEntity[] findByEntityKeys = e.getTargetExtDataEntitySet().FindByEntityKey(tgtName);
        Map<String, DynamicProperty> fldProperties = e.getFldProperties();
        for (ExtendedDataEntity findByEntityKey : findByEntityKeys) {
            DynamicObject dataEntity = findByEntityKey.getDataEntity();
            //核心单据id
            long yem_corebillid = dataEntity.getLong("yem_corebillid");
            QFilter qFilter = new QFilter("id", QCP.equals, yem_corebillid);
            qFilter.and(new QFilter("yem_billtype.number", QCP.equals, "yem_es_salesorder_PJ")
                    .or(new QFilter("yem_billtype.number", QCP.equals, "yem_es_salesorder_nmpj")));
            qFilter.and(new QFilter("yem_billbusstype.number", QCP.not_equals, "BBT-2"));
            qFilter.and(new QFilter("yem_fundusetype", QCP.equals, "B"));
            qFilter.and(new QFilter("yem_accfunddetail.yem_debcredtype.number", QCP.equals, "JDJLX-0003"));
            DynamicObject billType = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "id", qFilter.toArray());
            if (billType != null) {
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(yem_corebillid, "yem_es_salesorder");
                String msg = "当前单据对应的合同【"+dynamicObject.getString("billno")+"】不满足使用单据转换【"+getBOTPName("1797887963242168320")+"】，" +
                        "请手动选择【"+getBOTPName("1928929957191371776")+"】后重试！";
                throw  new KDBizException(msg);
            }
            fillWithExRate(dataEntity);
            setTaxRate(dataEntity);
            AmountCalculation.Amount(dataEntity);
        }
    }

    /**
     * 根据当前日期获取最新汇率
     * @param dataEntity
     */
    private void fillWithExRate(DynamicObject dataEntity) {
        long currency = dataEntity.getLong("yem_currency.id");//结算币别
        long currencybase = dataEntity.getLong("yem_currencybase.id");//本位币
        long exratetable = dataEntity.getLong("yem_exratetable.id");//汇率表
        if (YEM.isNotEmpty(currency) && YEM.isNotEmpty(currencybase) && YEM.isNotEmpty(exratetable)) {
            if (currencybase == currency) {
                dataEntity.set("yem_exrate", BigDecimal.ONE);
                return;
            }
            BigDecimal exchangeRate = BaseDataServiceHelper.getExchangeRate(exratetable, currency, currencybase, new Date());
            dataEntity.set("yem_exrate", exchangeRate);
        }


    }

    /**
     * 不报关 税率13%；
     * 报关  退税率为0  税率13%；
     * 报关  退税率不为0  税率0%；
     * @param dataEntity
     */
    private void setTaxRate(DynamicObject dataEntity) {
        String isdeclare = dataEntity.getString("yem_isdeclare");
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        DynamicObject taxrate13 = BusinessDataServiceHelper.loadSingle("bd_taxrate", new QFilter[]{new QFilter("number", QCP.equals, "V13")});
        DynamicObject taxrate0 = BusinessDataServiceHelper.loadSingle("bd_taxrate", new QFilter[]{new QFilter("number", QCP.equals, "V0")});
        for (DynamicObject dynamicObject : collection) {
            // 报关
            if ("A".equals(isdeclare)) {
                BigDecimal degrate = dynamicObject.getBigDecimal("yem_degrate");
                if (degrate.compareTo(BigDecimal.ZERO) == 0) {
                    dynamicObject.set("yem_taxrateid", taxrate13);
                    dynamicObject.set("yem_taxrate", new BigDecimal("13"));
                } else {
                    dynamicObject.set("yem_taxrateid", taxrate0);
                    dynamicObject.set("yem_taxrate", new BigDecimal("0"));
                }
            }

            // 不报关
            if ("B".equals(isdeclare)) {
                dynamicObject.set("yem_taxrateid", taxrate13);
                dynamicObject.set("yem_taxrate", new BigDecimal("13"));
            }
        }
    }

    /**
     * 根据BOTPid 获取转换规则名称
     *
     * @param id
     * @return
     */
    public String getBOTPName(String id) {
        String Name = "";
        ConvertRuleReader read = new ConvertRuleReader();
        List<ConvertRuleElement> convertRuleElements = read.loadRules("yem_shippingdetails", "yem_es_delivernotice");
        if (convertRuleElements.size() > 0) {
            for (int i = 0; i < convertRuleElements.size(); i++) {
                ConvertRuleElement convertRuleElement = convertRuleElements.get(i);
                String botpid = convertRuleElement.getId();
                if (botpid.equals(id)) {
                    Name = String.valueOf(convertRuleElement.getName());
                }
            }
        }
        return Name;
    }
}
