package com.glxp.mipsdl.client.zaxyy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.glxp.mipsdl.client.CommonHttpClient;
import com.glxp.mipsdl.config.ThirdSysConfig;
import com.glxp.mipsdl.constant.ConstantType;
import com.glxp.mipsdl.constant.Constants;
import com.glxp.mipsdl.dao.auth.AuthUserDao;
import com.glxp.mipsdl.dao.auth.AuthWarehouseDao;
import com.glxp.mipsdl.dao.auth.AuthWarehouseUserMapper;
import com.glxp.mipsdl.dao.basic.BasicBussinessTypeDao;
import com.glxp.mipsdl.dao.basic.BasicCorpDao;
import com.glxp.mipsdl.dao.inout.*;
import com.glxp.mipsdl.dao.thrsys.ThrInvWarehouseDao;
import com.glxp.mipsdl.dao.thrsys.ThrOrderUploadBustypesMapper;
import com.glxp.mipsdl.dao.thrsys.ThrSystemBusApiDao;
import com.glxp.mipsdl.entity.auth.AuthUserEntity;
import com.glxp.mipsdl.entity.auth.AuthWarehouseEntity;
import com.glxp.mipsdl.entity.auth.AuthWarehouseUser;
import com.glxp.mipsdl.entity.basic.BasicBussinessTypeEntity;
import com.glxp.mipsdl.entity.basic.BasicCorpEntity;
import com.glxp.mipsdl.entity.inout.*;
import com.glxp.mipsdl.entity.thrsys.ThrInvWarehouseEntity;
import com.glxp.mipsdl.entity.thrsys.ThrOrderUploadBustypesEntity;
import com.glxp.mipsdl.entity.thrsys.ThrSystemBusApiEntity;
import com.glxp.mipsdl.http.HttpClient;
import com.glxp.mipsdl.req.base.*;
import com.glxp.mipsdl.req.post.*;
import com.glxp.mipsdl.req.zaxyy.ZaZyRequest;
import com.glxp.mipsdl.req.zaxyy.ZaxzyyOrderRequest;
import com.glxp.mipsdl.res.BaseResponse;
import com.glxp.mipsdl.res.udiwms.ZzzyyProductsResponse;
import com.glxp.mipsdl.service.auth.AuthWarehouseService;
import com.glxp.mipsdl.service.order.OrderUploadLogService;
import com.glxp.mipsdl.service.thrsys.ThrCorpService;
import com.glxp.mipsdl.service.thrsys.ThrSystemDetailService;
import com.glxp.mipsdl.util.DateUtil;
import com.glxp.mipsdl.util.IntUtil;
import com.glxp.mipsdl.util.ResultVOUtils;
import com.glxp.mipsdl.util.SubmitOrderUtil;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 诏安县医院，智业V1接口对接
 */
@Slf4j
@Service(value = "100003HttpClient")  //bean注册名称，使用编码 + HttpClient，文件接口加 FileClient
public class ZaxyyClient extends CommonHttpClient {

    @Resource
    private ThrSystemDetailService thrSystemDetailService;
    @Resource
    private HttpClient httpClient;
    @Resource
    private IoOrderDao orderDao;
    @Resource
    private ThrSystemBusApiDao thrSystemBusApiDao;
    @Resource
    private AuthUserDao authUserDao;
    @Resource
    private BasicBussinessTypeDao basicBussinessTypeDao;
    @Resource
    private BasicCorpDao basicCorpDao;
    @Resource
    private IoCodeDao codeDao;
    @Resource
    private AuthWarehouseDao authWarehouseDao;
    @Resource
    private ThrInvWarehouseDao thrInvWarehouseDao;
    @Resource
    private AuthWarehouseService authWarehouseService;
    @Resource
    private ThirdSysConfig thirdSysConfig;
    @Resource
    private ThrCorpService thrCorpService;
    @Resource
    private IoOrderDetailBizDao orderDetailBizDao;
    @Resource
    private IoOrderDetailCodeDao orderDetailCodeDao;


    @Resource
    private IoOrderUploadLogDao orderUploadLogDao;
    @Resource
    private SubmitOrderUtil submitOrderUtil;
    @Resource
    AuthWarehouseUserMapper authWarehouseUserMapper;
    @Resource
    private ThrOrderUploadBustypesMapper thrOrderUploadBustypesMapper;

