package yem.wmc.ca.api;

import com.alibaba.fastjson.JSONObject;
import yem.wmc.ca.utils.*;
//import json.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.operation.OperationServiceHelper;
import org.jetbrains.annotations.NotNull;
import yem.wmc.ca.utils.ApilogUtils;
import yem.wmc.ca.utils.CommonUtils;
import yem.wmc.ca.utils.DateUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;



/**
 * @author zhouc
 * @date 2024/4/9 19:51
 * @className CaBillAddUpdata
 * @description 单一窗口升级版接口
 */
@ApiController(value = "CaBillAddUpdata", desc = "创建单一窗口报关单")
public class CaBillAddUpdata {
    @ApiPostMapping("/CaBillAddUpdata")
    public CustomApiResult<Object> cusdecAddUpdata(@NotNull @ApiParam("入参") String jsion,
                                                   @NotNull @ApiParam("单据标识") String entityName,
                                                   @NotNull @ApiParam("单据类型") String setmeal) throws IOException {
        List<Object> resultlist = Collections.synchronizedList(new ArrayList<>());
        boolean BollISSucces = false;
        String ErrMassage = "", entryId = "", entityNumber = "", FID = "", billno = "";
        JSONObject jsonData = new JSONObject();
        jsonData.put("jsion", jsion);
        jsonData.put("entityName", entityName);
        jsonData.put("setmeal", setmeal);
        JSONObject REdata = null;
        JSONObject preDecHeadVo = null;
        try {
            if (jsion != null) {
                if (setmeal.equals("A")) {
                    String Josn = CommonUtils.XMLTOJosn(jsion);
                    JSONObject jsonObj = JSONObject.parseObject(Josn);
                    if (jsonObj.containsKey("DEC_RESULT")) {
                        JSONObject decResult = jsonObj.getJSONObject("DEC_RESULT");
                        String CUS_CIQ_NO = decResult.getString("CUS_CIQ_NO");
                        QFilter qFilter = new QFilter("yem_spdecseqno", QCP.equals, CUS_CIQ_NO);
                        DynamicObject yem_ca_cusdec = BusinessDataServiceHelper.loadSingle("yem_ca_cusdec",
                                "id,billno,billstatus", new QFilter[]{qFilter});
                        if (yem_ca_cusdec != null) {
                            DynamicObject cusdec = setCusReceipt(yem_ca_cusdec, jsonObj);
                            OperationResult Operate = OperationServiceHelper.executeOperate("save",
                                    cusdec.getDynamicObjectType().getName(), new DynamicObject[]{cusdec},
                                    OperateOption.create());
                            if (Operate.isSuccess()) {//保存成功
                                billno = cusdec.getString("billno");
                                ErrMassage = "同步成功，单据编号为：" + billno;
                                BollISSucces = true;
                                FID = cusdec.getString("id");
                            } else {
                                //保存失败
                                BollISSucces = false;
                                ErrMassage = "单一窗口报关单保存失败！";
                            }
                        } else {
                            ErrMassage = "未获取到报关统一编码为；【" + CUS_CIQ_NO + "】的报关单！";
                            Map<String, Object> resultMap = Map(BollISSucces, FID, billno, ErrMassage);
                            resultlist.add(resultMap);
                            return CustomApiResult.success(resultlist);
                        }
                    } else {
                        REdata = jsonObj.getJSONObject("DecMessage");
                        preDecHeadVo = (jsonObj.getJSONObject("DecMessage")).getJSONObject("DecHead");
                        String cusIEFlag = (jsonObj.getJSONObject("DecMessage")).getJSONObject("DecHead").getString("IEFlag");
                        entryId = preDecHeadVo.getString("EntryId");
                        if (cusIEFlag.equals("E")) {
                            entityNumber = "CusDec_Exml";
                        } else {
                            entityNumber = "CusDec_Ixml";
                        }
                    }
                } else {
                    //获取进出口标记
                    JSONObject jsonObj = JSONObject.parseObject(jsion);
                    JSONObject result = jsonObj.getJSONObject("result");
                    REdata = result.getJSONObject("data");
                    preDecHeadVo = REdata.getJSONObject("preDecHeadVo");
                    String cusIEFlag = preDecHeadVo.getString("cusIEFlag");
                    entryId = preDecHeadVo.getString("entryId");
                    if (cusIEFlag.equals("E")) {
                        entityNumber = "CusDec_E";
                    } else {
                        entityNumber = "CusDec_I";
                    }
                }
                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, 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 = JsonUtils.jsonToData(REdata.toString(), entityName, yem_ca_billlogon_s, entryId, preDecHeadVo);
                        if (data != null) {
                            data.set("yem_setmeal", setmeal);
                            //处理运费保费杂费
                            if (setmeal.equals("C") || setmeal.equals("D")) {
                                //关务管理系统参数
                                Map map = CommonUtils.getcaParameter(data.getLong("org.id"), "yem_ca_cusdec");
                                if (map.size() > 0) {
                                    data = CommonUtils.ManageYBZ(data, map);
                                }
                                else{
                                    ErrMassage = "组织编码为【" + data.getString("org.number") + "】的组织为获取到对应的系统参数";
                                    return CustomApiResult.fail("502", ErrMassage);
                                }
                            }
                            OperationResult Operate = OperationServiceHelper.executeOperate("save",
                                    data.getDynamicObjectType().getName(), new DynamicObject[]{data},
                                    OperateOption.create());
                            if (Operate.isSuccess()) {//保存成功
                                billno = data.getString("billno");
                                ErrMassage = "同步成功，单据编号为：" + billno;
                                BollISSucces = true;
                                FID = data.getString("id");
                            } else {
                                //保存失败
                                BollISSucces = false;
                                ErrMassage = "单一窗口报关单保存失败！";
                            }
                        } else {
                            ErrMassage = "Json转DynamicObject失败，详情请联系管理员查看日志！";
                        }
                    } else {
                        ErrMassage = "未获取到【" + entityNumber + "】的单据注册信息，保存失败";
                    }
                } else {
                    ErrMassage = "单一窗口报关单已存在单据编号为：【" + entryId + "】的单据，保存失败";
                }
            } else {
                ErrMassage = "请求入参为null！";
            }
            Log(BollISSucces, 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 CustomApiResult.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;
    }

