package com.yem.tws.timingtask;

import com.yem.tws.common1.BigDecimalUtils;
import com.yem.tws.common1.DateUtils;
import com.yem.tws.common1.JsonUtils;
import com.yem.tws.common1.StringUtils;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;

import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;

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

/**
 * @author zhouc
 * @date 2023/6/13 12:02
 * @className CusDecTask
 * @description 单一窗口报关单定时任务
 */
public class CusDecTask extends AbstractTask {
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        Log log = LogFactory.getLog(CusDecTask.class);
        QFilter qFilter = new QFilter("yem_exchangerate", QCP.equals, 0)
                .and(new QFilter("yem_fiedatets", QCP.equals, null));
        DynamicObject[] yem_ca_billlogon_s = BusinessDataServiceHelper.load("yem_ca_cusdec",
                "id,billno,yem_fobtotal,yem_usdfobtotal,yem_othercutotal,yem_othermarkname,yem_othercubase,yem_otherrate" +
                        ",yem_insurcurtotal,yem_insurrate,yem_insurcurbase,yem_insurmarkname" +
                        ",yem_feecurrtotal,yem_feerate,yem_feecurrbase,yem_feemarkname,yem_sumlocdecltotal,yem_currencybase" +
                        ",yem_exchangerate,yem_fiedatets,yem_sumlocdecltotal,yem_sumdecltotal," +
                        ",yem_ca_cddetailedentry.yem_gqty,yem_ca_cddetailedentry.yem_decltotal,yem_ca_cddetailedentry.yem_fobamout" +
                        ",yem_ca_cddetailedentry.yem_fobprice,yem_ca_cddetailedentry.yem_usdfob,yem_grosswt" +
                        ",yem_ca_cddetailedentry.yem_rmbdecltotal,yem_usdcurrency,yem_entryid",
                new QFilter[]{qFilter}, null);
        int jg = 0;
        if (yem_ca_billlogon_s.length > 0) {
            for (int i = 0; i < yem_ca_billlogon_s.length; i++) {
                DynamicObject yem_ca_billlogon = yem_ca_billlogon_s[i];
                if (yem_ca_billlogon != null) {
                    yem_ca_billlogon.set("yem_usdcurrency", JsonUtils.getObjDynamicObject("bd_currency", "number", "USD"));
                    //金额合计
                    BigDecimal yem_sumdecltotal = yem_ca_billlogon.getBigDecimal("yem_sumdecltotal");
                    //金额本位币
                    BigDecimal yem_sumlocdecltotal = yem_ca_billlogon.getBigDecimal("yem_sumlocdecltotal");
                    //进出口日期
                    Date yem_fiedatets = yem_ca_billlogon.getDate("yem_fiedatets");
                    BigDecimal yem_grosswt = yem_ca_billlogon.getBigDecimal("yem_grosswt");
                    BigDecimal yem_exchangerate = yem_ca_billlogon.getBigDecimal("yem_exchangerate");//报关汇率
                    if (yem_exchangerate.equals(BigDecimal.ZERO)) {
                        //报关币别
                        DynamicObject yem_currencybase = yem_ca_billlogon.getDynamicObject("yem_currencybase");
                        if (yem_currencybase != null) {
                            yem_exchangerate = Setexchangerate(yem_fiedatets, yem_currencybase);
                            yem_sumlocdecltotal = yem_exchangerate.multiply(yem_sumdecltotal);
                            yem_ca_billlogon.set("yem_sumlocdecltotal", yem_sumlocdecltotal);
                        }
                    }
                    //当前单据运费保费杂费汇总
                    BigDecimal SumYBZ = BigDecimal.ZERO;
                    //运费标志
                    String yem_feemarkname = yem_ca_billlogon.getString("yem_feemarkname").toString();
                    if (StringUtils.isNotEmpty(yem_feemarkname) && StringUtils.isNotNull(yem_feemarkname)) {
                        DynamicObject yem_feecurrbase = yem_ca_billlogon.getDynamicObject("yem_feecurrbase");//运费币别
                        if (yem_feecurrbase != null) {
                            BigDecimal yem_feerate = yem_ca_billlogon.getBigDecimal("yem_feerate");//运费/率
                            BigDecimal feemarkAmt = YBZAmt(yem_feemarkname, yem_fiedatets, yem_feerate, yem_feecurrbase, yem_sumdecltotal, yem_grosswt);
                            SumYBZ = SumYBZ.add(feemarkAmt);
                            yem_ca_billlogon.set("yem_feecurrtotal", feemarkAmt);//运费总额（RMB）
                        }
                    }
                    //保费标志
                    String yem_insurmarkname = yem_ca_billlogon.getString("yem_insurmarkname").toString();
                    if (StringUtils.isNotEmpty(yem_insurmarkname) && StringUtils.isNotNull(yem_insurmarkname)) {
                        DynamicObject yem_insurcurbase = yem_ca_billlogon.getDynamicObject("yem_insurcurbase");//保费币别
                        if (yem_insurcurbase != null) {
                            BigDecimal yem_insurrate = yem_ca_billlogon.getBigDecimal("yem_insurrate");//保费/率
                            BigDecimal feemarkAmt = YBZAmt(yem_insurmarkname, yem_fiedatets, yem_insurrate, yem_insurcurbase, yem_sumdecltotal, yem_grosswt);
                            SumYBZ = SumYBZ.add(feemarkAmt);
                            yem_ca_billlogon.set("yem_insurcurtotal", feemarkAmt);//保费总额（RMB）
                        }
                    }
                    //杂费标志
                    String yem_othermarkname = yem_ca_billlogon.getString("yem_othermarkname").toString();
                    if (StringUtils.isNotEmpty(yem_othermarkname) && StringUtils.isNotNull(yem_othermarkname)) {
                        DynamicObject yem_othercubase = yem_ca_billlogon.getDynamicObject("yem_othercubase");//保费币别
                        BigDecimal yem_otherrate = yem_ca_billlogon.getBigDecimal("yem_otherrate");//杂费/率
                        BigDecimal feemarkAmt = YBZAmt(yem_othermarkname, yem_fiedatets, yem_otherrate, yem_othercubase, yem_sumdecltotal, yem_grosswt);
                        SumYBZ = SumYBZ.add(feemarkAmt);
                        yem_ca_billlogon.set("yem_othercutotal", feemarkAmt);//运费总额（RMB）
                    }
                    BigDecimal yem_fobtotal = BigDecimal.ZERO;
                    BigDecimal yem_fobtotalusd = BigDecimal.ZERO;
                    DynamicObjectCollection yem_ca_cddetailedentry = yem_ca_billlogon.getDynamicObjectCollection("yem_ca_cddetailedentry");
                    for (int j = 0; j < yem_ca_cddetailedentry.size(); j++) {
                        BigDecimal yem_fobamout = BigDecimal.ZERO;
                        BigDecimal yem_fobusd = BigDecimal.ZERO;
                        DynamicObject cddetailedentry = yem_ca_cddetailedentry.get(j);
                        BigDecimal yem_gqty = cddetailedentry.getBigDecimal("yem_gqty");//数量
                        BigDecimal yem_decltotal = cddetailedentry.getBigDecimal("yem_decltotal");//分录总额
                        cddetailedentry.set("yem_rmbdecltotal", yem_decltotal.multiply(yem_exchangerate));//分录总额本位币
                        if (SumYBZ.equals(BigDecimal.ZERO)) {
                            yem_fobamout = yem_decltotal.multiply(yem_exchangerate).setScale(2, BigDecimal.ROUND_HALF_UP);//FOB总价(RMB)
                            cddetailedentry.set("yem_fobamout", yem_fobamout);
                            if(!yem_gqty.equals(BigDecimal.ZERO)){
                                cddetailedentry.set("yem_fobprice", yem_fobamout.divide(yem_gqty, 10, BigDecimal.ROUND_UP));//FOB单价(RMB)
                            }
                            if((BigDecimal.ZERO).compareTo(yem_exchangerate) != 0) {
                                yem_fobusd = yem_fobamout.divide(yem_exchangerate, 10, BigDecimal.ROUND_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
                            }
                            cddetailedentry.set("yem_usdfob", yem_fobusd);
                        } else {
                            BigDecimal bl = yem_decltotal.divide(yem_sumdecltotal, 10, BigDecimal.ROUND_UP);
                            BigDecimal ybzrmb = SumYBZ.multiply(bl);
                            yem_fobamout = yem_decltotal.multiply(yem_exchangerate).subtract(ybzrmb).setScale(2, BigDecimal.ROUND_HALF_UP);
                            if((BigDecimal.ZERO).compareTo(yem_exchangerate) != 0) {
                                yem_fobusd = yem_fobamout.divide(yem_exchangerate, 10, BigDecimal.ROUND_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
                            }
                            cddetailedentry.set("yem_fobamout", yem_fobamout);
                            if(!yem_gqty.equals(BigDecimal.ZERO)){
                                cddetailedentry.set("yem_fobprice", yem_fobamout.divide(yem_gqty, 10, BigDecimal.ROUND_UP));//FOB单价(RMB)
                            }
                            cddetailedentry.set("yem_usdfob", yem_fobusd);
                        }
                        yem_fobtotal = yem_fobtotal.add(yem_fobamout);
                        yem_fobtotalusd = yem_fobtotalusd.add(yem_fobusd);
                    }
                    yem_ca_billlogon.set("yem_fobtotal", yem_fobtotal);
                    yem_ca_billlogon.set("yem_usdfobtotal", yem_fobtotalusd);
                    //调用保存
                    OperationResult Operate = OperationServiceHelper.executeOperate("save",
                            yem_ca_billlogon.getDynamicObjectType().getName(),
                            new DynamicObject[]{yem_ca_billlogon}, OperateOption.create());
                    if (Operate.isSuccess()) {
                        String entryid = yem_ca_billlogon.getString("yem_entryid");
                        log.info("【"+new Date()+"】更新【"+entryid+"】成功！");
                    }
                }
            }
        }
    }

    public BigDecimal Setexchangerate(Date yem_fiedatets, DynamicObject yem_currencybase) {
        BigDecimal exchangerate = BigDecimal.ZERO;
        if (yem_currencybase != null) {
            Date Min = DateUtils.getMinMonthDate(yem_fiedatets);
            Date max = DateUtils.getMaxMonthDate(yem_fiedatets);
            QFilter filter = new QFilter("yem_date", QCP.large_equals, Min)
                    .and(new QFilter("yem_date", QCP.less_equals, max));
            //查查询字段标
            String yem_curr = yem_currencybase.getString("number");
            String Fileid = "yem_" + yem_curr.toLowerCase();//将字段标识转换为小写
            DynamicObject[] erpcurrency = BusinessDataServiceHelper.load("yem_bd_centralrate",
                    "id,name,number,yem_date," + Fileid + "",
                    new QFilter[]{filter}, "yem_date");
            if (erpcurrency != null && erpcurrency.length > 0) {
                DynamicObject yem_ca_billlogon = erpcurrency[0];
                if (yem_ca_billlogon != null) {
                    exchangerate = BigDecimalUtils.toBigDecimal(yem_ca_billlogon.getString(Fileid)).divide(BigDecimalUtils.one_handred);
                }
            }
        }
        return exchangerate;
    }

    public BigDecimal YBZAmt(String yem_feemarkname, Date yem_fiedatets, BigDecimal yem_feerate, DynamicObject yem_feecurrbase, BigDecimal yem_sumdecltotal, BigDecimal grosswt) {
        BigDecimal amt = BigDecimal.ZERO;
        if (yem_feecurrbase != null && yem_fiedatets != null) {
            BigDecimal yem_feecurrexchangerate = Setexchangerate(yem_fiedatets, yem_feecurrbase);//运费汇率
            if (yem_feemarkname.equals("单价")) {
                BigDecimal yem_grosswt = grosswt.divide(BigDecimalUtils.one_thousand);//毛重
                amt = yem_grosswt.multiply(yem_feerate).multiply(yem_feecurrexchangerate);
            } else if (yem_feemarkname.equals("率")) {
                BigDecimal feerate = yem_feerate.divide(BigDecimalUtils.one_handred);
                amt = yem_sumdecltotal.multiply(feerate).multiply(yem_feecurrexchangerate);
            } else if (yem_feemarkname.equals("总价")) {
                amt = yem_feerate.multiply(yem_feecurrexchangerate);
            }
        }
        return amt;
    }

}