    /**
     * 拼接xml请求头
     *
     * @param methodName 方法名
     * @return
     */
    public String getMsgHeader(String methodName) {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<root>" +
                "<serverName>" +
                methodName +
                "</serverName>" +
                "</root>";
    }

    public String parserResult(String response) {
        if (response.contains("<root")) {
            try {
                Document document = DocumentHelper.parseText(response);
                String message = document.getRootElement().element("message").getText();
                return message;
            } catch (DocumentException e) {
                log.info("解析诏安智业接口返回结果异常, 返回结果：{}", response);
                log.error("异常信息：", e);
            }
        }
        return response;
    }

    @Override
    public BaseResponse getUnit(UdiwmsUnitRequest udiwmsUnitRequest) {
        ZaZyRequest zaZyRequest = new ZaZyRequest();
        zaZyRequest.setMsgHeader(getMsgHeader("getMaterialUnit"));
        zaZyRequest.setMsgBody(JSONUtil.toJsonStr(udiwmsUnitRequest));
        String response = httpClient.postJson(thrSystemDetailService.getUrlExclude(Constants.URL_NAME_CORP_URL), zaZyRequest);
        response = parserResult(response);
        try {
            BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
            return baseResponse;
        } catch (Exception e) {
            log.error("解析诏安智业接口返回往来单位字典数据异常，返回结果：{}", response);
            log.error("异常信息：{}", e);
            return ResultVOUtils.error(500, "网络错误，或远程服务器异常无法返回正确结果（" + response + ")");
        }
    }

    @Override
    public BaseResponse getProducts(UdiwmsProductRequest udiwmsProductRequest) {
        ZaZyRequest zaZyRequest = new ZaZyRequest();
        zaZyRequest.setMsgHeader(getMsgHeader("getMaterialDict"));
        zaZyRequest.setMsgBody(JSONUtil.toJsonStr(udiwmsProductRequest));
        String response = httpClient.postJson(thrSystemDetailService.getUrlExclude(Constants.URL_NAME_PI_QUERY_URL), zaZyRequest);
        response = parserResult(response);
        try {
            BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
            Map map = (Map) baseResponse.getData();
            List<ZzzyyProductsResponse> zzzyyProductsResponse = JSON.parseArray(map.get("list") + "", ZzzyyProductsResponse.class);
            for (ZzzyyProductsResponse productsResponse : zzzyyProductsResponse) {
                //判断要是规格和型号一致就是取规格 不一致就合并
                if (StrUtil.isNotEmpty(productsResponse.getModel_number()) && StrUtil.isNotEmpty(productsResponse.getStandard())) {
                    if (productsResponse.getModel_number().equals(productsResponse.getStandard())) {
                        productsResponse.setStandard(productsResponse.getStandard());
                    } else {
                        productsResponse.setStandard(productsResponse.getStandard() + productsResponse.getModel_number());
                    }
                } else if (StrUtil.isNotEmpty(productsResponse.getModel_number()) && StrUtil.isBlank(productsResponse.getStandard())) {
                    productsResponse.setStandard(productsResponse.getModel_number());
                }
            }
            map.put("list", JSON.toJSON(zzzyyProductsResponse));
            baseResponse.setData("");
            baseResponse.setData(map);
            return baseResponse;
        } catch (Exception e) {
            log.error("解析诏安智业接口返回产品信息字典数据异常，返回结果：{}", response);
            log.error("异常信息：{}", e);
            return ResultVOUtils.error(500, "网络错误，或远程服务器异常无法返回正确结果（" + response + ")");
        }
    }

    @Override
    public BaseResponse getOrderTypes(UdiwmsBusTypeRequest udiwmsBusTypeRequest) {
        ZaZyRequest zaZyRequest = new ZaZyRequest();
        zaZyRequest.setMsgHeader(getMsgHeader("getMaterialType"));
        zaZyRequest.setMsgBody(JSONUtil.toJsonStr(udiwmsBusTypeRequest));
        String response = httpClient.postJson(thrSystemDetailService.getUrlExclude(Constants.URL_NAME_BUS_TYPE_QUERY_URL), zaZyRequest);
        response = parserResult(response);
        try {
            BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
            return baseResponse;
        } catch (Exception e) {
            log.error("解析诏安智业接口返回单据类型数据异常，返回结果：{}", response);
            log.error("异常信息：{}", e);
            return ResultVOUtils.error(500, "网络错误，或远程服务器异常无法返回正确结果（" + response + ")");
        }
    }