    /**
     * 处理XML报关状态
     *
     * @param jsonObj
     */
    public DynamicObject setCusReceipt(DynamicObject yem_ca_cusdec, JSONObject jsonObj) {
        JSONObject decResult = jsonObj.getJSONObject("DEC_RESULT");
        DynamicObject cusdec = BusinessDataServiceHelper.loadSingle(yem_ca_cusdec.getLong("id"), "yem_ca_cusdec");
        if (cusdec != null) {
            DynamicObjectCollection yem_ca_cdstatusentry = cusdec.getDynamicObjectCollection("yem_ca_cdstatusentry");
            DynamicObject entry = yem_ca_cdstatusentry.addNew();
            entry.set("yem_spdecseqno_s", decResult.getString("CUS_CIQ_NO"));//统一编号
            entry.set("yem_entryid_s", decResult.getString("ENTRY_ID"));//海关编号
            entry.set("yem_channel", decResult.getString("CHANNEL"));//回执状态
            entry.set("yem_note", decResult.getString("NOTE"));//回执详细信息
            String I_E_DATE = decResult.getString("I_E_DATE");
            if (I_E_DATE.length() > 0) {
                if (StringUtils.isNotEmpty(I_E_DATE) && I_E_DATE.indexOf("-") != -1) {
                    entry.set("yem_iedate", DateUtils.formatDate(I_E_DATE, "yyyy-MM-dd"));//进出口日期
                } else if (StringUtils.isNotEmpty(I_E_DATE) && I_E_DATE.indexOf("-") == -1 && !I_E_DATE.contains("AM") && !I_E_DATE.contains("PM")) {
                    entry.set("yem_iedate", DateUtils.formatDate(I_E_DATE, "yyyyMMdd"));
                } else if (StringUtils.isNotEmpty(I_E_DATE) && JsonUtils.CheckFormat(I_E_DATE)) {
                    entry.set("yem_iedate", DateUtils.formatDate(I_E_DATE, "yyyy-MM-dd HH:mm:ss"));
                } else if (StringUtils.isNotEmpty(I_E_DATE) && I_E_DATE.indexOf(",") != -1 && (I_E_DATE.contains("AM") || I_E_DATE.contains("PM"))) {
                    entry.set("yem_iedate", DateUtils.formatDateLocale(I_E_DATE, "MMM dd, yyyy hh:mm:ss"));
                }
            }
            try {
                entry.set("yem_noticedate", StringtoDate(decResult.getString("NOTICE_DATE")));//回执时间
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String channel = CusReceipt.GetDecStatusName(decResult.getString("CHANNEL"));
            cusdec.set("yem_cusdecstatusname", channel);
            if (decResult.getString("CHANNEL").equals("R")) {
                if (StringUtils.isNotEmpty(I_E_DATE) && I_E_DATE.indexOf("-") != -1) {
                    cusdec.set("yem_fiedatets", DateUtils.formatDate(I_E_DATE, "yyyy-MM-dd"));//进出口日期
                } else if (StringUtils.isNotEmpty(I_E_DATE) && I_E_DATE.indexOf("-") == -1 && !I_E_DATE.contains("AM") && !I_E_DATE.contains("PM")) {
                    cusdec.set("yem_fiedatets", DateUtils.formatDate(I_E_DATE, "yyyyMMdd"));
                } else if (StringUtils.isNotEmpty(I_E_DATE) && JsonUtils.CheckFormat(I_E_DATE)) {
                    cusdec.set("yem_fiedatets", DateUtils.formatDate(I_E_DATE, "yyyy-MM-dd HH:mm:ss"));
                } else if (StringUtils.isNotEmpty(I_E_DATE) && I_E_DATE.indexOf(",") != -1 && (I_E_DATE.contains("AM") || I_E_DATE.contains("PM"))) {
                    cusdec.set("yem_fiedatets", DateUtils.formatDateLocale(I_E_DATE, "MMM dd, yyyy hh:mm:ss"));
                }
            }
        }
        return cusdec;
    }

    public Date StringtoDate(String dateString) throws ParseException {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.CHINA);
        Date date = format.parse(dateString);
        Long l = date.getTime();
        Date d1 = new Date(l + 1000L);
        return d1;
    }
}
