package com.yem.or.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.utils.YEM;
import kd.bos.bill.BillShowParameter;
import kd.bos.data.BusinessDataReader;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityType;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.botp.runtime.ConvertOperationResult;
import kd.bos.entity.botp.runtime.PushArgs;
import kd.bos.entity.botp.runtime.SourceBillReport;
import kd.bos.entity.datamodel.IBillModel;
import kd.bos.entity.datamodel.IRefrencedataProvider;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.operate.OperateOptionConst;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDBizException;
import kd.bos.form.IFormView;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.mvc.FormConfigFactory;
import kd.bos.mvc.SessionManager;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.botp.ConvertServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.workflow.MessageCenterServiceHelper;
import kd.bos.util.HttpClientUtils;
import kd.bos.workflow.engine.msg.info.MessageInfo;

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

/**
 * @author zhouc
 * @date 2024/3/18 9:58
 * @className OrderApiUtils
 * @description 下单平台API公共类
 */
public class OrderApiUtils {
    public static Log log = LogFactory.getLog(OrderApiUtils.class);
    public static String ENDPOINTS = "http://10.64.113.156";
//    public static String ENDPOINT = "http://122.4.221.133:30080";
//    public static final String LOCAL_DEBUG_ENDPOINT = "http://127.0.0.1:48080";

    /**
     * 获取token
     *
     * @return 成功响应：返回map，status: success，token: accessToken
     * 失败响应：返回map，status: error，msg: 异常信息
     * 使用示例：
     * Map<String, String> resMap = OrderUtils.getToken();
     * if ("success".equals(resMap.get("status"))) {
     * String accessToken = resMap.get("token");
     * // do something
     * // ...
     * } else {
     * log.error(resMap.get("msg"));
     * // do something
     * // ...
     * }
     */
    public static Map<String, String> getToken() throws IOException {

        final String requestUrl = ENDPOINTS + "/admin-api/system/auth/login";

        Map<String, String> headers = new HashMap<>();
        // 租户ID
        headers.put("tenant-id", "1");

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("username", "syncuser");
        requestBody.put("password", "syncuser@123");

        String res;

        Map<String, String> resStatus = new HashMap<>();
        log.info("start request {}", requestUrl);
        res = HttpClientUtils.postAppJson(requestUrl, headers, requestBody, 3000, 3000);
        resStatus.put("status", "error");
        resStatus.put("msg", String.format("获取token请求异常:"));

        JSONObject jsonObject = JSONObject.parseObject(res);

        int code = jsonObject.getIntValue("code");
        if (code == 0) {
            JSONObject data = jsonObject.getJSONObject("data");
            String token = data.getString("accessToken");

            if (token != null) {
                resStatus.put("status", "success");
                resStatus.put("token", token);
                return resStatus;

            } else {
                resStatus.put("status", "error");
                resStatus.put("msg", "获取token接口返回数据解析异常，未获取到accessToken");
                return resStatus;
            }
        }

        resStatus.put("status", "error");
        resStatus.put("msg", String.format("获取token接口返回异常:%s", res));
        log.error("response with error status", res);
        return resStatus;
    }