    @Override
    public BaseResponse getOrders(UdiwmsOrderQueryRequest udiwmsOrderQueryRequest) {
        ZaZyRequest zaZyRequest = new ZaZyRequest();
        zaZyRequest.setMsgHeader(getMsgHeader("getMaterialApply"));
        zaZyRequest.setMsgBody(JSONUtil.toJsonStr(udiwmsOrderQueryRequest));
        String response = httpClient.postJson(thrSystemDetailService.getUrlExclude(Constants.URL_NAME_BUS_TYPE_QUERY_URL), zaZyRequest);
        response = parserResult(response);
        try {
            BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
            return baseResponse;
        } catch (Exception e) {
            log.error("解析诏安智业接口返回单据类型数据异常，返回结果：{}", response);
            log.error("异常信息：{}", e);
            return ResultVOUtils.error(500, "网络错误，或远程服务器异常无法返回正确结果（" + response + ")");
        }
    }

    @Resource
    private OrderUploadLogService orderUploadLogService;

    @Override
    public BaseResponse submitOrders(UdiwmsOrderRequest udiwmsOrderRequest) {
        if (StrUtil.isBlank(udiwmsOrderRequest.getBillNo())) {
            return ResultVOUtils.error(500, "单据号不能为空");
        }

        ZaxzyyOrderRequest zaxzyyOrderRequest = new ZaxzyyOrderRequest();
        BeanUtil.copyProperties(udiwmsOrderRequest, zaxzyyOrderRequest);
        //查询单据和详情信息，组装第三方系统接口所需参数
        IoOrderEntity orderEntity = orderDao.selectOne(new QueryWrapper<IoOrderEntity>().eq("billNo", udiwmsOrderRequest.getBillNo()).last("limit 1"));
        zaxzyyOrderRequest.setBillDate(DateUtil.formatDateTime(orderEntity.getCreateTime()));
        //查询对应的第三方单据类型
        ThrSystemBusApiEntity thrSystemBusApiEntity = thrSystemBusApiDao.selectOne(new QueryWrapper<ThrSystemBusApiEntity>().eq("code", udiwmsOrderRequest.getBillType()));
        if (StrUtil.isBlank(thrSystemBusApiEntity.getUrl())) {
            return ResultVOUtils.error(500, "接口未配置，无法提交！");
        }
        zaxzyyOrderRequest.setThirdSys(getUserName(orderEntity));
        zaxzyyOrderRequest.setBillType(thrSystemBusApiEntity.getThirdBuyCode());
        zaxzyyOrderRequest.setBillFlag("1");

        //查询单据类型
        BasicBussinessTypeEntity basicBussinessTypeEntity = basicBussinessTypeDao.selectByAction(udiwmsOrderRequest.getBillType());
        if (basicBussinessTypeEntity.getCorpType().equals(Constants.CORP_HOSPTIAL)) {
            //医院客户
            zaxzyyOrderRequest.setCorpId(orderEntity.getFromCorp());
            //查询客户名称
            String corpName = basicCorpDao.selectNameByErpId(orderEntity.getFromCorp());
            zaxzyyOrderRequest.setCorpName(corpName);
        } else if (basicBussinessTypeEntity.getCorpType().equals(Constants.CORP_INTTERNAL)) {
            //内部科室
            BasicCorpEntity basicCorpEntity = null;
            if (StrUtil.isNotEmpty(orderEntity.getFromCorp())) {
                basicCorpEntity = basicCorpDao.selectByErpId(orderEntity.getFromCorp());
            }
            if (basicCorpEntity != null) {
                zaxzyyOrderRequest.setCorpId(basicCorpEntity.getThirdId());
                zaxzyyOrderRequest.setCorpName(basicCorpEntity.getName());
            } else {
                AuthWarehouseEntity warehouseEntity = authWarehouseDao.selectOne(new QueryWrapper<AuthWarehouseEntity>().eq("code", udiwmsOrderRequest.getCorpId()));
                try {
                    //根据第三方系统标识，获取对应字段的值
                    ThrInvWarehouseEntity thrInvWarehouseEntity = thrInvWarehouseDao.selectOne(new LambdaQueryWrapper<ThrInvWarehouseEntity>()
                            .eq(ThrInvWarehouseEntity::getCode, authWarehouseService.getThirdInvCode(warehouseEntity))
                            .eq(ThrInvWarehouseEntity::getThirdSysFk, thirdSysConfig.getThirdId()));

                    zaxzyyOrderRequest.setCorpId(thrInvWarehouseEntity.getCode());
                    zaxzyyOrderRequest.setCorpName(thrInvWarehouseEntity.getName());
                } catch (Exception e) {
                    log.error("查询单据对应往来单位的第三方仓库信息异常", e);
                }
            }

        } else if (basicBussinessTypeEntity.getCorpType().equals(Constants.CORP_SP)) {
            //供应商
            BasicCorpEntity basicCorpEntity = null;
            if (StrUtil.isNotEmpty(orderEntity.getFromCorp())) {
                basicCorpEntity = basicCorpDao.selectByErpId(orderEntity.getFromCorp());
            }
            if (basicCorpEntity != null) {
                zaxzyyOrderRequest.setCorpId(basicCorpEntity.getThirdId());
                zaxzyyOrderRequest.setCorpName(basicCorpEntity.getName());
            } else {
                log.error("查询单据对应的第三方往来单位信息异常");
            }
        }


        //查询仓库信息
        AuthWarehouseEntity warehouseEntity = authWarehouseDao.selectOne(new QueryWrapper<AuthWarehouseEntity>().eq("code", orderEntity.getInvCode()));
        try {
            ThrInvWarehouseEntity thrInvWarehouseEntity = thrInvWarehouseDao.selectOne(new LambdaQueryWrapper<ThrInvWarehouseEntity>()
                    .eq(ThrInvWarehouseEntity::getCode, authWarehouseService.getThirdInvCode(warehouseEntity))
                    .eq(ThrInvWarehouseEntity::getThirdSysFk, thirdSysConfig.getThirdId()));

            if (thrInvWarehouseEntity != null) {
                zaxzyyOrderRequest.setLocInvCode(thrInvWarehouseEntity.getCode());
                zaxzyyOrderRequest.setLocInvName(thrInvWarehouseEntity.getName());

                zaxzyyOrderRequest.setLocStorageCode(thrInvWarehouseEntity.getCode());
                zaxzyyOrderRequest.setLocStorageName(thrInvWarehouseEntity.getName());
            } else {
                orderUploadLogService.updateLocalErr(orderEntity, "查询第三方系统仓库信息异常");
                return ResultVOUtils.error(500, "查询第三方系统仓库信息异常");
            }

        } catch (Exception e) {
            log.error("查询第三方系统仓库信息异常", ExceptionUtil.stacktraceToString(e));
            orderUploadLogService.updateLocalErr(orderEntity, "查询第三方系统仓库信息异常" + ExceptionUtil.stacktraceToString(e));
            return ResultVOUtils.error(500, "查询第三方系统仓库信息异常");
        }

        //设置单据出入库类型
        if (basicBussinessTypeEntity.getMainAction().equals(ConstantType.TYPE_PUT)) {
            zaxzyyOrderRequest.setInoutType(1); //入库
        } else if (basicBussinessTypeEntity.getMainAction().equals(ConstantType.TYPE_OUT)) {
            zaxzyyOrderRequest.setInoutType(2); //出库
        }

        //设置备注信息
        zaxzyyOrderRequest.setRemark("udi管理系统提交单据");
        //组装单据明细数据
        List<IoCodeEntity> ioCodeEntities = codeDao.selectList(new QueryWrapper<IoCodeEntity>()
                .eq("orderId", orderEntity.getBillNo())
                .ne("action", "StockCheck")
        );
        List<UdiwmsOrderDetailRequest> items = new ArrayList<>();
        //查询业务单据详情
        List<IoOrderDetailBizEntity> detailBizEntities = orderDetailBizDao.selectList(new QueryWrapper<IoOrderDetailBizEntity>().eq("orderIdFk", orderEntity.getBillNo()));
        setOrderDetailList(ioCodeEntities, items, detailBizEntities);
        zaxzyyOrderRequest.setItem(items);
        if (CollUtil.isEmpty(items)) {
            log.error("\"产品信息对照异常，无法上传\"");
            orderUploadLogService.updateLocalErr(orderEntity, "产品信息对照异常，无法上传");
            return ResultVOUtils.error(500, "产品信息对照异常，无法上传");
        }

        for (UdiwmsOrderDetailRequest i : items) {
            String fphm = "";
            String fprq = null;
            List<IoOrderInvoiceEntity> invoiceList = IoOrderInvoiceEntity.builder().build()
                    .selectList(Wrappers.lambdaQuery(IoOrderInvoiceEntity.class).eq(IoOrderInvoiceEntity::getOrderIdFk, orderEntity.getBillNo())
                            .eq(IoOrderInvoiceEntity::getBindRlFk, i.getBindRlFk())
                            .eq(StrUtil.isNotEmpty(i.getBatchNo()), IoOrderInvoiceEntity::getBatchNo, i.getBatchNo()).
                                    groupBy(IoOrderInvoiceEntity::getInvoiceEncode));
            if (CollectionUtil.isNotEmpty(invoiceList)) {
                fphm = invoiceList.stream().map(IoOrderInvoiceEntity::getInvoiceEncode).collect(Collectors.joining(","));
                if (invoiceList.get(0).getInvoiceDate() != null)
                    fprq = DateUtil.formatDateTime(invoiceList.get(0).getInvoiceDate());
            }
            i.setFirstSalesInvNo(fphm);
            i.setSecSalesInvNo(fphm);
            i.setInvoiceDate(fprq);
            boolean isNeedFp = false;
            ThrOrderUploadBustypesEntity thrOrderUploadBustypesEntity = thrOrderUploadBustypesMapper.selectOne(new QueryWrapper<ThrOrderUploadBustypesEntity>().eq("action", basicBussinessTypeEntity.getAction()).last("limit 1"));
            if (thrOrderUploadBustypesEntity != null && IntUtil.value(thrOrderUploadBustypesEntity.getOrderStatus()) == 3) {
                isNeedFp = true;
            }
            if (basicBussinessTypeEntity.getMainAction().equals(ConstantType.TYPE_PUT) && StrUtil.isEmpty(fphm) && isNeedFp) {
                String errMsg = "提交失败，错误信息：" + i.getProductName() + "发票缺失,请补齐后重新提交";
                orderUploadLogService.updateLocalErr(orderEntity, errMsg);
                return ResultVOUtils.error(500, errMsg);
            }
        }


        //构造诏安接口参数
        ZaZyRequest zaZyRequest = new ZaZyRequest();
//
        //提交到第三方系统
        if (thrSystemBusApiEntity.getUrl().equals("saveMasterialInput")) {
            //采购入库单据
            zaZyRequest.setMsgHeader(getMsgHeader("saveMasterialInput"));
            zaZyRequest.setMsgBody(JSONUtil.toJsonStr(zaxzyyOrderRequest));
            return submitOrder(orderEntity, zaZyRequest);
        } else if (thrSystemBusApiEntity.getUrl().equals("saveMaterialHight")) {
//            1.先提交到物资；
//            zaZyRequest.setMsgHeader(getMsgHeader("saveMasterialInput"));
//            zaZyRequest.setMsgBody(JSONUtil.toJsonStr(zaxzyyOrderRequest));
//            submitOrder(orderEntity, zaZyRequest);
//          2.提交到预备货
            zaxzyyOrderRequest.setLocStorageCode("1001304");
            zaxzyyOrderRequest.setLocStorageName("骨科耗材及试剂仓库");
            zaZyRequest.setMsgHeader(getMsgHeader("saveMaterialHight"));
            UdiwmsPreInOrderRequest udiwmsPreInOrderRequest = submitPreInOrderToThirdSys(zaxzyyOrderRequest, orderEntity);
            zaZyRequest.setMsgBody(JSONUtil.toJsonStr(udiwmsPreInOrderRequest));
            return submitOrder(orderEntity, zaZyRequest);
        }
        return ResultVOUtils.error(500, "提交失败！");
    }

