package yem.wmc.ca.api;

import com.drew.lang.annotations.NotNull;
//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.metadata.form.FormMetadata;
import kd.bos.openapi.common.custom.annotation.ApiController;
import kd.bos.openapi.common.custom.annotation.ApiParam;
import kd.bos.openapi.common.custom.annotation.ApiPostMapping;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import yem.wmc.ca.utils.ApilogUtils;

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

import static yem.wmc.ca.utils.JsonUtils.jsonToData;

/**
 * @author zhouc
 * @date 2023/5/25 11:42
 * @className TaxPayment
 * @description 进口税费新增接口
 */
@ApiController(value = "TaxPayment", desc = "创建进口税费")
public class TaxPayment {
    @ApiPostMapping("/TaxPayment")
    public CustomApiResult<Object> doCustomService(@NotNull @ApiParam("入参") String jsion, @NotNull @ApiParam("单据标识") String entityName) {
        List<Object> resultlist = Collections.synchronizedList(new ArrayList<>());
        boolean BollISSucces = false;
        String ErrMassage = "",FID = "",billno = "";
        JSONObject jsonData = null;
        try {
            jsonData = JSONObject.parseObject(jsion);
            if (null != jsonData) {
                String entryId = JSONObject.parseObject(jsonData.getString("data")).getString("taxvouNo");//单据编号
                QFilter filter1 = new QFilter("billno", QCP.equals, entryId);
                DynamicObject simpleBill1 = BusinessDataServiceHelper.loadSingle(entityName, "id", new QFilter[]{filter1});
                if (simpleBill1 == null) {
                    QFilter qFilter = new QFilter("billno", QCP.equals, "taxpayment");
                    DynamicObject[] yem_ca_billlogon_s = BusinessDataServiceHelper.load("yem_ca_billlogon",
                            "id,billno,billstatus", new QFilter[]{qFilter}, null);
                    if (yem_ca_billlogon_s != null) {
                        DynamicObject data = jsonToData(jsion, entityName, yem_ca_billlogon_s, entryId, JSONObject.parseObject(jsonData.getString("data")));
                        if (data != null) {
                            OperationResult Operate = OperationServiceHelper.executeOperate("save",
                                    data.getDynamicObjectType().getName(), new DynamicObject[]{data},
                                    OperateOption.create());
                            if (Operate.isSuccess()) {//保存成功
                                billno = data.getString("billno");

                                BollISSucces = true;
                                FID = data.getString("id");
                                String taxType = data.getString("yem_taxtypename");//税费种类
                                Map<String, Object> objects = UpdateCusDec(data.getString("yem_entryid"), data.getDynamicObjectCollection("yem_taxpaydetal"), taxType);
                                ErrMassage = "同步成功，单据编号为：" + billno + "," + objects.get("ErrMassage");
                            } else {
                                //保存失败
                                ErrMassage = "进口税费保存失败！";
                            }
                        } else {
                            ErrMassage = "Json转DynamicObject失败，详情请联系管理员查看日志！";
                        }
                    } else {
                        ErrMassage = "未获取到关单注册注册编号为：【taxpayment】注册单据，Json转换失败！";
                    }
                } else {
                    ErrMassage = "进口税费已存在单据编号为：【" + entryId + "】的单据，禁止新增！";
                }
            } else {
                ErrMassage = "获取到Json为空，获取失败";

            }
        } catch (Exception e) {
            //获取到错误，记录错误日志
            ErrMassage = e.getMessage();
        } finally {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("description", ErrMassage);
            resultMap.put("result", BollISSucces);
            resultMap.put("billno", billno);
            resultMap.put("FID", FID);
            resultlist.add(resultMap);
            String opdesc = "同步进口税费ERP系统";
            ApilogUtils.Createlog(resultMap, billno, "进口税费", opdesc, "AddTaxPayment", jsonData);
        }
        return CustomApiResult.success(resultlist);
    }