    /**
     * 创建外贸客户需求单
     *
     * @param data
     */
    public static Map<String, String> Ordercreateuser(String data, String yem_billtype) {
        Map<String, String> resStatus = new HashMap<>();
        try {
            JSONObject json = JSONObject.parseObject(data);
            DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject("yem_im_clientdemand");
            dynamicObject.set("yem_orderplatid", json.getString("id"));//下单平台单据id
            dynamicObject.set("yem_synchronization", true);//下单平台单据id
            if (json.getString("remark") != null) {
                dynamicObject.set("yem_remark", json.getString("remark"));//下单平台单据id
            }
            //客户 yem_customer
            DynamicObject customer = OrderUtils.seelctDyn("bd_customer", "number", json.getString("username"));
            if (customer == null) {
                resStatus.put("status", "error");
                resStatus.put("msg", "未知客户");
                return resStatus;
            }
            customer = BusinessDataServiceHelper.loadSingle(customer.getPkValue(),customer.getDynamicObjectType().getName());

            dynamicObject.set("yem_customer", customer);//客户\
            dynamicObject.set("yem_customername", customer.getString("name"));
            dynamicObject.set("yem_customeraddr", customer.getLocaleString("bizpartner_address").getLocaleValue());
            dynamicObject.set("yem_customerlinkman", customer.getLocaleString("linkman").getLocaleValue());
            dynamicObject.set("yem_customertel", customer.getString("bizpartner_phone"));
            dynamicObject.set("yem_customerfax", customer.getString("bizpartner_fax"));
            dynamicObject.set("yem_customemail", customer.getString("postal_code"));

            dynamicObject.set("yem_ordbillno", json.getString("orderNo"));//下单平台单据id
            dynamicObject.set("billstatus", "A");//单据状态
            dynamicObject.set("yem_billtype", OrderUtils.seelctDyn("bos_billtype", "number", yem_billtype));//单据类型
            String product = json.getString("producttypeno"); // 产品分类

            if (product.contains("ZZJ")) {
                product = "ZZJPJ";
            } else if (product.contains("CC")) {
                product = "CCPJ";
            } else if (product.contains("TLJ")) {
                product = "TLJPJ";
            }

            dynamicObject.set("yem_bd_products", OrderUtils.seelctDyn("yem_bd_productsgroup", "number", product));//产品分类
            dynamicObject.set("org", OrderUtils.seelctDyn("bos_org", "number", "110"));//组织
            dynamicObject.set("yem_department", OrderUtils.seelctDyn("bos_org", "number", "110"));//部门
            dynamicObject.set("yem_businessdate", new Date());//业务日期
            dynamicObject.set("yem_bizdate", new Date());//报价日期
            dynamicObject.set("yem_singlenumber", new BigDecimal(1));//本单票数
//            DynamicObject yem_currency = OrderUtils.seelctDyn("bd_currency", "number", "USD");
            DynamicObject yem_currencybase = OrderUtils.seelctDyn("bd_currency", "number", "CNY");
            DynamicObject yem_exratetable = OrderUtils.seelctDyn("bd_exratetable", "number", "001");
            dynamicObject.set("yem_currency", yem_currencybase);//结算币别
            dynamicObject.set("yem_currencybase", yem_currencybase);//本位币
            dynamicObject.set("yem_exratetable", yem_exratetable);//汇率表
            dynamicObject.set("yem_exratedate", new Date());//汇率日期
            dynamicObject.set("yem_quotation", "0");//换算方式

            dynamicObject.set("yem_deliveryadd", json.getString("address")); // 交货地址;
            Date deliverydate = json.getDate("deliverydate");
            if (deliverydate != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                String format = sdf.format(deliverydate);
                dynamicObject.set("yem_jhrqyw", format); // 交货日期
            }

            dynamicObject.set("yem_contactpeople", json.getString("contactPerson")); // 联系人
            dynamicObject.set("yem_contactnumber", json.getString("contactNumber")); // 联系电话
            dynamicObject.set("yem_contactemail", json.getString("contactEmail")); // 联系邮箱

//            if (yem_currency != null && yem_currencybase != null && yem_exratetable != null) {
//                BigDecimal exchangerate = BaseDataServiceHelper.getExchangeRate(yem_exratetable.getLong("id"), yem_currency.getLong("id"), yem_currencybase.getLong("id"), new Date());
//            }
            dynamicObject.set("yem_exrate", new BigDecimal("1"));
            dynamicObject.set("creator", YEM.getCurrentUserId());//创建人
            DynamicObjectCollection yem_im_detailedinfor = dynamicObject.getDynamicObjectCollection("yem_im_detailedinfor");
            JSONArray details = json.getJSONArray("details");
            BigDecimal amount = BigDecimal.ZERO;
            for (int i = 0; i < details.size(); i++) {
                JSONObject jsonObject = details.getJSONObject(i);
                BigDecimal amountandtax = jsonObject.getBigDecimal("amountandtax");
                DynamicObject detailedinfor = yem_im_detailedinfor.addNew();
                detailedinfor.set("yem_orderplatentryid", jsonObject.getString("id"));
                detailedinfor.set("yem_colour", jsonObject.getString("color"));
                DynamicObject material = OrderUtils.seelctDyn("bd_material", "number", jsonObject.getString("materiel"));
                if (material != null) {
                    String id = material.getString("id");
                    DynamicObject Object = BusinessDataServiceHelper.loadSingle(id, "bd_material");
                    detailedinfor.set("yem_materiel", Object);//物料
                    detailedinfor.set("yem_materialename", Object.getString("yem_nameen"));//物料英文名称
                    detailedinfor.set("yem_unit", Object.getDynamicObject("baseunit"));//物料
                    detailedinfor.set("yem_baseunit", Object.getDynamicObject("baseunit"));//基本计量单位
                }
                detailedinfor.set("yem_qty", jsonObject.getBigDecimal("qty"));//需求数量
                detailedinfor.set("yem_safobprice", jsonObject.getBigDecimal("price"));//单价
                detailedinfor.set("yem_safobamount", amountandtax);//金额
                detailedinfor.set("yem_unasscontractqty", jsonObject.getBigDecimal("qty"));//未关联合同数量
                detailedinfor.set("yem_baseqty", jsonObject.getBigDecimal("qty"));//未关联合同数量
                detailedinfor.set("yem_businesssort", "P");//业务分类
                detailedinfor.set("yem_commissiontype", "P");//提成分类
                detailedinfor.set("yem_bigcabinet", OrderUtils.seelctDyn("yem_bd_boxtype", "number", "XX-0002"));//大柜
                detailedinfor.set("yem_mincabinet", OrderUtils.seelctDyn("yem_bd_boxtype", "number", "XX-0001"));//小柜
                amount = amount.add(amountandtax);
            }
            dynamicObject.set("yem_amount", amount);//报价金额（FOB）
            dynamicObject.set("yem_amountbase", amount);//报价金额本位币（FOB）
            OperationResult Operate = OperationServiceHelper.executeOperate("save",
                    dynamicObject.getDynamicObjectType().getName(), new DynamicObject[]{dynamicObject}, OperateOption.create());
            if (Operate.isSuccess()) {
                String billno = dynamicObject.getString("billno");
                dynamicObject.set("yem_title", "外贸配件客户需求单-" + billno);
                SaveServiceHelper.update(dynamicObject);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", dynamicObject.getString("id"));
                jsonObject.put("orderNo", dynamicObject.getString("billno"));
                resStatus.put("status", "success");
                resStatus.put("msg", jsonObject.toString());
                sendMessageToCorrelationUser(billno, customer.getString("name"), product);
            } else {
                List<IOperateInfo> allErrorOrValidateInfo = Operate.getAllErrorOrValidateInfo();
                String message = Operate.getMessage();
                resStatus.put("status", "error");
                resStatus.put("msg", message + "，" + allErrorOrValidateInfo);
            }
        } catch (Exception e) {
            String message = e.getMessage();
            resStatus.put("status", "error");
            resStatus.put("msg", message);
        }
        return resStatus;
    }