    public String getUserName(IoOrderEntity orderEntity) {
        AuthUserEntity authUserEntity = null;
        //创建人非供应商
        if (StrUtil.isNotEmpty(orderEntity.getReviewUser())) {
            authUserEntity = authUserDao.selectById(orderEntity.getReviewUser());
        } else if (StrUtil.isNotEmpty(orderEntity.getCreateUser()) && orderEntity.getCreateUser().length() != 14) {
            authUserEntity = authUserDao.selectById(orderEntity.getCreateUser());
        } else if (StrUtil.isNotEmpty(orderEntity.getUpdateUser()) && orderEntity.getUpdateUser().length() != 14) {
            authUserEntity = authUserDao.selectById(orderEntity.getUpdateUser());
        } else {
            List<AuthWarehouseUser> authWarehouseUsers = authWarehouseUserMapper.selectList(new QueryWrapper<AuthWarehouseUser>().eq("code", orderEntity.getInvCode()));
            if (CollUtil.isNotEmpty(authWarehouseUsers)) {
                return authWarehouseUsers.get(0).getUserName();
            }
        }
        if (authUserEntity != null)
            return authUserEntity.getUserName();
        return null;
    }

    /**
     * 处理提交单据，记录日志，解析结果逻辑
     *
     * @param orderEntity
     * @param zaZyRequest
     * @return
     */
    private BaseResponse submitOrder(IoOrderEntity orderEntity, ZaZyRequest zaZyRequest) {
        //记录日志
        IoOrderUploadLogEntity uploadLog = new IoOrderUploadLogEntity();
        uploadLog.setBillDate(orderEntity.getCreateTime());
        uploadLog.setBillType(orderEntity.getAction());
        uploadLog.setSubmitTime(new Date());
        uploadLog.setBillNo(orderEntity.getBillNo());
        uploadLog.setFromType(Constants.THIRD_ORDER_UPLOAD);
        String response = httpClient.postJson(thrSystemDetailService.getUrlExclude(Constants.URL_NAME_ORDER_SUBMIT_URL), zaZyRequest);
        response = parserResult(response);
        if (StrUtil.isNotBlank(response)) {
            try {
                BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
                if (baseResponse.getCode() == 20000) {
                    String thirdBillNo = String.valueOf(baseResponse.getData());
                    orderEntity.setThirdBillNo(thirdBillNo);
                    orderEntity.setExportStatus(1); //提交成功
                    uploadLog.setStatus(2);
                    uploadLog.setThrBillNo(thirdBillNo);
                    uploadLog.setResult("提交成功");
                    orderDao.updateById(orderEntity);
                    orderUploadLogDao.insert(uploadLog);
                    return ResultVOUtils.success("提交成功");
                }
                uploadLog.setStatus(3);
                uploadLog.setResult("提交失败，错误信息：" + baseResponse.getMessage());
                orderEntity.setExportStatus(2); //上传失败
                orderDao.updateById(orderEntity);
                orderUploadLogDao.insert(uploadLog);
                return baseResponse;
            } catch (Exception e) {
                log.error("解析提交到智业单据返回结果异常，结果信息：{}", response);
                log.error("异常信息：{}", e);
                uploadLog.setStatus(3);
                uploadLog.setResult("提交失败，错误信息：" + response);
                orderEntity.setExportStatus(2); //上传失败
                orderDao.updateById(orderEntity);
                orderUploadLogDao.insert(uploadLog);
                return ResultVOUtils.error(500, "提交失败");
            }
        } else {
            uploadLog.setStatus(3);
            uploadLog.setResult("提交失败，调用接口返回为空");
            orderEntity.setExportStatus(2); //上传失败
            orderDao.updateById(orderEntity);
            orderUploadLogDao.insert(uploadLog);
            return ResultVOUtils.error(500, "提交失败");
        }
    }


