package com.yem.tws.aip;

import com.yem.tws.common1.*;
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 json.JSONArray;
//import json.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.*;

public class CusReceipt implements IBillWebApiPlugin {
    @Override
    public ApiResult doCustomService(Map<String, Object> params) {
        List<Object> resultlist = Collections.synchronizedList(new ArrayList<>());
        boolean BollISSucces = false;
        JSONObject jsonChildrenObject = new JSONObject();
        JSONArray jsonFieldsArray = new JSONArray();
        String ErrMassage = StringUtils.getEmpty();
        JSONObject jsonData = null;
        try {
            jsonData = JSONObject.parseObject(JSONObject.toJSONString(params));
            if (jsonData != null) {
                JSONArray BGD = JSONObject.parseObject(jsonData.getString("jsion")).getJSONArray("bgdList");
                for (int i = 0; i < BGD.size(); i++) {
                    JSONObject entryData = BGD.getJSONObject(i);
                    JSONArray Rows = JSONObject.parseArray(entryData.getString("rows"));
                    //根据报关单号查询当前单据id
                    QFilter filter1 = new QFilter("billno", QCP.equals, entryData.getString("BGDH"));
                    DynamicObject date = BusinessDataServiceHelper.loadSingle("yem_ca_cusdec", "id", new QFilter[]{filter1});//单一窗口报关单
                    if (date != null) {
                        //根据ID获取整个单据数据
                        DynamicObject simpleBill = BusinessDataServiceHelper.loadSingle(date.get("id"), "yem_ca_cusdec");
                        if (simpleBill != null) {
                            DynamicObjectCollection yem_ca_cdstatusentry = simpleBill.getDynamicObjectCollection("yem_ca_cdstatusentry");//报关状态
                            String iEDate = StringUtils.getEmpty(), cusDecStatusName = StringUtils.getEmpty(), cusDecStatus = StringUtils.getEmpty();
                            String DeciEDate = StringUtils.getEmpty(), DecStatusName = StringUtils.getEmpty(), DecStatus = StringUtils.getEmpty();
                            for (int j = 0; j < Rows.size(); j++) {

                                JSONObject RowsData = Rows.getJSONObject(j);


                                QFilter filter_S = new QFilter("yem_ca_cdstatusentry.yem_cusretseqno", QCP.equals, RowsData.getString("cusretseqno"));
                                DynamicObject simpleBill1_S = BusinessDataServiceHelper.loadSingle("yem_ca_cusdec", "id", new QFilter[]{filter_S});// 业务单元
                                if (simpleBill1_S == null) {


                                    DynamicObject entry = yem_ca_cdstatusentry.addNew();  //新增数据,
                                    entry.set("yem_cusretseqno", RowsData.getString("cusretseqno"));//回执号
                                    entry.set("yem_spdecseqno_s", RowsData.getString("spDecSeqNo"));//统一编号
                                    entry.set("yem_entryid_s", RowsData.getString("customsno"));//海关编号
                                    entry.set("yem_channel", RowsData.getString("channel"));//回执状态
                                    entry.set("yem_note", RowsData.getString("note"));//回执详细信息
                                    //日期处理
                                    String FiEDate = RowsData.getString("iEDate");
                                    if (!FiEDate.equals("0001/1/1 0:00:00") && !FiEDate.equals("0000/0/0 0:00:00") && !FiEDate.isEmpty()) {
                                        entry.set("yem_iedate", DateUtils.formatDate(FiEDate, "yyyy/MM/dd"));//出口日期

                                    }
                                    entry.set("yem_noticedate", DateUtils.formatDate(RowsData.getString("noticeDate"), "yyyy/MM/dd HH:mm:ss"));//回执时间
                                    //特殊处理
                                    if (RowsData.getString("channel").equals("R")) {
                                        DeciEDate = RowsData.getString("iEDate");
                                        DecStatusName = "结关";
                                        DecStatus = "10";
                                    }
                                    if (j == Rows.size() - 1) {
                                        iEDate = RowsData.getString("iEDate");
                                        cusDecStatusName = GetDecStatusName(RowsData.getString("channel"));
                                        cusDecStatus = "999";
                                    }

                                }
                            }
                            //更新申报状态以及进出口日期
                            if (StringUtils.isNotEmpty(DecStatusName)) {
                                if (!DeciEDate.equals("0001/1/1 0:00:00") && !DeciEDate.equals("0000/0/0 0:00:00") && !DeciEDate.isEmpty()) {
                                    simpleBill.set("yem_fiedatets", DateUtils.formatDate(DeciEDate, "yyyy/MM/dd"));//进出口日期
                                    Setexchangerate(DateUtils.formatDate(DeciEDate, "yyyy/MM/dd"),simpleBill);
                                }
                                simpleBill.set("yem_cusdecstatusname", DecStatusName);//申报状态名称
                                simpleBill.set("yem_cusdecstatus", DecStatus);//申报状态编码
                            } else {
                                if (!iEDate.equals("0001/1/1 0:00:00") && !iEDate.equals("0000/0/0 0:00:00") && !iEDate.isEmpty()) {
                                    simpleBill.set("yem_fiedatets", DateUtils.formatDate(iEDate, "yyyy/MM/dd"));//进出口日期
                                    Setexchangerate(DateUtils.formatDate(iEDate, "yyyy/MM/dd"),simpleBill);
                                }
                                simpleBill.set("yem_cusdecstatusname", cusDecStatusName);//申报状态名称
                                simpleBill.set("yem_cusdecstatus", cusDecStatus);//申报状态编码
                            }
                            //处理运费保费杂费
                            simpleBill = ManageYBZ(simpleBill);
                            OperationResult Operate5 = OperationServiceHelper.executeOperate("save", simpleBill.getDynamicObjectType().getName(), new DynamicObject[]{simpleBill}, OperateOption.create());
                            if (Operate5.isSuccess()) {
                                if (simpleBill.getString("yem_cusdecstatusname").equals("结关")) {
                                    simpleBill = CommonUtils.billingnote(simpleBill);
                                }
                            }
                            //保存单据
                            OperationResult Operate = OperationServiceHelper.executeOperate("save", simpleBill.getDynamicObjectType().getName(), new DynamicObject[]{simpleBill}, OperateOption.create());
                            if (Operate.isSuccess()) {
                                //构建返回信息 获取当前单据报关状态信息回执号 用于更新
                                JSONObject BGDObject = new JSONObject();
                                JSONArray FieldsArray = new JSONArray();
                                DynamicObjectCollection cdstatusentry = simpleBill.getDynamicObjectCollection("yem_ca_cdstatusentry");//报关状态
                                for (int k = 0; k < cdstatusentry.size(); k++) {
                                    DynamicObject entry = cdstatusentry.get(k);
                                    String yem_cusretseqno = entry.getString("yem_cusretseqno");
                                    JSONObject jsonFieldObject = new JSONObject();
                                    jsonFieldObject.put("FcusRetSeqNo", yem_cusretseqno);
                                    FieldsArray.add(jsonFieldObject);
                                }
                                BollISSucces = true;
                                BGDObject.put("Data", FieldsArray);
                                BGDObject.put("AnnexId", simpleBill.get("id"));
                                BGDObject.put("BollISSucces", true);
                                BGDObject.put("ErrMassage", "同步成功，海关编号为【" + simpleBill.getString("yem_entryid") + "】");
                                jsonFieldsArray.add(BGDObject);
                            } else {
                                ErrMassage = "单一窗口报关单保存失败！";
                                jsonChildrenObject.put("ErrMassage", ErrMassage);
                                Log(BollISSucces, "", "", ErrMassage, jsonData);
                            }
                        } else {
                            ErrMassage = "ERP未获取到海关编号为:【" + entryData.getString("BGDH") + "】的单一窗口报关单对象！";
                            jsonChildrenObject.put("ErrMassage", ErrMassage);
                            Log(BollISSucces, "", "", ErrMassage, jsonData);
                        }
                    } else {
                        ErrMassage = "ERP未获取到海关编号为:【" + entryData.getString("BGDH") + "】的单一窗口报关单！";
                        jsonChildrenObject.put("ErrMassage", ErrMassage);
                        Log(BollISSucces, "", "", ErrMassage, jsonData);
                    }
                }
            } else {
                ErrMassage = "ERP未接受到Json，请求失败！";
                jsonChildrenObject.put("ErrMassage", ErrMassage);
                Log(BollISSucces, "", "", ErrMassage, jsonData);
            }
            jsonChildrenObject.put("rows", jsonFieldsArray);
        } catch (Exception e) {
            jsonChildrenObject.put("BollISSucces", BollISSucces);
            jsonChildrenObject.put("ErrMassage", e.getMessage());
            Log(BollISSucces, "", "", ErrMassage, jsonData);
        } finally {
            //记录日志
            ErrMassage = jsonChildrenObject.toJSONString();
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("description", ErrMassage);
            resultlist.add(resultMap);
            Log(BollISSucces, "", "", ErrMassage, jsonData);
        }
        return ApiResult.success(resultlist);
    }