    /**
     * 发送消息给用户
     *
     * @param billno
     */
    private static void sendMessageToCorrelationUser(String billno, String username, String product) {
        List<Long> users = new ArrayList<>();
        String[] userNumber = new String[]{};
        if (product.contains("ZZJ")) {
            userNumber = new String[]{"ID-001001", "11565"};
        }
        if (product.contains("TLJ")) {
            userNumber = new String[]{"ID-001001", "14295"};
        }
        if (product.contains("CC")) {
            userNumber = new String[]{"ID-001001", "11565"};
        }
        DynamicObjectCollection collection = QueryServiceHelper.query("bos_user", "id", new QFilter[]{new QFilter("number", QCP.in, userNumber)});
        for (DynamicObject dynamicObject : collection) {
            users.add(dynamicObject.getLong("id"));
        }
        final String title = "客户下单通知";
//        String message = String.format("客户 [ %s ] 已在下单平台下单，已创建外贸配件需求单，单号为: [ %s ]，请前往查看！", username, billno);
//        YEM.sendMessage(users, "系统发送", MessageInfo.TYPE_MESSAGE, title, message, "业务消息");

        MessageInfo message = new MessageInfo();
        message.setUserIds(users);
        message.setSenderName("系统发送");
        message.setType(MessageInfo.TYPE_NOTICE);
        message.setTitle(title);
        message.setContent(String.format("客户 [ %s ] 已在下单平台下单，已创建外贸配件需求单，单号为: [ %s ]，请前往查看！", username, billno));
        message.setTag("业务消息");
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> systemNotice = new HashMap<>();
        systemNotice.put("showType", 1);
        params.put("systemNotice", systemNotice);
        message.setParams(params);
        MessageCenterServiceHelper.sendMessage(message);
    }