    /**
     * 封装单据详情参数
     *
     * @param ioCodeEntities      单据码明细
     * @param orderDetailRequests 单据详情参数
     * @param detailBizEntities   单据业务详情
     */
    private void setOrderDetailList(List<IoCodeEntity> ioCodeEntities, List<UdiwmsOrderDetailRequest> orderDetailRequests, List<IoOrderDetailBizEntity> detailBizEntities) {
        for (IoOrderDetailBizEntity detailBizEntity : detailBizEntities) {

            IoOrderDetailCodeEntity orderDetailCodeEntity = orderDetailCodeDao
                    .selectOne(new QueryWrapper<IoOrderDetailCodeEntity>()
                            .eq("orderIdFk", detailBizEntity.getOrderIdFk())
                            .eq("bindRlFk", detailBizEntity.getBindRlFk())
                            .eq(StrUtil.isNotEmpty(detailBizEntity.getBatchNo()), "batchNo", detailBizEntity.getBatchNo())
                            .isNull(StrUtil.isEmpty(detailBizEntity.getBatchNo()), "batchNo").last("LIMIT 1"));
            if (orderDetailCodeEntity != null && IntUtil.value(orderDetailCodeEntity.getReCount()) > 0) {
                detailBizEntity.setCount(orderDetailCodeEntity.getReCount());
                UdiwmsOrderDetailRequest item = submitOrderUtil.buildProductInfo(detailBizEntity);
                if (item != null) {
                    //封装条码信息
                    submitOrderUtil.setCodeList(ioCodeEntities, detailBizEntity, item);
                    orderDetailRequests.add(item);
                }
            }
        }
    }

