package com.benyun.project.third.longxiang.service.impl;

import com.benyun.common.exception.ServiceException;
import com.benyun.common.utils.DateUtils;
import com.benyun.common.utils.JsonUtil;
import com.benyun.common.utils.MapUtils;
import com.benyun.common.utils.StringUtils;
import com.benyun.framework.web.domain.AjaxResult;
import com.benyun.project.third.TransferDirect.domain.KingdeeTransferDirect;
import com.benyun.project.third.TransferDirect.mapper.KingdeeTransferDirectMapper;
import com.benyun.project.third.area.domain.OmsArea;
import com.benyun.project.third.area.mapper.OmsAreaMapper;
import com.benyun.project.third.byKingdeeConfig.domain.ByKingdeeConfig;
import com.benyun.project.third.byKingdeeConfig.mapper.ByKingdeeConfigMapper;
import com.benyun.project.third.kingdee.sdk.customer.BdCustomer;
import com.benyun.project.third.longxiang.domain.*;
import com.benyun.project.third.longxiang.mapper.BySynMaterialMsgMapper;
import com.benyun.project.third.longxiang.service.LongXiangService;
import com.benyun.project.third.material.domain.ByMaterialOut;
import com.benyun.project.third.material.mapper.ByMaterialOutMapper;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.kingdee.bos.webapi.entity.OperateParam;
import com.kingdee.bos.webapi.entity.OperatorResult;
import com.kingdee.bos.webapi.entity.QueryParam;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.ListUtils;

import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.fail;

@Service
@Slf4j
public class LongXiangServiceImpl implements LongXiangService, Serializable {

    private static final long serialVersionUID = 1L;


    private static final String SYS = "LongXiangServiceImpl.";

    static K3CloudApi api = new K3CloudApi();

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ByMaterialOutMapper byMaterialOutMapper;

    @Autowired
    private BySynMaterialMsgMapper bySynMaterialMsgMapper;


    @Autowired
    private OmsAreaMapper omsAreaMapper;
    @Autowired
    private KingdeeTransferDirectMapper kingdeeTransferDirectMapper;


    @Autowired
    private ByKingdeeConfigMapper byKingdeeConfigMapper;

    /**
     * @return
     */
    @Override
    public AjaxResult refreshAllToken() {


        //获取到所有有效的租户配置信息
        List<ByKingdeeConfig> kingdeeConfigListAll = byKingdeeConfigMapper.selectByKingdeeConfigListAll();

        for (ByKingdeeConfig byKingdeeConfig : kingdeeConfigListAll) {
            String configKey = "KingdeeConfi" + byKingdeeConfig.getTenantId();
            ByKingdeeConfig kingdeeConfig = (ByKingdeeConfig)redisTemplate.opsForValue().get(configKey);
            if (null == kingdeeConfig) {
                redisTemplate.opsForValue().set(configKey, byKingdeeConfig, 7, TimeUnit.DAYS);
            }
        }

        for (ByKingdeeConfig byKingdeeConfig : kingdeeConfigListAll) {
            //查询各租户的oms的Token信息
            String key = "LongXiangToken" + byKingdeeConfig.getTenantId();
            String token = (String) redisTemplate.opsForValue().get(key);
            if (StringUtils.isEmpty(token)) {
                token = getToken(getCode(byKingdeeConfig.getOmsUrl(), byKingdeeConfig.getOmsClientId(), byKingdeeConfig.getOmsProjectId(),
                        byKingdeeConfig.getOmsRedirectUri()), byKingdeeConfig.getOmsClientId(), byKingdeeConfig.getOmsClientSecret(), byKingdeeConfig.getOmsRedirectUri(), byKingdeeConfig.getOmsUrl());
                redisTemplate.opsForValue().set(key, token, 7, TimeUnit.DAYS);
            }

            //查询各租户的货主信息
            String partnerKey = "partnerKey" + byKingdeeConfig.getTenantId();
            Integer partner = (Integer) redisTemplate.opsForValue().get(partnerKey);
            if (null == (partner)) {
                getOwner(byKingdeeConfig.getOmsUrl(), token, byKingdeeConfig.getTenantId());
            }

        }

        return AjaxResult.success();
    }


    /**
     * @param skuCode
     * @return
     * @throws Exception
     */
    @Override
    public AjaxResult skuSync(Integer num) {

        if (null == num) {
            num = 1;
        }

        //获取到所有有效的租户配置信息
        List<ByKingdeeConfig> kingdeeConfigListAll = byKingdeeConfigMapper.selectByKingdeeConfigListAll();
        for (ByKingdeeConfig byKingdeeConfig : kingdeeConfigListAll) {
            String configKey = "KingdeeConfi" + byKingdeeConfig.getTenantId();
            ByKingdeeConfig tenantConfig = (ByKingdeeConfig) redisTemplate.opsForValue().get(configKey);
            if (null == (tenantConfig)) {
                refreshAllToken();
                tenantConfig = (ByKingdeeConfig) redisTemplate.opsForValue().get(configKey);
            }

            String tokenReids = "LongXiangToken" + tenantConfig.getTenantId();
            String token = (String) redisTemplate.opsForValue().get(tokenReids);
            if (StringUtils.isEmpty(token)) {
                refreshAllToken();
                token = (String) redisTemplate.opsForValue().get(tokenReids);
            }

            //redis获取货主
            String partnerKey = "partnerKey" + tenantConfig.getTenantId();
            Integer wmsMemberId = (Integer) redisTemplate.opsForValue().get(partnerKey);
            if (null == wmsMemberId) {
                refreshAllToken();
                wmsMemberId = (Integer) redisTemplate.opsForValue().get(partnerKey);
            }

            try {
                K3CloudApi api = new K3CloudApi();
                String json = "{\n" +
                        "    \"FormId\": \"BD_Material\",\n" +
                        //                  金蝶物料Id  金蝶物料code 名称    组织ID      使用组织     库存单位Id
                        "    \"FieldKeys\": \"FNumber,FName,FMATERIALID\",\n" +
//                    "    \"FieldKeys\": \"FNumber,FName\",\n" +
                        "}";

                //金蝶返回的所有物料列表
                List<List<Object>> lists = api.executeBillQuery(json);
                if (ListUtils.isEmpty(lists)) {
                    return AjaxResult.error("查询金蝶物料列表为空!");
                }

                for (List<Object> list : lists) {
                    String FNumber = list.get(0).toString();
                    String FName = list.get(1).toString();
                    ItemSkuSyncParams itemSkuSyncParams1 = new ItemSkuSyncParams();
                    //查询本地  如果有  则跳过
                    if (null != byMaterialOutMapper.selectByMaterialOutByCode(FNumber)) {
                        continue;
                    }
                    //WMS系统唯一编码   69码
                    itemSkuSyncParams1.setBar_code(FNumber);
                    //租户Id
                    itemSkuSyncParams1.setTenant_id(tenantConfig.getTenantId());
                    //货主id
                    itemSkuSyncParams1.setPartner_id(wmsMemberId);
                    //商品名称
                    itemSkuSyncParams1.setSku_title(FName);
                    //操作类型
                    itemSkuSyncParams1.setAction_type("add");
                    //Sku编号
                    itemSkuSyncParams1.setSku_code(FNumber);
                    //价格
                    itemSkuSyncParams1.setPrice(0.00);
                    //重量
                    itemSkuSyncParams1.setHeight(0.00);
                    //长度
                    itemSkuSyncParams1.setLength(0.00);
                    //宽度
                    itemSkuSyncParams1.setWidth(0.00);
                    //高度
                    itemSkuSyncParams1.setHeight(0.00);
                    //是否组合商品
                    itemSkuSyncParams1.setIs_combine(false);

                    AjaxResult result = syncSaveToOms(itemSkuSyncParams1, token, list.get(2).toString(), tenantConfig.getChannelCode(), tenantConfig.getTenantId(), tenantConfig.getOmsUrl());
                    if (0 != (Integer) result.get("code")) {
                        log.error(SYS + result.get("msg"));
                    }
                }

            } catch (Exception e) {
                log.error(SYS + e.getMessage());

                num++;
                if (num < 4) {
                    //如果失败  则重试3次
                    skuSync(num);
                } else {
                    return AjaxResult.error(SYS + e.getMessage());
                }
                return AjaxResult.error(SYS + e.getMessage());
            }
        }
        return AjaxResult.success();
    }