    /**
     * 撤销客户需求单
     *
     * @param id
     */
    public static Map<String, String> Orderunsubmit(String id) {
        Map<String, String> resStatus = new HashMap<>();
        try {
            Map map = new HashMap<>();
            map.put("A", "暂存");
            map.put("B", "已提交");
            map.put("C", "已审核");
            QFilter qFilters = new QFilter("yem_orderplatid", QCP.equals, id);
            DynamicObject yem_im_clientdemand = BusinessDataServiceHelper.loadSingle("yem_im_clientdemand", qFilters.toArray());
            if (yem_im_clientdemand != null) {
                String billstatus = yem_im_clientdemand.getString("billstatus");
                //A:暂存 B:已提交 C:已审核
                if (billstatus.equals("A")) {
                    OperationResult delete = OperationServiceHelper.executeOperate("delete",
                            yem_im_clientdemand.getDynamicObjectType().getName(), new Object[]{yem_im_clientdemand.getLong("id")}, OperateOption.create());
                    if (!delete.isSuccess()) {
                        String message = delete.getMessage();
                        List<IOperateInfo> allErrorOrValidateInfo = delete.getAllErrorOrValidateInfo();
                        resStatus.put("status", "error");
                        resStatus.put("msg", message + "\n" + allErrorOrValidateInfo);
                    } else {
                        resStatus.put("status", "success");
                        resStatus.put("msg", "操作成功");
                    }
                } else {
                    resStatus.put("status", "error");
                    resStatus.put("msg", "获取到对应单号【" + yem_im_clientdemand.getString("billno") + "】的状态为【" + map.get(billstatus) + "】，禁止撤销！");
                }
            } else {
                resStatus.put("status", "error");
                resStatus.put("msg", "未获取到对应的需求单!");
            }
        } catch (Exception e) {
            String message = e.getMessage();
            resStatus.put("status", "error");
            resStatus.put("msg", message);
        }
        return resStatus;
    }