    @Override
    public BaseResponse getInvProducts(UdiwmsInvProductsRequest udiwmsInvProductsRequest) {
        ZaZyRequest zaZyRequest = new ZaZyRequest();
        zaZyRequest.setMsgHeader(getMsgHeader("getMaterialStorage"));
        zaZyRequest.setMsgBody(JSONUtil.toJsonStr(udiwmsInvProductsRequest));
        String response = httpClient.postJson(thrSystemDetailService.getUrlExclude(Constants.URL_NAME_INV_PI_URL), zaZyRequest);
        response = parserResult(response);
        try {
            BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
            return baseResponse;
        } catch (Exception e) {
            log.error("解析诏安智业接口返回库存产品数据异常，返回结果：{}", response);
            log.error("异常信息：{}", e);
            return ResultVOUtils.error(500, "网络错误，或远程服务器异常无法返回正确结果（" + response + ")");
        }
    }

    @Override
    public BaseResponse getWarehouse(UdiwmsWarehouseRequest udiwmsWarehouseRequest) {
        ZaZyRequest zaZyRequest = new ZaZyRequest();
        zaZyRequest.setMsgHeader(getMsgHeader("getMaterialDept"));
        zaZyRequest.setMsgBody(JSONUtil.toJsonStr(udiwmsWarehouseRequest));
        String response = httpClient.postJson(thrSystemDetailService.getUrlExclude(Constants.URL_NAME_WAREHOUSE_QUERY_URL), zaZyRequest);
        response = parserResult(response);
        try {
            BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
            return baseResponse;
        } catch (Exception e) {
            log.error("解析诏安智业接口返回仓库（科室）数据异常，返回结果：{}", response);
            log.error("异常信息：{}", e);
            return ResultVOUtils.error(500, "网络错误，或远程服务器异常无法返回正确结果（" + response + ")");
        }
    }