    private AjaxResult syncSaveToOms(ItemSkuSyncParams itemSkuSyncParams, String token, String FMaterialId, String channelCode, String tenantId, String omsUrl) {

        RequestMaterialDomain requestMaterialDomain = new RequestMaterialDomain();
        requestMaterialDomain.setBiz_content(itemSkuSyncParams);

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JsonUtil.toJsonString(requestMaterialDomain));
        Request request = new Request.Builder()
                .url(omsUrl + "/oms/skuSync")
                .method("POST", body)
                .addHeader("Authorization", "Bearer " + token)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Content-Type", "application/json")
                .build();

        try {
            Response response = client.newCall(request).execute();
            if (200 != response.code()) {
                String msg = "<br/>" + "请求Oms失败,网络错误码:" + response.code() + ",网络错误信息:" + response.message();
                log.error(SYS + msg);
                //保存失败回执信息
                BySynMaterialMsg responseMsgDomain = new BySynMaterialMsg();
                responseMsgDomain.setMsgCode("" + response.code());
                responseMsgDomain.setMsgContext(response.message());
                responseMsgDomain.setResponseMsg(msg);
                responseMsgDomain.setOperateCode("syncSaveToOms");
                responseMsgDomain.setSyncMaterialCode(itemSkuSyncParams.getBar_code());
                responseMsgDomain.setSyncChannelCode(channelCode);
                responseMsgDomain.setCreateTime(new Date());
                responseMsgDomain.setTenantId(tenantId);
                bySynMaterialMsgMapper.insertBySynMaterialMsg(responseMsgDomain);
                return AjaxResult.error(msg);

            }
            //解析body内容
            String string = response.body().string();
            ResponseMaterialMsg responseMaterialMsg = JsonUtil.buildNonNullBinder().getJsonToObject(string, ResponseMaterialMsg.class);
            if (!"200".equals(responseMaterialMsg.getCode())) {
                String msg = "<br/>" + "请求Oms失败,oms系统错误码:" + responseMaterialMsg.getCode() + ",oms系统错误信息:" + responseMaterialMsg.getMsg();
                log.error(SYS + msg);
                //保存失败回执信息
                BySynMaterialMsg responseMsgDomain = new BySynMaterialMsg();
                responseMsgDomain.setMsgCode("" + response.code());
                responseMsgDomain.setMsgContext(response.message());
                responseMsgDomain.setResponseCode(responseMaterialMsg.getCode());
                responseMsgDomain.setResponseMsg(msg);
                responseMsgDomain.setOperateCode("syncSaveToOms");
                responseMsgDomain.setSyncMaterialCode(itemSkuSyncParams.getBar_code());
                responseMsgDomain.setSyncChannelCode(channelCode);
                responseMsgDomain.setCreateTime(new Date());
                responseMsgDomain.setTenantId(tenantId);
                bySynMaterialMsgMapper.insertBySynMaterialMsg(responseMsgDomain);
                return AjaxResult.error(msg);
            }

            //同步成功的物料  保存到本地
            ByMaterialOut byMaterialOut = new ByMaterialOut();
            byMaterialOut.setMaterialName(itemSkuSyncParams.getSku_title());
            byMaterialOut.setOutMaterialCode(itemSkuSyncParams.getBar_code());
            byMaterialOut.setOutChannelCode(channelCode);
            byMaterialOut.setInMaterialCode(responseMaterialMsg.getData());
            byMaterialOut.setInChannelCode(tenantId);
            byMaterialOut.setFlagCode("0");
            byMaterialOut.setOutMaterialId(FMaterialId);
            byMaterialOutMapper.insertByMaterialOut(byMaterialOut);

            //保存成功回执信息
            BySynMaterialMsg responseMsgDomain = new BySynMaterialMsg();
            responseMsgDomain.setMsgCode("" + response.code());
            responseMsgDomain.setMsgContext(response.message());
            responseMsgDomain.setResponseCode(responseMaterialMsg.getCode());
            responseMsgDomain.setResponseMsg(responseMaterialMsg.getMsg());
            responseMsgDomain.setOperateCode("syncSaveToOms");
            responseMsgDomain.setSyncMaterialCode(itemSkuSyncParams.getBar_code());
            responseMsgDomain.setSyncChannelCode(channelCode);
            responseMsgDomain.setCreateTime(new Date());
            responseMsgDomain.setTenantId(tenantId);
            bySynMaterialMsgMapper.insertBySynMaterialMsg(responseMsgDomain);

        } catch (Exception e) {
            log.error(SYS + e.getMessage());

        }
        return AjaxResult.success();
    }

    /**
     * @return
     * @throws Exception
     */