    /**
     * 外贸客户需求单下推外销合同
     *
     * @return
     */
    public static Map<String, String> clientdemandtosalesorder(String data) {
        Map<String, String> resStatus = new HashMap<>();
        JSONObject json = JSONObject.parseObject(data);
        if (json.containsKey("id")) {
            String yem_orderplatid = json.getString("id");
            QFilter qFilters = new QFilter("yem_orderplatid", QCP.equals, yem_orderplatid);
            DynamicObject yem_im_clientdemand = BusinessDataServiceHelper.loadSingle("yem_im_clientdemand", qFilters.toArray());
            String bill1 = "yem_im_clientdemand";
            String bill2 = "yem_es_salesorder";
            String ruleId = "1731759680012705792";

            PushArgs pushArgs = new PushArgs();
            pushArgs.setSourceEntityNumber(bill1);        // 必选，源单标识
            pushArgs.setTargetEntityNumber(bill2);      // 必选，目标单标识
            pushArgs.setHasRight(false);                // 可选，传入true，不检查目标单新增权
            pushArgs.setAppId("");                    // 可选，传入目标单验权使用的应用编码
            pushArgs.setDefOrgId(0L);                    // 可选，传入目标单主组织默认值
            pushArgs.setRuleId(ruleId);                    // 可选，传入本次下推使用的转换规则id；传入空值，由系统自动寻找合适的转换规则
            pushArgs.setBuildConvReport(true);            // 是否输出详细错误报告

            List<ListSelectedRow> selectedRows = new ArrayList<>();
            ListSelectedRow srcBillRows = new ListSelectedRow(yem_im_clientdemand.getPkValue());
            selectedRows.add(srcBillRows);
            pushArgs.setSelectedRows(selectedRows);        // 必选，设置需要下推的源单及分录内码

            // 调用下推引擎，下推目标单
            ConvertOperationResult pushResult = ConvertServiceHelper.push(pushArgs);
            if (pushResult.isSuccess()) {
                // 获取生成的目标单数据包
                MainEntityType targetMainType = EntityMetadataCache.getDataEntityType(bill2);
                List<DynamicObject> targetBillObjs = pushResult.loadTargetDataObjects(new IRefrencedataProvider() {
                    @Override
                    public void fillReferenceData(Object[] objs, IDataEntityType dType) {
                        BusinessDataReader.loadRefence(objs, dType);
                    }
                }, targetMainType);
                // 设置保存参数，调用目标单保存服务，保存目标单（保存时自动反写源单）
                OperateOption saveOption = OperateOption.create();
                saveOption.setVariableValue(OperateOptionConst.IGNOREWARN, String.valueOf(true));    // 不执行警告级别校验器
                saveOption.setVariableValue(OperateOptionConst.IGNOREINTERACTION, String.valueOf(true));    // 不显示交互提示，自动执行到底
                saveOption.setVariableValue(OperateOptionConst.STRICTVALIDATION, String.valueOf(true));        // 全部校验通过才保存
                DynamicObject newbill = targetBillObjs.get(0);
                OperationResult saveResult = SaveServiceHelper.saveOperate(bill2, new DynamicObject[]{newbill}, saveOption);
                // 判断保存结果
                if (!saveResult.isSuccess()) {
                    String errMessage = saveResult.getMessage();    // 错误摘要
                    String detailMessage = "";
                    // 演示提取保存详细错误
                    for (IOperateInfo errInfo : saveResult.getAllErrorOrValidateInfo()) {
                        detailMessage += errInfo.getMessage() + "\r\n";
                    }
                    resStatus.put("status", "error");
                    resStatus.put("msg", "确认下单保存失败：" + detailMessage);
                } else {
                    long id = (long) saveResult.getSuccessPkIds().get(0);
                    String billno = newbill.getString("billno");
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", id);
                    jsonObject.put("orderNo", billno);
                    resStatus.put("status", "success");
                    resStatus.put("msg", jsonObject.toString());
                }
            } else {
                String errMessage = pushResult.getMessage();    // 错误摘要
                for (SourceBillReport billReport : pushResult.getBillReports()) {
                    // 演示如何提取各单错误报告
                    if (!billReport.isSuccess()) {
                        String billMessage = billReport.getFailMessage();
                    }
                }
                resStatus.put("status", "error");
                resStatus.put("msg", errMessage);
            }
        }
        return resStatus;
    }

