package com.yem.tws.aip;

import com.yem.tws.common1.*;
//import json.JSONObject;
import com.alibaba.fastjson.JSONObject;
import kd.bos.bill.IBillWebApiPlugin;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.api.ApiResult;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;

import java.math.BigDecimal;
import java.util.*;

import static com.yem.tws.common1.JsonUtils.jsonToData;

public class CaBillAddUpdata implements IBillWebApiPlugin {

    @Override
    public ApiResult doCustomService(Map<String, Object> params) {
        List<Object> resultlist = Collections.synchronizedList(new ArrayList<>());
        boolean BollISSucces = false;
        String ErrMassage = "";
        String FID = "";
        String billno = "";
        JSONObject jsonData = null;
        try {
            jsonData = JSONObject.parseObject(JSONObject.toJSONString(params));
            if (null != jsonData) {
                String jsion = jsonData.getString("jsion");
                String entityName = jsonData.getString("entityName");
                if (jsion != null) {
                    //获取进出口标记
                    JSONObject jsonObj = JSONObject.parseObject(jsion);
                    JSONObject result = jsonObj.getJSONObject("result");
                    boolean ok = result.getBoolean("ok");
                    if (!ok) {
                        ErrMassage = "接口接收到json失败";
                        Map<String, Object> resultMap = Map(BollISSucces, FID, billno, ErrMassage);
                        resultlist.add(resultMap);
                        return ApiResult.success(resultlist);
                    }
                    JSONObject REdata = result.getJSONObject("data");
                    JSONObject preDecHeadVo = REdata.getJSONObject("preDecHeadVo");
                    String cusIEFlag = preDecHeadVo.getString("cusIEFlag");
                    String entryId = preDecHeadVo.getString("entryId");
                    String entityNumber = "";
                    if (cusIEFlag.equals("E")) {
                        entityNumber = "CusDec_E";
                    } else {
                        entityNumber = "CusDec_I";
                    }
                    QFilter qFilter = new QFilter("billno", QCP.equals, entityNumber);
                    DynamicObject[] yem_ca_billlogon_s = BusinessDataServiceHelper.load("yem_ca_billlogon",
                            "id,billno,billstatus", new QFilter[]{qFilter}, null);
                    if (yem_ca_billlogon_s != null && yem_ca_billlogon_s.length > 0) {
                        DynamicObject data = jsonToData(REdata.toString(), entityName, yem_ca_billlogon_s, entryId, preDecHeadVo);
                        if (data != null) {
                            billno = data.getString("billno");
                            if (billno != null) {
                                QFilter filter1 = new QFilter("billno", QCP.equals, billno);
                                DynamicObject simpleBill1 = BusinessDataServiceHelper.loadSingle(entityName, "id", new QFilter[]{filter1});
                                if (simpleBill1 == null) {
                                    //处理运费保费杂费
                                    data = ManageYBZ(data);
                                    //开票备注
//                                    data = billingnote(data);
                                    OperationResult Operate5 = OperationServiceHelper.executeOperate("save", data.getDynamicObjectType().getName(), new DynamicObject[]{data}, OperateOption.create());
                                    if (Operate5.isSuccess()) {
                                        if (data.getString("yem_cusdecstatusname").equals("结关")) {
                                            data = CommonUtils.billingnote(data);
                                        }
                                    }
                                    OperationResult Operate = OperationServiceHelper.executeOperate("save",
                                            data.getDynamicObjectType().getName(), new DynamicObject[]{data},
                                            OperateOption.create());
                                    if (Operate.isSuccess()) {//保存成功
                                        ErrMassage = "同步成功，单据编号为：" + billno;
                                        BollISSucces = true;
                                        FID = data.getString("id");
                                    } else {
                                        //保存失败
                                        BollISSucces = false;
                                        ErrMassage = "单一窗口报关单保存失败！";
                                    }
                                } else {
                                    ErrMassage = "单一窗口报关单已存在单据编号为：【" + billno + "】的单据，保存失败";
                                }
                            } else {
                                ErrMassage = "关单单据注册中【" + entityName + "】单据编号为注册，保存失败";
                            }
                        } else {
                            ErrMassage = "Json转DynamicObject失败，详情请联系管理员查看日志！";
                        }
                    }
                }
                Log(BollISSucces, FID, billno, ErrMassage, jsonData);
            } else {
                ErrMassage = "获取到Json为空，获取失败";
                Log(false, FID, billno, ErrMassage, jsonData);
            }
        } catch (Exception e) {
            //获取到错误，记录错误日志
            ErrMassage = e.getMessage();
            Log(false, FID, billno, ErrMassage, jsonData);
        }
        Map<String, Object> resultMap = Map(BollISSucces, FID, billno, ErrMassage);
        resultlist.add(resultMap);
        return ApiResult.success(resultlist);
    }

    public void Log(boolean BollISSucces, String FID, String billno, String ErrMassage, JSONObject jsonData) {
        Map<String, Object> resultMap = Map(BollISSucces, FID, billno, ErrMassage);
        //记录API日志
        String opdesc = "将中国国际贸易单一窗口同步至单一窗口报关单";
        ApilogUtils.Createlog(resultMap, billno, "单一窗口报关单", opdesc, "AddCusDec", jsonData);
    }

    public Map<String, Object> Map(boolean BollISSucces, String FID, String billno, String ErrMassage) {
        String description = "{\"data\":{\"BollISSucces\":\"" + BollISSucces + "\",\"FID\":\"" + FID + "\",\"ErrMassage\": \"" + ErrMassage + "\"}}";
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("description", description);
        resultMap.put("result", BollISSucces);
        resultMap.put("billno", billno);
        return resultMap;
    }

    /**
     * 处理运保杂
     */
    public DynamicObject ManageYBZ(DynamicObject yem_ca_billlogon) {
        if (yem_ca_billlogon != null) {
            //金额合计
            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 = exchangerate(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_qty1");//数量
                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);
        }
        return yem_ca_billlogon;
    }

    public BigDecimal exchangerate(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) {
            BigDecimal yem_feecurrexchangerate = exchangerate(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;
    }



}