    @Override
    public BaseResponse postProducts(PostThrProductsRequest postThrProductsRequest) {
        postThrProductsRequest.setUploadType("文件导入");
        String response = httpClient.postUDIWMSJson(thirdSysConfig.getPostPiUrl(), postThrProductsRequest);
        BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
        return baseResponse;
    }

    @Override
    public BaseResponse postCorps(PostThrCorpRequest postThrCorpRequest) {
        postThrCorpRequest.setUploadType("文件导入");
        String response = httpClient.postUDIWMSJson(thirdSysConfig.getPostCorpUrl(), postThrCorpRequest);
        BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
        return baseResponse;
    }

    @Override
    public BaseResponse postOrderDetail(PostFileThrOrderRequest postFileThrOrderRequest) {
        postFileThrOrderRequest.setUploadType("文件导入");
        String response = httpClient.postUDIWMSJson(thirdSysConfig.getPostOrderUrl(), postFileThrOrderRequest);
        BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
        return baseResponse;
    }

    @Override
    public BaseResponse postInvProducts(PostThrInvProductsRequest postThrInvProductsRequest) {
        String response = httpClient.postUDIWMSJson(thirdSysConfig.getPostInvPiUrl(), postThrInvProductsRequest);
        BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
        return baseResponse;
    }

    @Override
    public BaseResponse postRelProduct(PostRelProductRequest postThrInvProductsRequest) {


        return null;
    }

    @Override
    public BaseResponse testConnect() {
        UdiwmsUnitRequest udiwmsUnitRequest = new UdiwmsUnitRequest();
        udiwmsUnitRequest.setPage(1);
        udiwmsUnitRequest.setLimit(1);
        BaseResponse baseResponse = getUnit(udiwmsUnitRequest);
        if (baseResponse.getCode() == 20000) {
            return ResultVOUtils.success("连接成功！");
        }
        return ResultVOUtils.error(500, "连接失败！");
    }