    /**
     * 新增用户
     */
    public static Map<String, String> demands(String data, String string) {
        final String requestUrl = ENDPOINTS + "/admin-api/system/user/create";

        Map<String, String> headers = null;
        try {
            headers = getToken();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Map<String, String> resStatus = new HashMap<>();
        // 租户ID
        if ("success".equals(headers.get("status"))) {
            String accessToken = headers.get("token");
            headers.put("Authorization", "Bearer " + (accessToken));
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("nickname", data);
            requestBody.put("password", "ensign@123");
            requestBody.put("username", string);
            requestBody.put("deptId", "100");
            String res = "";


            try {
                log.info("start request {}", requestUrl);
                res = HttpClientUtils.postAppJson(requestUrl, headers, requestBody, 3000, 3000);
            } catch (IOException e) {
                log.error("request token error", e);
                resStatus.put("status", "error");
                resStatus.put("msg", String.format("获取token请求异常:%s", e.getMessage()));
//                throw new RuntimeException(e);
            }

            JSONObject jsonObject = JSONObject.parseObject(res);
            Long id = 0L;
            int code = jsonObject.getIntValue("code");
            if (code == 0) {
                id = jsonObject.getLong("data");
                String ids = id.toString();
                resStatus.put("id", ids);
            }
            return resStatus;
        } else {
            log.error(headers.get("msg"));
        }
        return resStatus;
    }
    /**
     * 修改用户
     */
    public static Map<String, String> Modifyuser(String big,String string) {

        final String requestUrl = ENDPOINTS + "/admin-api/system/user/update-status";

        Map<String, String> headers = null;
        try {
            headers = getToken();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Map<String, String> resStatus = new HashMap<>();
        // 租户ID
        if ("success".equals(headers.get("status"))) {
            String accessToken = headers.get("token");
            headers.put("Authorization", "Bearer " + (accessToken));
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("id", string);
            requestBody.put("status", big);
            String res = "";
            try {
                log.info("start request {}", requestUrl);
                res = HttpUtils.doPut(requestUrl,  JSON.toJSONString(requestBody),"json", headers);
//                HttpUtils.doPut(requestUrl, JSON.toJSONString(objectArrayList), "json", headers);
            } catch (IOException e) {
                log.error("request token error", e);
                resStatus.put("status", "error");
                resStatus.put("msg", String.format("获取token请求异常:%s", e.getMessage()));
            }
        }
        return null;
    }
    /**
     * 同步订单
     *
     * @param list
     * @return
     */
    public static Map<String, String> Devicefiles(List<Map<String, Object>> list) {
        if (!list.isEmpty()) {
            final String requestUrl = ENDPOINTS + "/admin-api/em/cusorderedit/batch/create";
            Map<String, String> headers = null;
            try {
                headers = OrderApiUtils.getToken();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            Map<String, String> resStatus = new HashMap<>();
            // 租户ID

            if ("success".equals(headers.get("status"))) {
                String accessToken = headers.get("token");
                headers.put("Authorization", "Bearer " + (accessToken));
                Map<String, Object> requestBodyMap = new HashMap<>();
                List<Object> objectArrayList = new ArrayList<>();
                for (Map<String, Object> Bearer : list) {
                    List<Object> objectList = new ArrayList<>();
                    Map<String, Object> requestBody = new HashMap<>();
                    requestBody.put("userNo", Bearer.get("userNo"));
                    requestBody.put("salesorderno", Bearer.get("salesorderno"));
                    requestBody.put("orderTime", Bearer.get("orderTime"));
//                    requestBody.put("product", Bearer.get("product"));
//                    requestBody.put("qty",Bearer.get("qty"));
                    requestBody.put("model", Bearer.get("model"));
                    requestBody.put("salesman", Bearer.get("salesman"));
                    requestBody.put("seller", Bearer.get("seller"));
                    requestBody.put("productenname",Bearer.get("productenname"));
                    requestBody.put("productname",Bearer.get("productname"));
                    requestBody.put("product",Bearer.get("productnumber"));
                    Map<String, Object> objectMap = new HashMap<>();
                    objectMap.put("salesorderno", Bearer.get("salesordernos"));
                    objectMap.put("framenumber", Bearer.get("framenumber"));
                    objectMap.put("model", Bearer.get("models"));
                    objectMap.put("grouptype", Bearer.get("grouptype"));
                    objectMap.put("color", Bearer.get("color"));
                    objectMap.put("qty", 1);
                    objectMap.put("enginecode", Bearer.get("enginecode"));
                    objectMap.put("enginemodel", Bearer.get("enginemodel"));
                    objectMap.put("dateofmanufacture", Bearer.get("dateofmanufacture"));
                    objectMap.put("kingdeeId", Bearer.get("kingdeeId"));
                    objectList.add(objectMap);
                    requestBody.put("cusordereditentrys", objectList);
                    objectArrayList.add(requestBody);
                }
                requestBodyMap.put("cusorderedi", objectArrayList);
                String res = "";
                try {
                    log.info("start request {}", requestUrl);
                    res = HttpClientUtils.postAppJson(requestUrl, headers, requestBodyMap, 3000000, 3000000);
                } catch (IOException e) {
                    log.error("request token error", e);
                    resStatus.put("status", "error");
                    resStatus.put("msg", String.format("获取token请求异常:%s", e.getMessage()));
                    throw new RuntimeException(e);
                }
                JSONObject jsonObject = JSONObject.parseObject(res);
                if (jsonObject != null) {
                    int code = jsonObject.getIntValue("code");
                    if (code == 0) {
                        JSONArray id = jsonObject.getJSONArray("data");
                        String ids = id.toString();
                        resStatus.put("id", ids);
                        for (Object object : id) {
                            JSONObject objects = (JSONObject) object;
                            String salesorderno = objects.getString("salesorderno");
                            Long objectsId = objects.getLong("id");
                            DynamicObject mechanical = BusinessDataServiceHelper.loadSingle("yem_em_devicefiles"
                                    , "id,number,yem_ordeid,yem_issynorde"
                                    , new QFilter[]{new QFilter("yem_salesorderno", QCP.equals, salesorderno)});
                            if (mechanical != null) {
                                mechanical.set("yem_ordeid", objectsId);
                                mechanical.set("yem_issynorde", true);
                                SaveServiceHelper.update(mechanical);
                                SaveServiceHelper.save(new DynamicObject[]{mechanical});
                            }
                        }
                    }
                } else {
                    log.error(headers.get("msg"));
                }
            }
        }
        return null;
    }

    /**
     * 同步产品机型到下单平台权限项
     * @param parentObject 父级
     */
    public static void syncProductModuleToPermissions(DynamicObject parentObject, ORM orm) throws IOException {
        DynamicObjectCollection dynamicObjectCollection = queryChildrenProductModule(parentObject, orm);

        if (dynamicObjectCollection == null || dynamicObjectCollection.isEmpty()) {
            return;
        }

        String token = initRequest();

        for (DynamicObject dynamicObject : dynamicObjectCollection) {

            int index = dynamicObjectCollection.indexOf(dynamicObject);

            Long permissionId = doSyncPermission(dynamicObject, orm, index, token, parentObject);
            dynamicObject.set("yem_orderperid", permissionId);

            syncProductModuleToPermissions(dynamicObject, orm);

        }
        SaveServiceHelper.update(dynamicObjectCollection.toArray(new DynamicObject[0]));

    }

    /**
     * 查询子级所有的产品机型，为空则查询一级
     * @param parent
     * @return
     */
    private static DynamicObjectCollection queryChildrenProductModule(DynamicObject parent, ORM orm) {
        if (YEM.isEmpty(parent)) {
            QFilter qFilter = new QFilter("parent.id", QCP.equals, 0);
            return orm.query("yem_bd_productsgroup", qFilter.toArray());
        }
        Long pkValue = (Long) parent.getPkValue();

        QFilter qFilter = new QFilter("parent.id", QCP.equals, pkValue);
        return orm.query("yem_bd_productsgroup", qFilter.toArray());
    }

    /**
     * 同步每一级产品类型，及该类型下的所有产品机型
     *
     * @param dynamicObject 产品类型
     * @param orm
     * @param token
     * @param parentObject
     * @return
     */
    private static Long doSyncPermission(DynamicObject dynamicObject, ORM orm, int index, String token, DynamicObject parentObject) throws IOException {
        Long pkValue = (Long) dynamicObject.getPkValue();
        QFilter qFilter = new QFilter("group.id", QCP.equals, pkValue);
        DynamicObjectCollection collection = orm.query("yem_bd_productstree", qFilter.toArray());

        log.info("AddPermissionGroup__" + dynamicObject.getPkValue() + "__" + dynamicObject.getString("number") + "__" + dynamicObject.getString("name"));

        Long returnId = requestAddPermissionGroup(dynamicObject, token, index, parentObject);

        for (DynamicObject object : collection) {
            int subIdx = collection.indexOf(object);
            Long itemId = requestAddPermissionItem(object, returnId, token, subIdx);
            object.set("yem_orderperid", itemId);

            log.info("AddPermissionItem__parent: " + dynamicObject.getString("number") + "_" + dynamicObject.getString("name") +"_item: " + object.getPkValue() + "_" + object.getString("number") + "_" + object.getString("name"));
        }

        SaveServiceHelper.update(collection.toArray(new DynamicObject[0]));
        return returnId;
    }

    private static String initRequest() throws IOException {
        Map<String, String> resMap = getToken();
        if ("success".equals(resMap.get("status"))) {
            return "Bearer " + resMap.get("token");
        } else {
            throw new  IOException("获取token失败");
        }
    }


    /**
     * 同步产品类型
     *
     * @param dynamicObject 产品类型
     * @param parentObject
     * @return
     */
    private static Long requestAddPermissionGroup(DynamicObject dynamicObject, String token, int index, DynamicObject parentObject) throws IOException {
        final String requestUrl = ENDPOINTS + "/admin-api/system/menu/update_if_exist_or_create_group";

        Map<String, String> header = new HashMap<>();
        header.put("Authorization", token);

        Map<String, Object> body = new HashMap<>();

        if (YEM.isEmpty(parentObject)) {

            body.put("parentId", 2754);
        } else {
            body.put("parentId", parentObject.getLong("yem_orderperid"));
        }
        body.put("name", dynamicObject.getString("name"));
        body.put("type", 1);
        body.put("sort", index);
        body.put("status", 0);
        body.put("visible", false);
        body.put("keepAlive", true);
        body.put("alwaysShow", true);
        body.put("path", dynamicObject.getString("number"));

        log.info("request_body__{}", JSON.toJSONString(body));
        String result = HttpUtils.doPost(requestUrl, JSON.toJSONString(body), "json", header);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Long data = jsonObject.getObject("data", Long.class);
        Integer code = jsonObject.getInteger("code");
        if (code == 0) {

            log.info(jsonObject.toJSONString());
            log.info("Group同步成功__{}__{}", dynamicObject.getString("name"), dynamicObject.getString("number"));
        } else {

            log.error(jsonObject.toJSONString());
            log.error("Group同步失败__{}__{}", dynamicObject.getString("name"), dynamicObject.getString("number"));
        }
        return data;
    }


    /**
     * 同步产品机型
     *
     * @param object   产品机型
     * @param parentId 该机型对应类型ID
     * @param subIdx 排序
     * @return
     */
    private static Long requestAddPermissionItem(DynamicObject object, Long parentId, String token, int subIdx) throws IOException {
        final String requestUrl = ENDPOINTS + "/admin-api/system/menu/update_if_exist_or_create_item";
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", token);

        Map<String, Object> body = new HashMap<>();

        String number = object.getString("number");
        body.put("parentId", parentId);
        body.put("name", number);
        body.put("type", 3);
        body.put("sort", subIdx);
        body.put("status", 0);
        body.put("visible", true);
        body.put("keepAlive", true);
        body.put("alwaysShow", true);
        body.put("permission", "kingdee:model:type:" + number);

        log.debug("request_body__{}", JSON.toJSONString(body));
        String result = HttpUtils.doPost(requestUrl, JSON.toJSONString(body), "json", header);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Long data = jsonObject.getObject("data", Long.class);
        Integer code = jsonObject.getInteger("code");
        if (code == 0) {

            log.info(jsonObject.toJSONString());
            log.info("Item同步成功__{}__{}", object.getString("name"), number);
        } else {

            log.error(jsonObject.toJSONString());
            log.error("Item同步失败__{}__{}", object.getString("name"), number);
        }
        return data;
    }

    /**
     * @param list
     * @return
     */
    public static Map<String, String> partsorderlist(List<Map<String, Object>> list) {
        if (!list.isEmpty()) {
            final String requestUrl = ENDPOINTS + "/admin-api/em/partsorderlist/list/update";
            Map<String, String> headers = null;
            try {
                headers = OrderApiUtils.getToken();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            Map<String, String> resStatus = new HashMap<>();
            List<Object> objectArrayList = new ArrayList<>();
            if ("success".equals(headers.get("status"))) {
                String accessToken = headers.get("token");
                headers.put("Authorization", "Bearer " + (accessToken));
                for (Map<String, Object> Bearer : list) {
                    Map<String, Object> requestBody = new HashMap<>();
                    requestBody.put("id",Bearer.get("id"));
                    requestBody.put("status",Bearer.get("status"));
                    requestBody.put("logisticsNo",Bearer.get("logisticsNo"));
                    requestBody.put("ladingDate",Bearer.get("ladingDate"));
                    objectArrayList.add(requestBody);
                }
                try {
                    log.info("start request {}", requestUrl);
                    HttpUtils.doPut(requestUrl, JSON.toJSONString(objectArrayList), "json", headers);
                } catch (IOException e) {
                    log.error("request token error", e);
                    resStatus.put("status", "error");
                    resStatus.put("msg", String.format("获取token请求异常:%s", e.getMessage()));
                    throw new RuntimeException(e);
                }
            }
        }
        return null;
    }
}