    public void Log(boolean BollISSucces, String FID, String billno, String ErrMassage, JSONObject jsonData) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("description", ErrMassage);
        resultMap.put("result", BollISSucces);
        resultMap.put("billno", billno);
        //记录API日志
        String opdesc = "更新单一窗口报关单报关状态！";
        ApilogUtils.Createlog(resultMap, billno, "单一窗口报关单", opdesc, "UpCusDec", jsonData);
    }

    /**
     * 获取表头申报状态名称
     *
     * @param Type 申报状态编码
     * @return String
     */
    public static String GetDecStatusName(String Type) {
        String StatusName = StringUtils.getEmpty();
        if (Type.equals("L")) {
            StatusName = "海关入库";
        }
        if (Type.equals("E")) {
            StatusName = "退单";
        }
        if (Type.equals("G") || Type.equals("J")) {
            StatusName = "审结";
        }
        if (Type.equals("A") || Type.equals("D") || Type.equals("Z")) {
            StatusName = "删单";
        }
        if (Type.equals("P") || Type.equals("K") || Type.equals("W") || Type.equals("X") || Type.equals("I")) {
            StatusName = "放行";
        }
        if (Type.equals("R")) {
            StatusName = "结关";
        }
        if (Type.equals("C")) {
            StatusName = "查验通知";
        }
        return StatusName;
    }

    public void Setexchangerate(Date yem_fiedatets,DynamicObject simpleBill) {
        if(simpleBill!=null){
            if(DateUtils.formatDate(DateUtils.getData(yem_fiedatets,"yyyy-MM-dd"), "yyyy-MM-dd")
                    .equals(DateUtils.formatDate("2021-12-31", "yyyy-MM-dd"))){
                yem_fiedatets=DateUtils.formatDate("2022-01-04", "yyyy-MM-dd");
            }
            if(DateUtils.formatDate(DateUtils.getData(yem_fiedatets,"yyyy-MM-dd"), "yyyy-MM-dd")
                    .before(DateUtils.formatDate("2021-12-31", "yyyy-MM-dd"))){
                yem_fiedatets=DateUtils.formatDate("2022-01-04", "yyyy-MM-dd");
            }
            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));
            //查查询字段标识
            BigDecimal sum =simpleBill.getBigDecimal("yem_sumdecltotal");//金额合计
            DynamicObject creatorDObj = simpleBill.getDynamicObject("yem_currencybase");
            String yem_curr = creatorDObj.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){
                    BigDecimal exchangerate = BigDecimalUtils.toBigDecimal(yem_ca_billlogon.getString(Fileid)).divide(BigDecimalUtils.one_handred);
                    simpleBill.set("yem_exchangerate",exchangerate);//汇率赋值
                    simpleBill.set("yem_sumlocdecltotal",exchangerate.multiply(sum));//汇率赋值
                }
            }
        }
    }

    /**
     * 处理运保杂
     */
    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_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);
        }
        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;
    }

//    /**
//     * 开票备注
//     *
//     * @return
//     */
//    public DynamicObject billingnote(DynamicObject yem_ca_billlogon) {
//        DynamicObject yem_transmodbase = yem_ca_billlogon.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_invoicingremarks",
//                    "id,name,number",
//                    new QFilter[]{qFilter}, null);
//            if (invoicingremarks.length > 0) {
//                long InvoicingRemarksId = invoicingremarks[0].getLong("id");
//                String yem_billingnote = getRemarks(InvoicingRemarksId, yem_ca_billlogon.getLong("id"), "yem_ca_cusdec");
//                yem_ca_billlogon.set("yem_invoicingremarks", invoicingremarks[0]);
//                yem_ca_billlogon.set("yem_billingnote", yem_billingnote.trim());
//
//            }
//        }
//        return yem_ca_billlogon;
//    }
}