    public Map<String, Object> UpdateCusDec(String FentryId, DynamicObjectCollection FTaxPayDetal, String taxType) {
        Map<String, Object> Mag = new HashMap<String, Object>();
        String ErrMassage = null, FID = null, FBillNo = null;
        String BollISSucces = "false";//是否成功
        try {
            QFilter qFilter = new QFilter("billno", QCP.equals, FentryId);
            DynamicObject[] yem_ca_billlogon_s = BusinessDataServiceHelper.load("yem_ca_cusdec",
                    "id", new QFilter[]{qFilter}, null);
            if (yem_ca_billlogon_s.length > 0) {
                int SEntLCAmt = yem_ca_billlogon_s[0].getInt("id");
                if (SEntLCAmt > 0) {
                    BigDecimal SumTaxRateAmt = BigDecimal.ZERO;
                    BigDecimal SumDutyRateAmt = BigDecimal.ZERO;
                    BigDecimal SumRegRateAmt = BigDecimal.ZERO;
                    BigDecimal SumAntidRateAmt = BigDecimal.ZERO;
                    DynamicObject StrogetranObj = BusinessDataServiceHelper.loadSingle(SEntLCAmt, "yem_ca_cusdec");
                    DynamicObjectCollection FCusDecMerge = StrogetranObj.getDynamicObjectCollection("yem_ca_cddetailedentry");//明细信息
                    if (StrogetranObj != null) {
                        for (int i = 0; i < FTaxPayDetal.size(); i++)//进口税费明细
                        {
                            String goodsNo = FTaxPayDetal.get(i).getString("yem_goodsno");//商品序号

                            for (int j = 0; j < FCusDecMerge.size(); j++)//单一窗口报关单明细
                            {
                                String gNo = FCusDecMerge.get(j).getString("yem_gno");//
                                DynamicObject FCusDecMerges = FCusDecMerge.get(j);
                                if (goodsNo.equals(gNo)) {
                                    if (taxType.equals("A"))//进口关税
                                    {
                                        FCusDecMerges.set("yem_dutyrate", FTaxPayDetal.get(i).getBigDecimal("yem_valoremrate"));//从价税率
                                        FCusDecMerges.set("yem_qtydutyrate", FTaxPayDetal.get(i).getBigDecimal("yem_qtyrate"));//从量税率
                                        FCusDecMerges.set("yem_dutydutyvalue", FTaxPayDetal.get(i).getBigDecimal("yem_dutyvalue"));//完税价格
                                        FCusDecMerges.set("yem_dutyrateamt", FTaxPayDetal.get(i).getBigDecimal("yem_tax"));//税额
                                        FCusDecMerges.set("yem_exchangerates", FTaxPayDetal.get(i).getBigDecimal("yem_exchangerate"));//外汇折算率
                                        SumDutyRateAmt = SumDutyRateAmt.add(FTaxPayDetal.get(i).getBigDecimal("yem_tax"));
                                    }
                                    if (taxType.equals("L"))//进口增值税
                                    { //增值税只有从价税率
                                        FCusDecMerges.set("yem_taxrate", FTaxPayDetal.get(i).getBigDecimal("yem_valoremrate"));//从价税率
                                        FCusDecMerges.set("yem_taxdutyvalue", FTaxPayDetal.get(i).getBigDecimal("yem_dutyvalue"));//完税价格
                                        FCusDecMerges.set("yem_taxrateamt", FTaxPayDetal.get(i).getBigDecimal("yem_tax"));//税额
                                        FCusDecMerges.set("yem_exchangerates", FTaxPayDetal.get(i).getBigDecimal("yem_exchangeRate"));//外汇折算率
                                        SumTaxRateAmt = SumTaxRateAmt.add(FTaxPayDetal.get(i).getBigDecimal("yem_tax"));
                                    }
                                    if (taxType.equals("Y"))//进口消费税
                                    {
                                        FCusDecMerges.set("yem_RegRate", FTaxPayDetal.get(i).getBigDecimal("yem_valoremRate"));//从价税率
                                        FCusDecMerges.set("yem_QtyRegRate", FTaxPayDetal.get(i).getBigDecimal("yem_qtyRate"));//从量税率
                                        FCusDecMerges.set("yem_RegdutyValue", FTaxPayDetal.get(i).getBigDecimal("yem_dutyValue"));//完税价格
                                        FCusDecMerges.set("yem_RegRateAmt", FTaxPayDetal.get(i).getBigDecimal("yem_tax"));//税额
                                        FCusDecMerges.set("yem_exchangerates", FTaxPayDetal.get(i).getBigDecimal("yem_exchangeRate"));//外汇折算率
                                        SumRegRateAmt = SumRegRateAmt.add(FTaxPayDetal.get(i).getBigDecimal("yem_tax"));
                                    }
                                    if (taxType.equals("I"))//反倾销税
                                    {
                                        FCusDecMerges.set("yem_AntidumpingRate", FTaxPayDetal.get(i).getBigDecimal("yem_valoremRate"));//从价税率
                                        FCusDecMerges.set("yem_AntidumpingValue", FTaxPayDetal.get(i).getBigDecimal("yem_dutyValue"));//完税价格
                                        FCusDecMerges.set("yem_AntidRateAmt", FTaxPayDetal.get(i).getBigDecimal("yem_tax"));//税额
                                        FCusDecMerges.set("yem_exchangerates", FTaxPayDetal.get(i).getBigDecimal("yem_exchangeRate"));//外汇折算率
                                        SumAntidRateAmt = SumAntidRateAmt.add(FTaxPayDetal.get(i).getBigDecimal("yem_tax"));
                                    }
                                }
                            }
                        }
                    }
                    ///汇总表头税额
                    //进口增值税
                    StrogetranObj.set("yem_asumtaxrateamt", SumTaxRateAmt);
                    //进口关税
                    StrogetranObj.set("yem_SumDutyRateAmt", SumDutyRateAmt);
                    //进口消费税
                    StrogetranObj.set("yem_SumRegRateAmt", SumRegRateAmt);
                    //反倾销税
                    StrogetranObj.set("yem_SumAntidRateAmt", SumAntidRateAmt);
                    OperationResult sults = OperationServiceHelper.executeOperate("save",
                            StrogetranObj.getDynamicObjectType().getName(), new DynamicObject[]{StrogetranObj},
                            OperateOption.create());
                    if (sults.isSuccess()) {
                        FBillNo = StrogetranObj.getString("BillNo");
                        FID = StrogetranObj.getString("id");
                        BollISSucces = "True";
                        ErrMassage = "更新单一窗口报关单明税费信息成功，单据编号为【" + FBillNo + "】";
                    } else {
                        BollISSucces = "false";
                        ErrMassage = sults.getMessage();
                    }
                } else {
                    BollISSucces = "false";
                    ErrMassage = "未查询到对应单一窗口报关单,单据编号为；【" + FentryId + "】报关单，同步失败";
                }

            }
        } catch (Exception ex) {
            ErrMassage = ex.getMessage();
            BollISSucces = "false";
        } finally {
            Mag.put("BollISSucces", BollISSucces);
            Mag.put("FID", FID);
            Mag.put("FBillNo", FBillNo);
            Mag.put("ErrMassage", ErrMassage);
        }
        return Mag;
    }
}
