package yem.wmc.ca.api;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.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.basedata.BaseDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import org.jetbrains.annotations.NotNull;
import yem.wmc.ca.utils.*;

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

/**
 * 同步单一窗口报关单单据状态
 */
@ApiController(value = "CusReceipt", desc = "更新报关单状态")
public class CusReceipt {
    @ApiPostMapping("/CusReceipt")
    public CustomApiResult<Object> cusdecCusReceipt(@NotNull @ApiParam("入参") String jsion,
                                                    @NotNull @ApiParam("单据类型") String setmeal) throws IOException {
        List<Object> resultlist = Collections.synchronizedList(new ArrayList<>());
        boolean BollISSucces = false;
        JSONObject jsonChildrenObject = new JSONObject();
        JSONArray jsonFieldsArray = new JSONArray();
        String ErrMassage = StringUtils.getEmpty();
        JSONObject jsonData = new JSONObject();
        jsonData.put("jsion", jsion);
//        jsonData.put("entityName", entityName);
        jsonData.put("setmeal", setmeal);
        try {
            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);//申报状态编码
                            }
                            //处理运费保费杂费
                            if (setmeal.equals("C") || setmeal.equals("D")) {
                                //关务管理系统参数
                                Map map = CommonUtils.getcaParameter(simpleBill.getLong("org.id"), "yem_ca_cusdec");
                                if (map.size() > 0) {
                                    simpleBill = CommonUtils.ManageYBZ(simpleBill, map);
                                } else {
                                    ErrMassage = "组织编码为【" + simpleBill.getString("org.number") + "】的组织为获取到对应的系统参数";
                                    return CustomApiResult.fail("502", ErrMassage);
                                }
                            }
                            //保存单据
                            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 CustomApiResult.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) {
        BigDecimal sum = simpleBill.getBigDecimal("yem_sumdecltotal");//金额合计
        if (simpleBill != null) {
            Map map = CommonUtils.getcaParameter(simpleBill.getLong("org.id"), "yem_ca_cusdec");
            if (map.containsKey("yem_exchangetype")) {
                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));
                //查查询字段标识
                DynamicObject creatorDObj = simpleBill.getDynamicObject("yem_currencybase");
                String yem_curr = creatorDObj.getString("number");
                String Fileid = "yem_" + yem_curr.toLowerCase();//将字段标识转换为小写
                DynamicObject[] erpcurrency = BusinessDataServiceHelper.load("yem_ca_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));//汇率赋值
                    }
                }
            } else {
                LinkedHashMap yem_exratetable = (LinkedHashMap) map.get("yem_exratetable");
                String number = yem_exratetable.get("number").toString();
                //获取汇率表
                long exchangeratetableId = CommonUtils.getexratetable(number);
                //获取本位币内码
                long localCurrencyId = CommonUtils.getcurrencyid("CNY");
                //获取原币内码
                long endCurrencyId = CommonUtils.getcurrencyid(simpleBill.getString("yem_currencybase.number"));
                if (exchangeratetableId > 0 && localCurrencyId > 0 && endCurrencyId > 0 && yem_fiedatets != null) {
                    BigDecimal exchangerate = BigDecimal.ZERO;
                    if (localCurrencyId == endCurrencyId) {
                        exchangerate = new BigDecimal(1);
                    } else {
                        exchangerate = BaseDataServiceHelper.getExchangeRate(exchangeratetableId, endCurrencyId, localCurrencyId, yem_fiedatets);
                    }
                    simpleBill.set("yem_exchangerate", exchangerate);//汇率赋值
                    simpleBill.set("yem_sumlocdecltotal", exchangerate.multiply(sum));//汇率赋值
                }
            }

        }
    }

}