//    @Override
//    public AjaxResult skuBatchSync() {
//
//        String token = getToken();
//
//        try {
//            K3CloudApi api = new K3CloudApi();
//            String json = "{\n" +
//                    "    \"FormId\": \"BD_Material\",\n" +
//                    //                  金蝶物料Id  金蝶物料code 名称    组织ID      使用组织     库存单位Id
////                    "    \"FieldKeys\": \"FMATERIALID,FNumber,FName,FCreateOrgId,FUseOrgId,FStoreUnitID\",\n" +
//                    "    \"FieldKeys\": \"FNumber,FName\",\n" +
//                    "}";
//
//            //金蝶返回的所有物料列表
//            List<List<Object>> lists = api.executeBillQuery(json);
//            if (ListUtils.isEmpty(lists)) {
//                return AjaxResult.error("查询金蝶物料列表为空!");
//            }
//            List<ItemSkuSyncParams> itemSkuList = new ArrayList<>();
//
//            //redis获取货主
//            String partnerKey = "partnerKey";
//            Integer wmsMemberId = (Integer) redisTemplate.opsForValue().get(partnerKey);
//            if (null == wmsMemberId) {
//                ResponseWmsCustomer owner = getOwner(token);
//                wmsMemberId = owner.getId();
//            }
//
//
//            for (List<Object> list : lists) {
//                String FNumber = list.get(0).toString();
//                String FName = list.get(1).toString();
//                ItemSkuSyncParams itemSkuSyncParams1 = new ItemSkuSyncParams();
//                //查询本地  如果有  则跳过
//                if (null != byMaterialOutMapper.selectByMaterialOutByCode(FNumber)) {
//                    continue;
//                }
//                //WMS系统唯一编码   69码
//                itemSkuSyncParams1.setBar_code(FNumber);
//                //租户Id
//                itemSkuSyncParams1.setTenant_id(omsOpenConfig.getTenantId());
//                //货主id
//                itemSkuSyncParams1.setPartner_id(wmsMemberId);
//                //商品名称
//                itemSkuSyncParams1.setSku_title(FName);
//                //操作类型
//                itemSkuSyncParams1.setAction_type("add");
//                //Sku编号
//                itemSkuSyncParams1.setSku_code(FNumber);
//                //价格
//                itemSkuSyncParams1.setPrice(0.00);
//                //重量
//                itemSkuSyncParams1.setHeight(0.00);
//                //长度
//                itemSkuSyncParams1.setLength(0.00);
//                //宽度
//                itemSkuSyncParams1.setWidth(0.00);
//                //高度
//                itemSkuSyncParams1.setHeight(0.00);
//                //是否组合商品
//                itemSkuSyncParams1.setIs_combine(false);
//
//
//                itemSkuList.add(itemSkuSyncParams1);
//                if (50 == itemSkuList.size()) {
//                    //同步到oms系统
//                    AjaxResult result = batchSaveToOms(itemSkuList, token);
//                    if (!result.get("code").equals("200")) {
//                        log.error(SYS + result.get("msg"));
//                    }
//                    //然后清空list   进入下一次循环
//                    itemSkuList.clear();
//                }
//            }
//            AjaxResult result = batchSaveToOms(itemSkuList, token);
//            if (!result.get("code").equals("200")) {
//                log.error(SYS + result.get("msg"));
//            }
//
//        } catch (Exception e) {
//            log.error(SYS + e.getMessage());
//            return AjaxResult.error(SYS + e.getMessage());
//
//        }
//        return AjaxResult.success();
//    }
    private AjaxResult batchSaveToOms(List<ItemSkuSyncParams> itemSkuList, String token, String omsUrl, String tenantId, String channelCode) {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        CreatSkuBatch creatSkuBatch = new CreatSkuBatch();
        creatSkuBatch.setItem_sku_list(itemSkuList);
        RequestBatchMaterialDomain requestBatchMaterialDomain = new RequestBatchMaterialDomain();
        requestBatchMaterialDomain.setBiz_content(creatSkuBatch);

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JsonUtil.toJsonString(requestBatchMaterialDomain));
        Request request = new Request.Builder()
                .url(omsUrl + "/oms/skuBatchSync")
                .method("POST", body)
                .addHeader("Authorization", "Bearer " + token)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Content-Type", "application/json")
                .build();


        try {
            Response response = client.newCall(request).execute();
            if (200 != response.code()) {
                String msg = "<br/>" + "请求Oms失败,网络错误码:" + response.code() + ",网络错误信息:" + response.message();
                failureMsg.append(msg + response.message());
            }
            String string = response.body().string();
            ResponseBatchMaterialMsg responseMaterialMsg = JsonUtil.buildNonNullBinder().getJsonToObject(string, ResponseBatchMaterialMsg.class);
            if (!"200".equals(responseMaterialMsg.getCode())) {
                String msg = "<br/>" + "请求Oms失败,oms系统错误码:" + responseMaterialMsg.getCode() + ",oms系统错误信息:" + response.message();
                failureMsg.append(msg + responseMaterialMsg.getMsg());
                log.error("请求Oms失败,oms系统错误码:" + responseMaterialMsg.getCode() + ",oms系统错误信息:" + response.message());
            }

            ItemSkuBatchSyncResult data = responseMaterialMsg.getData();
            List<ItemSkuBatchSyncSuccessResult> successItems = data.getSuccessItems();
            if (!ListUtils.isEmpty(successItems)) {
                for (ItemSkuBatchSyncSuccessResult successItem : successItems) {
                    //同步成功的物料  保存到本地
                    ByMaterialOut byMaterialOut = new ByMaterialOut();
//                    byMaterialOut.setMaterialName();
                    byMaterialOut.setOutMaterialCode(successItem.getBarCode());
                    byMaterialOut.setOutChannelCode(channelCode);
                    byMaterialOut.setInMaterialCode(successItem.getSkuId());
                    byMaterialOut.setInChannelCode(tenantId);
                    byMaterialOut.setFlagCode("0");
                    byMaterialOutMapper.insertByMaterialOut(byMaterialOut);
                    successMsg.append("<br/>" + successNum + "、" + channelCode + "商品barCode: " + successItem.getBarCode() + " 同步成功");
                    successNum++;

                }
            }
            List<ItemSkuBatchSyncSuccessResult> failureItems = data.getFailureItems();
            if (!ListUtils.isEmpty(failureItems)) {
                for (ItemSkuBatchSyncSuccessResult failureItem : failureItems) {
                    String msg = "<br/>" + failureNum + "、" + channelCode + "商品barCode: " + failureItem.getBarCode() + " 同步失败：";
                    failureMsg.append(msg + failureItem.getMsg());
                    failureNum++;
                }

            }
            if (failureNum > 0) {
                failureMsg.insert(0, "很抱歉，同步失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                log.debug(failureMsg.toString());
                throw new ServiceException(failureMsg.toString());

            } else {
                successMsg.insert(0, "恭喜您，数据已全部同步成功！共 " + successNum + " 条，数据如下：");
                log.info(successMsg.toString());
                return AjaxResult.success();
            }

        } catch (Exception e) {

        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult getKingdeeSkuInfoById(String skuId) {
        try {
            if (StringUtils.isEmpty(skuId)) {
                return AjaxResult.error("skuId");
            }


            K3CloudApi api = new K3CloudApi();
            QueryParam<List<Map<String, Object>>> para = new QueryParam<>();
            para.setFormId("BD_Material");
            //                 名称    code    id
            para.setFieldKeys("FName,FNumber,FMaterialId");

            Map<String, Object> mapStockId = new HashMap<>();
            mapStockId.put("Left", "(");
            mapStockId.put("FieldName", "FMaterialId");
            mapStockId.put("Compare", "=");
            mapStockId.put("Value", skuId);
            mapStockId.put("Right", ")");
            mapStockId.put("Logic", "and");

            List<Map<String, Object>> list = new ArrayList<>();
            list.add(mapStockId);
            para.setFilterString(list);
            List<List<Object>> lists = api.executeBillQuery(para.toJson());
            if (ListUtils.isEmpty(lists)) {
                return AjaxResult.error("查询金蝶物料信息为空");
            }
            return AjaxResult.success(lists.get(0).get(1).toString());

        } catch (Exception e) {
            e.getMessage();
        }

        return AjaxResult.error("查询金蝶物料信息为空");
    }

    /**
     * @return
     * @throws Exception
     */
    @Override
    public AjaxResult createWmsInOrder() throws Exception {
        return null;
    }

    /**
     * @return
     * @throws Exception
     */
    @Override
    public AjaxResult createOrder() {

        //获取到所有有效的租户配置信息
        List<ByKingdeeConfig> kingdeeConfigListAll = byKingdeeConfigMapper.selectByKingdeeConfigListAll();
        for (ByKingdeeConfig byKingdeeConfig : kingdeeConfigListAll) {
            String configKey = "KingdeeConfi" + byKingdeeConfig.getTenantId();
            ByKingdeeConfig tenantConfig = (ByKingdeeConfig) redisTemplate.opsForValue().get(configKey);
            if (null == (tenantConfig)) {
                refreshAllToken();
                tenantConfig = (ByKingdeeConfig) redisTemplate.opsForValue().get(configKey);
            }

            String tokenReids = "LongXiangToken" + tenantConfig.getTenantId();
            String token = (String) redisTemplate.opsForValue().get(tokenReids);
            if (StringUtils.isEmpty(token)) {
                refreshAllToken();
                token = (String) redisTemplate.opsForValue().get(tokenReids);
            }

            //redis获取货主
            String partnerKey = "partnerKey" + tenantConfig.getTenantId();
            Integer wmsMemberId = (Integer) redisTemplate.opsForValue().get(partnerKey);
            if (null == wmsMemberId) {
                refreshAllToken();
                wmsMemberId = (Integer) redisTemplate.opsForValue().get(partnerKey);
            }


            try {

                K3CloudApi api = new K3CloudApi();
                QueryParam<List<Map<String, Object>>> para = new QueryParam<>();
                para.setFormId("SAL_OUTSTOCK");
                //                 单据编号，  客户，     物料编码，      数量     销售组织， 日期    仓库      价格     订单类型
                para.setFieldKeys("FBillNo,FCustomerID,FMaterialID,FRealQty,FSaleOrgId,FDate,FStockID,FPrice,FBillTypeID");
                Map<String, Object> map = new HashMap<>();
                map.put("Left", "(");
                map.put("FieldName", "FDate");
                map.put("Compare", ">=");
                String yesterday = DateUtils.getYesterday(DateUtils.YYYY_MM_DD);
                map.put("Value", yesterday + "T00:00:00");
                map.put("Right", ")");
                map.put("Logic", "and");

                Map<String, Object> mapStockId = new HashMap<>();
                mapStockId.put("Left", "(");
                mapStockId.put("FieldName", "FStockID");
                mapStockId.put("Compare", "=");
                mapStockId.put("Value", tenantConfig.getSellCloudStockId());
                mapStockId.put("Right", ")");
                mapStockId.put("Logic", "and");

                List<Map<String, Object>> list = new ArrayList<>();
                list.add(map);
                list.add(mapStockId);
                para.setFilterString(list);
                List<List<Object>> lists = api.executeBillQuery(para.toJson());
                List<OrderCreateParams> orderList = new ArrayList<>();

                //还要兼容2个商品在一个出库单
                for (List<Object> kingdeeCkd : lists) {

                    //先去redis里面找  如果有相同的订单号则跳过
                    String key = "LongXiangOrder" + kingdeeCkd.get(0).toString();
                    if (null != redisTemplate.opsForValue().get(key)) {
                        continue;
                    }

                    boolean flag = true;
                    if (!ListUtils.isEmpty(orderList)) {
                        for (OrderCreateParams orderCreateParams : orderList) {
                            //说明有一样的订单号  这时候添加一个sku在原来的订单号内
                            if (orderCreateParams.getRaw_source_id().equals(kingdeeCkd.get(0).toString())) {
                                ItemSku sku = new ItemSku();
                                //查询物料编码
                                String Fnumber = mtestQueryMaterial2(kingdeeCkd.get(2).toString());
                                ByMaterialOut byMaterialOut = byMaterialOutMapper.selectByMaterialOutByCode(Fnumber);
                                if (null != byMaterialOut) {
                                    sku.setSku_id(byMaterialOut.getInMaterialCode());
                                } else {
                                    //如果查询不到物料编码则开启同步
                                    skuSync(null);
                                    byMaterialOut = byMaterialOutMapper.selectByMaterialOutByCode(Fnumber);
                                    sku.setSku_id(byMaterialOut.getInMaterialCode());
                                }
                                //是否赠品
                                sku.setIs_gift(false);
                                //数量
                                sku.setQty((Double) kingdeeCkd.get(3));
                                //单价
                                sku.setPrice((Double) kingdeeCkd.get(7));
                                //金额
                                sku.setBase_price((Double) kingdeeCkd.get(7));

                                orderCreateParams.getItems().add(sku);
                                flag = false;
                            }
                        }
                        if (!flag) {
                            continue;
                        }
                    }
                    //通过物料ID获取商品信息
                    OrderCreateParams order = new OrderCreateParams();
                    order.setTenant_id(tenantConfig.getTenantId());
                    ArrayList<ItemSku> itemSkus = new ArrayList<>();
                    ItemSku sku = new ItemSku();
                    //查询物料编码
                    String Fnumber = mtestQueryMaterial2(kingdeeCkd.get(2).toString());
                    ByMaterialOut byMaterialOut = byMaterialOutMapper.selectByMaterialOutByCode(Fnumber);
                    if (null != byMaterialOut) {
                        sku.setSku_id(byMaterialOut.getInMaterialCode());
                    } else {
                        //如果查询不到物料编码则开启同步
                        skuSync(null);
                        byMaterialOut = byMaterialOutMapper.selectByMaterialOutByCode(Fnumber);
                        sku.setSku_id(byMaterialOut.getInMaterialCode());
                    }
                    //是否赠品
                    sku.setIs_gift(false);
                    //数量
                    sku.setQty((Double) kingdeeCkd.get(3));
                    //单价
                    sku.setPrice((Double) kingdeeCkd.get(7));
                    //金额
                    sku.setBase_price((Double) kingdeeCkd.get(7));
                    itemSkus.add(sku);
                    order.setItems(itemSkus);

                    order.setUp_source_channel("OPENB2B_KINGDEE");
                    //订单号
                    order.setRaw_source_id(kingdeeCkd.get(0).toString());

                    order.setShop_status("WAIT_SELLER_SEND_GOODS");

                    //是否货到付款
                    order.setIs_cod(false);
                    //运费
                    order.setFreight(0.01);

                    //查询具体金蝶销售出库单的客户信息

                    Map customerInfo = queryCustomerInfo(kingdeeCkd.get(1).toString());
                    if (null != customerInfo) {
                        //详细地址
                        String address = (String) customerInfo.get("ADDRESS");
                        order.setReceiver_address(address);

                        //收件人电话
                        String tel = (String) customerInfo.get("TEL");
                        if (StringUtils.isNotEmpty(tel)) {
                            order.setReceiver_mobile(tel);
                        } else {
                            order.setReceiver_mobile("");
                        }
                        //客户名称
                        List<LinkedTreeMap<String, Object>> namesList = (ArrayList<LinkedTreeMap<String, Object>>) customerInfo.get("Name");
                        String name = (String) namesList.get(0).get("Value");
                        if (StringUtils.isNotEmpty(name)) {
                            //收件人
                            order.setReceiver_name(name);
                        } else {
                            order.setReceiver_name("");
                        }

                        List bd_customerext = (ArrayList<LinkedTreeMap<String, Object>>) customerInfo.get("BD_CUSTOMEREXT");
                        Map custMap = (LinkedTreeMap<String, Object>) bd_customerext.get(0);
                        //省
                        Map province = (LinkedTreeMap<String, Object>) custMap.get("PROVINCE");
                        List provinceValue = (ArrayList<LinkedTreeMap<String, Object>>) province.get("FDataValue");
                        Map provinceMap = (LinkedTreeMap<String, Object>) provinceValue.get(0);
                        String provinceName = (String) provinceMap.get("Value");
                        OmsArea omsAreaProvince = omsAreaMapper.selectOmsAreaByExtName(provinceName);
                        String provinceId = "";
                        String cityId = "";
                        String areaCountyId = "";
                        if (null != omsAreaProvince) {
                            provinceId = omsAreaProvince.getId();
                            //收件信息 省
                            order.setReceiver_province(provinceName);
                            //省编码
                            order.setReceiver_province_code(provinceId);
                        } else {
                            omsAreaProvince = omsAreaMapper.selectOmsAreaByExtNameFuzzy(provinceName);
                            if (null == omsAreaProvince) {
                                //收件信息 省
                                order.setReceiver_province("");
                                //省编码
                                order.setReceiver_province_code("");
                                log.error(SYS + "省份匹配失败,省份名称:" + provinceName);
                            } else {
                                provinceId = omsAreaProvince.getId();
                                //收件信息 省
                                order.setReceiver_province(provinceName);
                                //省编码
                                order.setReceiver_province_code(provinceId);
                            }
                        }

                        //市
                        Map city = (LinkedTreeMap<String, Object>) custMap.get("CITY");
                        List cityValue = (ArrayList<LinkedTreeMap<String, Object>>) city.get("FDataValue");
                        Map cityMap = (LinkedTreeMap<String, Object>) cityValue.get(0);
                        String cityName = (String) cityMap.get("Value");
                        OmsArea omsAreaCity = omsAreaMapper.selectOmsAreaByExtNameAndPid(cityName, provinceId);
                        if (null != omsAreaCity) {
                            cityId = omsAreaCity.getId();
                            //市
                            order.setReceiver_city(cityName);
                            //市编码
                            order.setReceiver_city_code(cityId);
                        } else {
                            omsAreaCity = omsAreaMapper.selectOmsAreaByExtNameFuzzy(cityName);
                            if (null == omsAreaCity) {
                                //市
                                order.setReceiver_city("");
                                //市编码
                                order.setReceiver_city_code("");
                                log.error(SYS + "城市匹配失败,城市名称:" + cityName);
                            } else {
                                cityId = omsAreaCity.getId();
                                //市
                                order.setReceiver_city(cityName);
                                //市编码
                                order.setReceiver_city_code(cityId);
                            }
                        }

                        //县(区)
                        Map fCounty = (LinkedTreeMap<String, Object>) custMap.get("FCounty");
                        List fCountyValue = (ArrayList<LinkedTreeMap<String, Object>>) fCounty.get("FDataValue");
                        Map fCountyMap = (LinkedTreeMap<String, Object>) fCountyValue.get(0);
                        String fCountyName = (String) fCountyMap.get("Value");
                        OmsArea omsAreaCounty = omsAreaMapper.selectOmsAreaByExtNameAndPid(fCountyName, cityId);
                        if (null != omsAreaCounty) {
                            areaCountyId = omsAreaCounty.getId();
                            //区
                            order.setReceiver_district(fCountyName);
                            //区编码
                            order.setReceiver_district_code(areaCountyId);
                        } else {
                            omsAreaCounty = omsAreaMapper.selectOmsAreaByExtNameFuzzy(fCountyName);
                            if (null == omsAreaCounty) {
                                //区
                                order.setReceiver_district("");
                                //区编码
                                order.setReceiver_district_code("");
                                log.error(SYS + "区匹配失败,区名称:" + fCountyName);
                            } else {
                                areaCountyId = omsAreaCounty.getId();
                                //区
                                order.setReceiver_district(fCountyName);
                                //区编码
                                order.setReceiver_district_code(areaCountyId);
                            }
                        }

                    }

                    //抵扣金额
                    order.setFree_amount(0.00);
                    //订单日期
                    String date = kingdeeCkd.get(5).toString().substring(0, 10) + " " + kingdeeCkd.get(5).toString().substring(12, 19);
                    order.setOrder_date(date);
                    //支付信息
                    PayDomain payDomain = new PayDomain();
                    //金额
                    payDomain.setAmount(0.01);
                    //当前日期加上随机数生成字符串
                    String dateFormat = DateUtils.getDateFormat(DateUtils.DATESTOREFORMAT);
                    //获取四位随机数
                    String random = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
                    payDomain.setOuter_pay_id(dateFormat + random);
                    payDomain.setPay_date(date);
                    //支付渠道
                    payDomain.setPayment("微信");
                    order.setPay(payDomain);

                    orderList.add(order);
                }


                for (OrderCreateParams orderCreateParams : orderList) {
                    createOrder(orderCreateParams, token, tenantConfig.getOmsUrl(), tenantConfig.getChannelCode(), tenantConfig.getTenantId());
                }
            } catch (Exception e) {
                log.error(SYS + "createOrder.error:" + e.getMessage());
            }
        }
        return AjaxResult.success();

    }

    @Override
    public AjaxResult orderOtherSync() {

        //获取到所有有效的租户配置信息
        List<ByKingdeeConfig> kingdeeConfigListAll = byKingdeeConfigMapper.selectByKingdeeConfigListAll();
        for (ByKingdeeConfig byKingdeeConfig : kingdeeConfigListAll) {
            String configKey = "KingdeeConfi" + byKingdeeConfig.getTenantId();
            ByKingdeeConfig tenantConfig = (ByKingdeeConfig) redisTemplate.opsForValue().get(configKey);
            if (null == (tenantConfig)) {
                refreshAllToken();
                tenantConfig = (ByKingdeeConfig) redisTemplate.opsForValue().get(configKey);
            }

            String tokenReids = "LongXiangToken" + tenantConfig.getTenantId();
            String token = (String) redisTemplate.opsForValue().get(tokenReids);
            if (StringUtils.isEmpty(token)) {
                refreshAllToken();
                token = (String) redisTemplate.opsForValue().get(tokenReids);
            }

            //redis获取货主
            String partnerKey = "partnerKey" + tenantConfig.getTenantId();
            Integer wmsMemberId = (Integer) redisTemplate.opsForValue().get(partnerKey);
            if (null == wmsMemberId) {
                refreshAllToken();
                wmsMemberId = (Integer) redisTemplate.opsForValue().get(partnerKey);
            }

            try {

                K3CloudApi api = new K3CloudApi();
                QueryParam<List<Map<String, Object>>> para = new QueryParam<>();
                para.setFormId("STK_MisDelivery");
                //                 单据编号，  物料编码，     数量   日期    仓库      价格   客户id   订单类型
                para.setFieldKeys("FBillNo,FMaterialID,FBaseQty,FDate,FStockID,FPrice,FCustId,FBillTypeID");
                Map<String, Object> map = new HashMap<>();
                map.put("Left", "(");
                map.put("FieldName", "FDate");
                map.put("Compare", ">=");
                String yesterday = DateUtils.getYesterday(DateUtils.YYYY_MM_DD);
                map.put("Value", yesterday + "T00:00:00");
                map.put("Right", ")");
                map.put("Logic", "and");

                Map<String, Object> mapStockId = new HashMap<>();
                mapStockId.put("Left", "(");
                mapStockId.put("FieldName", "FStockID");
                mapStockId.put("Compare", "=");
                mapStockId.put("Value", tenantConfig.getOtherCloudStockId());
                mapStockId.put("Right", ")");
                mapStockId.put("Logic", "and");

                Map<String, Object> billType = new HashMap<>();
                billType.put("Left", "(");
                billType.put("FieldName", "FBillTypeID");
                billType.put("Compare", "=");
                billType.put("Value", tenantConfig.getOtherCloudOrderType());
                billType.put("Right", ")");
                billType.put("Logic", "and");

                List<Map<String, Object>> list = new ArrayList<>();
                list.add(map);
                list.add(mapStockId);
                //todo 金蝶其他出库单类型不生效   存疑
//        list.add(billType);
                para.setFilterString(list);
                List<List<Object>> lists = api.executeBillQuery(para.toJson());
                List<OrderCreateParams> orderList = new ArrayList<>();

                if (ListUtils.isEmpty(lists)) {
                    return AjaxResult.success("金蝶其他出库单列表为空");
                }
                for (List<Object> kingdeeCkd : lists) {
                    //获取具体其他出库单信息

                    //先去redis里面找  如果有相同的订单号则跳过
                    String key = "LongXiangOrder" + kingdeeCkd.get(0).toString();
                    if (null != redisTemplate.opsForValue().get(key)) {
                        continue;
                    }
                    boolean flag = true;
                    if (!ListUtils.isEmpty(orderList)) {
                        for (OrderCreateParams orderCreateParams : orderList) {
                            //说明有一样的订单号  这时候添加一个sku在原来的订单号内
                            if (orderCreateParams.getRaw_source_id().equals(kingdeeCkd.get(0).toString())) {
                                ItemSku sku = new ItemSku();
                                //查询物料编码
                                String Fnumber = mtestQueryMaterial2(kingdeeCkd.get(1).toString());
                                ByMaterialOut byMaterialOut = byMaterialOutMapper.selectByMaterialOutByCode(Fnumber);
                                if (null != byMaterialOut) {
                                    sku.setSku_id(byMaterialOut.getInMaterialCode());
                                } else {
                                    //如果查询不到物料编码则开启同步
                                    skuSync(null);
                                    byMaterialOut = byMaterialOutMapper.selectByMaterialOutByCode(Fnumber);
                                    sku.setSku_id(byMaterialOut.getInMaterialCode());
                                }
                                //是否赠品
                                sku.setIs_gift(false);
                                //数量
                                sku.setQty((Double) kingdeeCkd.get(3));
                                //单价
                                sku.setPrice((Double) kingdeeCkd.get(4));
                                //金额
                                sku.setBase_price((Double) kingdeeCkd.get(4));

                                orderCreateParams.getItems().add(sku);
                                flag = false;
                            }
                        }
                        if (!flag) {
                            continue;
                        }
                    }
                    //通过物料ID获取商品信息
                    OrderCreateParams order = new OrderCreateParams();
                    order.setTenant_id(tenantConfig.getTenantId());
                    ArrayList<ItemSku> itemSkus = new ArrayList<>();
                    ItemSku sku = new ItemSku();
                    //查询物料编码
                    String Fnumber = mtestQueryMaterial2(kingdeeCkd.get(1).toString());
                    ByMaterialOut byMaterialOut = byMaterialOutMapper.selectByMaterialOutByCode(Fnumber);
                    if (null != byMaterialOut) {
                        sku.setSku_id(byMaterialOut.getInMaterialCode());
                    } else {
                        //如果查询不到物料编码则开启同步
                        skuSync(null);
                        byMaterialOut = byMaterialOutMapper.selectByMaterialOutByCode(Fnumber);
                        sku.setSku_id(byMaterialOut.getInMaterialCode());
                    }
                    //是否赠品
                    sku.setIs_gift(false);
                    //数量
                    sku.setQty((Double) kingdeeCkd.get(2));
                    //单价
                    sku.setPrice((Double) kingdeeCkd.get(5));
                    //金额
                    sku.setBase_price((Double) kingdeeCkd.get(5));
                    itemSkus.add(sku);
                    order.setItems(itemSkus);

                    order.setUp_source_channel("OPENB2B_KINGDEE");
                    //订单号
                    order.setRaw_source_id(kingdeeCkd.get(0).toString());

                    order.setShop_status("WAIT_SELLER_SEND_GOODS");

                    //是否货到付款
                    order.setIs_cod(false);
                    //运费
                    order.setFreight(0.01);

                    //查询具体金蝶销售出库单的客户信息

                    Map customerInfo = queryCustomerInfo(kingdeeCkd.get(6).toString());
                    if (null != customerInfo) {
                        //详细地址
                        String address = (String) customerInfo.get("ADDRESS");
                        order.setReceiver_address(address);

                        //收件人电话
                        String tel = (String) customerInfo.get("TEL");
                        if (StringUtils.isNotEmpty(tel)) {
                            order.setReceiver_mobile(tel);
                        } else {
                            order.setReceiver_mobile("");
                        }
                        //客户名称
                        List<LinkedTreeMap<String, Object>> namesList = (ArrayList<LinkedTreeMap<String, Object>>) customerInfo.get("Name");
                        String name = (String) namesList.get(0).get("Value");
                        if (StringUtils.isNotEmpty(name)) {
                            //收件人
                            order.setReceiver_name(name);
                        } else {
                            order.setReceiver_name("");
                        }

                        List bd_customerext = (ArrayList<LinkedTreeMap<String, Object>>) customerInfo.get("BD_CUSTOMEREXT");
                        Map custMap = (LinkedTreeMap<String, Object>) bd_customerext.get(0);
                        //省
                        Map province = (LinkedTreeMap<String, Object>) custMap.get("PROVINCE");
                        List provinceValue = (ArrayList<LinkedTreeMap<String, Object>>) province.get("FDataValue");
                        Map provinceMap = (LinkedTreeMap<String, Object>) provinceValue.get(0);
                        String provinceName = (String) provinceMap.get("Value");
                        OmsArea omsAreaProvince = omsAreaMapper.selectOmsAreaByExtName(provinceName);
                        String provinceId = "";
                        String cityId = "";
                        String areaCountyId = "";
                        if (null != omsAreaProvince) {
                            provinceId = omsAreaProvince.getId();
                            //收件信息 省
                            order.setReceiver_province(provinceName);
                            //省编码
                            order.setReceiver_province_code(provinceId);
                        } else {
                            omsAreaProvince = omsAreaMapper.selectOmsAreaByExtNameFuzzy(provinceName);
                            if (null == omsAreaProvince) {
                                //收件信息 省
                                order.setReceiver_province("");
                                //省编码
                                order.setReceiver_province_code("");
                                log.error(SYS + "省份匹配失败,省份名称:" + provinceName);
                            } else {
                                provinceId = omsAreaProvince.getId();
                                //收件信息 省
                                order.setReceiver_province(provinceName);
                                //省编码
                                order.setReceiver_province_code(provinceId);
                            }
                        }
                        //市
                        Map city = (LinkedTreeMap<String, Object>) custMap.get("CITY");
                        List cityValue = (ArrayList<LinkedTreeMap<String, Object>>) city.get("FDataValue");
                        Map cityMap = (LinkedTreeMap<String, Object>) cityValue.get(0);
                        String cityName = (String) cityMap.get("Value");
                        OmsArea omsAreaCity = omsAreaMapper.selectOmsAreaByExtNameAndPid(cityName, provinceId);
                        if (null != omsAreaCity) {
                            cityId = omsAreaCity.getId();
                            //市
                            order.setReceiver_city(cityName);
                            //市编码
                            order.setReceiver_city_code(cityId);
                        } else {
                            omsAreaCity = omsAreaMapper.selectOmsAreaByExtNameFuzzy(cityName);
                            if (null == omsAreaCity) {
                                //市
                                order.setReceiver_city("");
                                //市编码
                                order.setReceiver_city_code("");
                                log.error(SYS + "城市匹配失败,城市名称:" + cityName);
                            } else {
                                cityId = omsAreaCity.getId();
                                //市
                                order.setReceiver_city(cityName);
                                //市编码
                                order.setReceiver_city_code(cityId);
                            }
                        }

                        //县(区)
                        Map fCounty = (LinkedTreeMap<String, Object>) custMap.get("FCounty");
                        List fCountyValue = (ArrayList<LinkedTreeMap<String, Object>>) fCounty.get("FDataValue");
                        Map fCountyMap = (LinkedTreeMap<String, Object>) fCountyValue.get(0);
                        String fCountyName = (String) fCountyMap.get("Value");
                        OmsArea omsAreaCounty = omsAreaMapper.selectOmsAreaByExtNameAndPid(fCountyName, cityId);
                        if (null != omsAreaCounty) {
                            areaCountyId = omsAreaCounty.getId();
                            //区
                            order.setReceiver_district(fCountyName);
                            //区编码
                            order.setReceiver_district_code(areaCountyId);
                        } else {
                            omsAreaCounty = omsAreaMapper.selectOmsAreaByExtNameFuzzy(fCountyName);
                            if (null == omsAreaCounty) {
                                //区
                                order.setReceiver_district("");
                                //区编码
                                order.setReceiver_district_code("");
                                log.error(SYS + "区匹配失败,区名称:" + fCountyName);
                            } else {
                                areaCountyId = omsAreaCounty.getId();
                                //区
                                order.setReceiver_district(fCountyName);
                                //区编码
                                order.setReceiver_district_code(areaCountyId);
                            }
                        }
                        //抵扣金额
                        order.setFree_amount(0.00);
                        //订单日期
                        String date = kingdeeCkd.get(3).toString().substring(0, 10) + " " + kingdeeCkd.get(3).toString().substring(12, 19);
                        order.setOrder_date(date);
                        //支付信息
                        PayDomain payDomain = new PayDomain();
                        //金额
                        payDomain.setAmount(0.01);
                        //当前日期加上随机数生成字符串
                        String dateFormat = DateUtils.getDateFormat(DateUtils.DATESTOREFORMAT);
                        //获取四位随机数
                        String random = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
                        payDomain.setOuter_pay_id(dateFormat + random);
                        payDomain.setPay_date(date);
                        //支付渠道
                        payDomain.setPayment("微信");
                        order.setPay(payDomain);

                        orderList.add(order);
                    }
                }


                for (OrderCreateParams orderCreateParams : orderList) {
                    createOrder(orderCreateParams, token, tenantConfig.getOmsUrl(), tenantConfig.getChannelCode(), tenantConfig.getTenantId());
                }

            } catch (Exception e) {
                log.error(SYS + "orderOtherSync.error:" + e.getMessage());
            }

        }
        return AjaxResult.success();
    }


    private Map queryCustomerInfo(String customerId) {
        try {
            OperateParam para = new OperateParam();
            //客户ID
            para.setId(customerId);
            OperatorResult result = api.view("BD_Customer", para);
            Gson gson = new Gson();
            if (result.getResult().getResponseStatus().isIsSuccess()) {
                Map<String, Object> resultMap = (LinkedTreeMap<String, Object>) result.getResult().getResult();
                if (null != resultMap) {
                    return resultMap;
                }
                System.out.printf("客户查看接口: %s%n", gson.toJson(result.getResult()));
            } else {
                fail("客户查看接口: " + gson.toJson(result.getResult()));
            }
        } catch (Exception e) {

        }
        return null;
    }


    public String mtestQueryMaterial2(String id) throws Exception {
        K3CloudApi api = new K3CloudApi();
        Gson gson = new Gson();
        QueryParam<List<Map<String, Object>>> para = new QueryParam<>();
        para.setFormId("BD_Material");
        para.setFieldKeys("FMATERIALID,FNumber,FName,FCreateOrgId,FUseOrgId");
        Map<String, Object> map = new HashMap<>();
        map.put("Left", "(");
        map.put("FieldName", "FMATERIALID");
        map.put("Compare", "=");
        map.put("Value", id);
        map.put("Right", ")");
        map.put("Logic", "and");
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(map);
        para.setFilterString(list);
        List result = api.executeBillQuery(para, BdCustomer.class);
        if (ListUtils.isEmpty(result)) {
            return null;
        }
        BdCustomer res = (BdCustomer) result.get(0);
        return res.getFNumber();
    }

    //订单创建
    private void createOrder(OrderCreateParams order, String token, String omsUrl, String channelCode, String tenantId) {

        RequestOrderDomain requestOrderDomain = new RequestOrderDomain();
        requestOrderDomain.setBiz_content(order);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JsonUtil.toJsonString(requestOrderDomain));
        Request request = new Request.Builder()
                .url(omsUrl + "/oms/createOrder")
                .method("POST", body)
                .addHeader("Authorization", "Bearer " + token)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Content-Type", "application/json")
                .build();


        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            ResponseMsg jsonToObject = JsonUtil.buildNonNullBinder().getJsonToObject(string, ResponseMsg.class);
            if (!"200".equals(jsonToObject.getCode())) {
                //保存失败回执信息
                BySynMaterialMsg responseMsgDomain = new BySynMaterialMsg();
                responseMsgDomain.setMsgCode("" + response.code());
                responseMsgDomain.setMsgContext(response.message());
                responseMsgDomain.setResponseCode(jsonToObject.getCode());
                responseMsgDomain.setResponseMsg(jsonToObject.getMsg());
                responseMsgDomain.setOperateCode("createOrder");
                responseMsgDomain.setSyncMaterialCode(order.getRaw_source_id());
                responseMsgDomain.setSyncChannelCode(channelCode);
                responseMsgDomain.setCreateTime(new Date());
                responseMsgDomain.setTenantId(tenantId);
                bySynMaterialMsgMapper.insertBySynMaterialMsg(responseMsgDomain);
                log.error("订单创建失败" + jsonToObject.getMsg());
            } else {
                //保存成功回执信息
                BySynMaterialMsg responseMsgDomain = new BySynMaterialMsg();
                responseMsgDomain.setMsgCode("" + response.code());
                responseMsgDomain.setMsgContext(response.message());
                responseMsgDomain.setResponseCode(jsonToObject.getCode());
                responseMsgDomain.setResponseMsg(jsonToObject.getMsg());
                responseMsgDomain.setOperateCode("createOrder");
                responseMsgDomain.setSyncMaterialCode(order.getRaw_source_id());
                responseMsgDomain.setSyncChannelCode(channelCode);
                responseMsgDomain.setCreateTime(new Date());
                responseMsgDomain.setTenantId(tenantId);
                bySynMaterialMsgMapper.insertBySynMaterialMsg(responseMsgDomain);
                log.info(SYS + order.getRaw_source_id() + "订单创建成功");

                //放进redis里
                String key = "LongXiangOrder" + order.getRaw_source_id();
                redisTemplate.opsForValue().set(key, order.toString(), 7, TimeUnit.DAYS);
            }

        } catch (Exception e) {

        }
    }

    /**
     * @return
     * @throws Exception
     */
    @Override
    public AjaxResult createOrderBatch() throws Exception {
        return null;
    }

    /**
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public AjaxResult getOrder(String orderId) throws Exception {
        return null;
    }

    /**
     * @return
     * @throws Exception
     */
    @Override
    public AjaxResult orderDelivery() throws Exception {
        return null;
    }

    /**
     * @return
     * @throws Exception
     */
    @Override
    public AjaxResult orderMaterial() throws Exception {
        return null;
    }

    @Override
    public AjaxResult createSaleOutOrder() throws Exception {
        return null;
    }

    @Override
    public AjaxResult syncTransferDirect() {
        //获取到所有有效的租户配置信息
        List<ByKingdeeConfig> kingdeeConfigListAll = byKingdeeConfigMapper.selectByKingdeeConfigListAll();
        for (ByKingdeeConfig byKingdeeConfig : kingdeeConfigListAll) {
            String configKey = "KingdeeConfi" + byKingdeeConfig.getTenantId();
            ByKingdeeConfig tenantConfig = (ByKingdeeConfig) redisTemplate.opsForValue().get(configKey);
            if (null == (tenantConfig)) {
                refreshAllToken();
                tenantConfig = (ByKingdeeConfig) redisTemplate.opsForValue().get(configKey);
            }

            String tokenReids = "LongXiangToken" + tenantConfig.getTenantId();
            String token = (String) redisTemplate.opsForValue().get(tokenReids);
            if (StringUtils.isEmpty(token)) {
                refreshAllToken();
                token = (String) redisTemplate.opsForValue().get(tokenReids);
            }

            //redis获取货主
            String partnerKey = "partnerKey" + tenantConfig.getTenantId();
            Integer wmsMemberId = (Integer) redisTemplate.opsForValue().get(partnerKey);
            if (null == wmsMemberId) {
                refreshAllToken();
                wmsMemberId = (Integer) redisTemplate.opsForValue().get(partnerKey);
            }

            try {
                //获取直接调拨单指定的仓库id
                String kingdeeStockTransferId = byKingdeeConfig.getTransferCloudStockId();

                K3CloudApi api = new K3CloudApi();
                QueryParam<List<Map<String, Object>>> para = new QueryParam<>();
                para.setFormId("STK_TransferDirect");
                //                  日期    调拨单号   单据类型      调入货主类型        调入货主        调出货主类型         调出货主         调拨方向          物料编码      物料名称        调出仓库      调入仓库      单位   数量  成本价
                para.setFieldKeys("FDate,FBillNo,FBillTypeID,FOwnerTypeIdHead,FOwnerIdHead,FOwnerTypeOutIdHead,FOwnerOutIdHead,FTransferDirect,FMaterialId,FMaterialName,FSrcStockId,FDestStockId,FUnitID,FQty,FPrice");
                Map<String, Object> map = new HashMap<>();
                map.put("Left", "(");
                map.put("FieldName", "FDate");
                map.put("Compare", ">=");
                String yesterday = DateUtils.getYesterday(DateUtils.YYYY_MM_DD);
                map.put("Value", yesterday + "T00:00:00");
                map.put("Right", ")");
                map.put("Logic", "and");

                //查询如果是指定仓库转入   则增加库存
                Map<String, Object> destStockIdMap = new HashMap<>();
                destStockIdMap.put("Left", "(");
                destStockIdMap.put("FieldName", "FDestStockId");
                destStockIdMap.put("Compare", "=");
                destStockIdMap.put("Value", kingdeeStockTransferId);
                destStockIdMap.put("Right", ")");
                destStockIdMap.put("Logic", "or");
                List<Map<String, Object>> list = new ArrayList<>();
                list.add(map);
                list.add(destStockIdMap);

                para.setFilterString(list);
                List<List<Object>> lists = api.executeBillQuery(para.toJson());
                for (List<Object> objects : lists) {
                    //如果调入仓库是的，就是调入lists = {ArrayList@12952}  size = 3
                    if ((objects.get(11).toString()).equals(kingdeeStockTransferId)) {

                        //先去redis里面找  如果有相同的订单号则跳过
                        String key = "LongXiangTransferOrder" + objects.get(1).toString() + objects.get(8).toString();
                        if (null != redisTemplate.opsForValue().get(key)) {
                            continue;
                        }
                        KingdeeTransferDirect kingdeeTransferDirect = new KingdeeTransferDirect();
                        kingdeeTransferDirect.setSendFlag("1");
                        kingdeeTransferDirect.setFBillNo(objects.get(1).toString());
                        kingdeeTransferDirect.setFMaterialId(objects.get(8).toString());
                        List<KingdeeTransferDirect> kingdeeTransferDirects = kingdeeTransferDirectMapper.selectKingdeeTransferDirectList(kingdeeTransferDirect);
                        if (!ListUtils.isEmpty(kingdeeTransferDirects)) {
                            redisTemplate.opsForValue().set(key, key, 7, TimeUnit.DAYS);
                            continue;
                        }

                        //调用oms接口增加WMS库存
                        List<UpdateWmsStockItems> resItems = new ArrayList<>();
                        UpdateWmsStockItems updateWmsStockItems = new UpdateWmsStockItems();
                        ByMaterialOut materialInfo = byMaterialOutMapper.selectByMaterialOutByOutId(objects.get(8).toString());
                        if (null != materialInfo) {
                            updateWmsStockItems.setSku_id(materialInfo.getInMaterialCode());
                            updateWmsStockItems.setQty(((Double) objects.get(13)).intValue());
                        }
                        log.info("调入仓库是" + kingdeeStockTransferId + "的调拨单");

                        resItems.add(updateWmsStockItems);
                        AjaxResult ajaxResult = updateWmsStock(resItems, objects, wmsMemberId, tenantConfig.getOmsUrl(), token, tenantConfig.getChannelCode(), tenantConfig.getTenantId());
                        if (0 != (Integer) ajaxResult.get("code")) {
                            return ajaxResult;
                        }
                    }
                }
            } catch (Exception e) {
                log.error("查询直接调拨单列表接口异常", e);
            }
        }
        return AjaxResult.success();
    }

    /**
     * @param skuCode
     * @return
     * @throws Exception
     */
    @Override
    public AjaxResult getSkuStock(String skuCode) throws Exception {
        return null;
    }


    //获取code
    private String getCode(String omsUrl, String clientId, String projectId, String redirectUri) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("client_id", clientId)
                .addFormDataPart("project_id", projectId)
                .addFormDataPart("redirect_uri", redirectUri)
                .addFormDataPart("response_type", "code")
                .addFormDataPart("state", "login")
                .build();
        Request request = new Request.Builder()
                .url(omsUrl + "/ua/login_page")
                .method("POST", body)
                .addHeader("Authorization", "Bearer {{access_token}}")
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            if (200 != response.code()) {
                ResponseCodeErrorMsg jsonToObject = JsonUtil.buildNonNullBinder().getJsonToObject(string, ResponseCodeErrorMsg.class);
                log.error("获取code失败" + jsonToObject.getErrors().get(0));
                return null;
            }
            ResponseCode jsonToObject = JsonUtil.buildNonNullBinder().getJsonToObject(string, ResponseCode.class);
            return jsonToObject.getAuthorize_code();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    //获取token
    private String getToken(String authorize_code, String clientId, String clientSecret, String redirectUri, String omsUrl) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("client_id", clientId)
                .addFormDataPart("client_secret", clientSecret)
                .addFormDataPart("redirect_uri", redirectUri)
                .addFormDataPart("authorize_code", authorize_code)
                .build();
        Request request = new Request.Builder()
                .url(omsUrl + "/ua/access_token")
                .method("POST", body)
                .addHeader("Authorization", "Bearer {{access_token}}")
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            ResponseToken jsonToObject = JsonUtil.buildNonNullBinder().getJsonToObject(string, ResponseToken.class);
            return jsonToObject.getAccess_token();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //货主查询
    private ResponseWmsCustomer getOwner(String omsUrl, String token, String tenantId) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\r\n    \"biz_content\": {\r\n        \"tenant_id\": \"" + tenantId + "\"\r\n    }\r\n}");
        Request request = new Request.Builder()
                .url(omsUrl + "/oms/omsPartnerQuery")
                .method("POST", body)
                .addHeader("Authorization", "Bearer " + token)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (200 != response.code()) {
                log.error(SYS + "获取货主失败" + response.message());
                return null;
            }
            String string = response.body().string();
            ResponseMsg jsonToObject = JsonUtil.buildNonNullBinder().getJsonToObject(string, ResponseMsg.class);
            List<HashMap<String, Object>> data = (List<HashMap<String, Object>>) jsonToObject.getData();
            if (null == data || data.size() == 0) {
                return null;
            }
            Map<String, Object> stringObjectHashMap = data.get(0);
            ResponseWmsCustomer wmsCustomer = (ResponseWmsCustomer) MapUtils.mapToObject(stringObjectHashMap, ResponseWmsCustomer.class);
            Integer wmsMemberId = wmsCustomer.getId();
            //把货主信息放进redis里
            redisTemplate.opsForValue().set("partnerKey" + tenantId, wmsMemberId, 7, TimeUnit.DAYS);
            return wmsCustomer;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    //修改wms的库存
    private AjaxResult updateWmsStock(List<UpdateWmsStockItems> itms, List<Object> objects, Integer partner_id, String omsUrl, String token, String channelCode, String tenantId) {

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");


        RequestUpdateWmsStock requestUpdateWmsStock = new RequestUpdateWmsStock();
        UpdateWmsStockParams updateWmsStockParams = new UpdateWmsStockParams();
        updateWmsStockParams.setPartner_id(partner_id);
        updateWmsStockParams.setSend_type("B2BRK");
        updateWmsStockParams.setTenant_id(tenantId);
        updateWmsStockParams.setItems(itms);

        requestUpdateWmsStock.setBiz_content(updateWmsStockParams);


        RequestBody body = RequestBody.create(mediaType, JsonUtil.toJsonString(requestUpdateWmsStock));

        Request request = new Request.Builder()
                .url(omsUrl + "/oms/wmsEntryOrder")
                .method("POST", body)
                .addHeader("Authorization", "Bearer " + token)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (200 != response.code()) {
                log.error(SYS + "修改wms库存失败,请求失败" + response.message());
                //保存失败回执信息
                BySynMaterialMsg responseMsgDomain = new BySynMaterialMsg();
                responseMsgDomain.setMsgCode("" + response.code());
                responseMsgDomain.setMsgContext(response.message());
                responseMsgDomain.setResponseCode("" + response.code());
                responseMsgDomain.setResponseMsg(response.message());
                responseMsgDomain.setOperateCode("updateWmsStock");
                responseMsgDomain.setSyncMaterialCode("");
                responseMsgDomain.setSyncChannelCode(channelCode);
                responseMsgDomain.setCreateTime(new Date());
                responseMsgDomain.setTenantId(tenantId);
                bySynMaterialMsgMapper.insertBySynMaterialMsg(responseMsgDomain);

                return AjaxResult.error(SYS + "修改wms库存请求失败" + response.message());
            }
            String string = response.body().string();
            ResponseMsg jsonToObject = JsonUtil.buildNonNullBinder().getJsonToObject(string, ResponseMsg.class);
            if (!"200".equals(jsonToObject.getCode())) {
                log.error(SYS + "修改wms库存业务失败" + jsonToObject.getMsg());
                //保存失败回执信息
                BySynMaterialMsg responseMsgDomain = new BySynMaterialMsg();
                responseMsgDomain.setMsgCode("" + response.code());
                responseMsgDomain.setMsgContext(response.message());
                responseMsgDomain.setResponseCode(jsonToObject.getCode());
                responseMsgDomain.setResponseMsg(jsonToObject.getMsg());
                responseMsgDomain.setOperateCode("updateWmsStock");
                responseMsgDomain.setSyncMaterialCode("");
                responseMsgDomain.setSyncChannelCode(channelCode);
                responseMsgDomain.setCreateTime(new Date());
                responseMsgDomain.setTenantId(tenantId);
                bySynMaterialMsgMapper.insertBySynMaterialMsg(responseMsgDomain);
                return AjaxResult.error(SYS + "修改wms库存业务失败" + jsonToObject.getMsg());
            }
            //保存成功回执信息
            BySynMaterialMsg responseMsgDomain = new BySynMaterialMsg();
            responseMsgDomain.setMsgCode("" + response.code());
            responseMsgDomain.setMsgContext(response.message());
            responseMsgDomain.setResponseCode(jsonToObject.getCode());
            responseMsgDomain.setResponseMsg(jsonToObject.getMsg());
            responseMsgDomain.setOperateCode("updateWmsStock");
            responseMsgDomain.setSyncMaterialCode((String) jsonToObject.getData());
            responseMsgDomain.setSyncChannelCode(channelCode);
            responseMsgDomain.setCreateTime(new Date());
            responseMsgDomain.setTenantId(tenantId);
            bySynMaterialMsgMapper.insertBySynMaterialMsg(responseMsgDomain);

            KingdeeTransferDirect kingdeeTransferDirect = new KingdeeTransferDirect();
            kingdeeTransferDirect.setCreateTime(new Date());
            kingdeeTransferDirect.setFDate(objects.get(0).toString());
            kingdeeTransferDirect.setFBillNo(objects.get(1).toString());
            kingdeeTransferDirect.setFBillTypeID(objects.get(2).toString());
            kingdeeTransferDirect.setFOwnerTypeIdHead(objects.get(3).toString());
            kingdeeTransferDirect.setFOwnerIdHead(objects.get(4).toString());
            kingdeeTransferDirect.setFOwnerTypeOutIdHead(objects.get(5).toString());
            kingdeeTransferDirect.setFOwnerOutIdHead(objects.get(6).toString());

            kingdeeTransferDirect.setFTransferDirect(objects.get(7).toString());
            kingdeeTransferDirect.setFMaterialId(objects.get(8).toString());
            kingdeeTransferDirect.setFMaterialName(objects.get(9).toString());
            kingdeeTransferDirect.setFSrcStockId(objects.get(10).toString());
            kingdeeTransferDirect.setFDestStockId(objects.get(11).toString());
            kingdeeTransferDirect.setFUnitID(objects.get(12).toString());
            kingdeeTransferDirect.setFQty(objects.get(13).toString());
            kingdeeTransferDirect.setFPrice(objects.get(14).toString());
            kingdeeTransferDirect.setSendFlag("0");
            kingdeeTransferDirectMapper.insertKingdeeTransferDirect(kingdeeTransferDirect);

            String key = "LongXiangTransferOrder" + objects.get(1).toString() + objects.get(8).toString();
            redisTemplate.opsForValue().set(key, key, 7, TimeUnit.DAYS);

            log.info(SYS + "修改wms库存成功");
            return AjaxResult.success("修改wms库存成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