    @Override
    public BaseResponse queryUdiInvProducts(UdiwmsQueryUdiInvProductsRequest queryUdiInvProductsRequest) {
        String response = httpClient.postUDIWMSJson(thirdSysConfig.getQueryInvUrl(), queryUdiInvProductsRequest);
        BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
        return baseResponse;
    }

    @Override
    public BaseResponse submitProducts(UdiwmsAddProductsRequest udiwmsAddProductsRequest) {
        return null;
    }

    @Override
    public BaseResponse submitUnit(UdiwmsAddUnitRequest udiwmsAddUnitRequest) {
        return null;
    }

    @Override
    public BaseResponse submitPreInOrders(UdiwmsPreInOrderRequest udiwmsPreInOrderRequest) {
        ZaZyRequest zaZyRequest = new ZaZyRequest();
        zaZyRequest.setMsgHeader(getMsgHeader("saveMaterialHight"));
        zaZyRequest.setMsgBody(JSONUtil.toJsonStr(udiwmsPreInOrderRequest));
        String response = httpClient.postJson(thrSystemDetailService.getUrlExclude(Constants.URL_NAME_PRE_IN_ORDER_SUBMIT_URL), zaZyRequest);
        response = parserResult(response);
        try {
            BaseResponse baseResponse = JSONObject.parseObject(response, BaseResponse.class);
            return baseResponse;
        } catch (Exception e) {
            log.error("解析诏安智业接口提交单据返回数据异常，返回结果：{}", response);
            log.error("异常信息：{}", e);
            return ResultVOUtils.error(500, "网络错误，或远程服务器异常无法返回正确结果（" + response + ")");
        }
    }


    /**
     * 转换提交单据参数
     *
     * @param udiwmsOrderRequest
     * @param orderEntity
     * @return
     */
    public UdiwmsPreInOrderRequest submitPreInOrderToThirdSys(ZaxzyyOrderRequest udiwmsOrderRequest, IoOrderEntity orderEntity) {
        UdiwmsPreInOrderRequest udiwmsPreInOrderRequest = new UdiwmsPreInOrderRequest();
        if (udiwmsOrderRequest != null) {
            BeanUtils.copyProperties(udiwmsOrderRequest, udiwmsPreInOrderRequest);
            udiwmsPreInOrderRequest.setLocInvCode(udiwmsOrderRequest.getLocStorageCode());
            udiwmsPreInOrderRequest.setLocInvName(udiwmsOrderRequest.getLocStorageName());
            if (orderEntity.getReviewUser() != null) {
                AuthUserEntity authUser = authUserDao.selectById(orderEntity.getReviewUser());
                udiwmsPreInOrderRequest.setActor(authUser.getEmployeeName());
            } else if (orderEntity.getCreateUser() != null) {
                AuthUserEntity authUser = authUserDao.selectById(orderEntity.getCreateUser());
                udiwmsPreInOrderRequest.setActor(authUser.getEmployeeName());
            }
            List<UdiwmsPreInOrderRequest.ItemDTO> itemDTOS = new ArrayList<>();
            if (CollUtil.isNotEmpty(udiwmsOrderRequest.getItem())) {
                for (UdiwmsOrderDetailRequest udiwmsOrderDetail : udiwmsOrderRequest.getItem()) {
                    if (CollUtil.isNotEmpty(udiwmsOrderDetail.getCodeList())) {
                        for (UdiwmsOrderDetailRequest.CodeDetailEntity codeDetaiEntity : udiwmsOrderDetail.getCodeList()) {
                            UdiwmsPreInOrderRequest.ItemDTO itemDTO = new UdiwmsPreInOrderRequest.ItemDTO();
                            BeanUtils.copyProperties(udiwmsOrderDetail, itemDTO);
                            String code = codeDetaiEntity.getCode();
                            if (code.contains("\u001D")) {
//                                code = code.replace("\u001D", "zysoft");  智业无法识别GS1符号
                                code = code.replace("\u001D", "");
                            }
                            itemDTO.setCode(code);
                            itemDTO.setNameCode(code.substring(0, 16));
                            itemDTO.setCount(codeDetaiEntity.getCount());
                            itemDTOS.add(itemDTO);

                        }
                    }
                }
            }
            udiwmsPreInOrderRequest.setItems(itemDTOS);
        }
        return udiwmsPreInOrderRequest;
    }


}
