package com.zfire.mall.manager.bean.engin.order;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.engin.info.EnginInfoBean;
import com.zfire.mall.manager.bean.engin.sys.EnginSysAgencyBills;
import com.zfire.mall.manager.bean.valid.HomeOrderGroup;
import com.zfire.mall.manager.bean.valid.TradeOrderGroup;
import com.zfire.mall.manager.enums.IsEnum;
import com.zfire.mall.manager.enums.OrderTypeEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.EnginInfoOrderItemService;
import com.zfire.mall.manager.plus.service.KingDeeMaterialService;
import com.zfire.mall.manager.utils.ApplicationContextUtils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
@ApiModel
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(value = { "createBy","createTime","updateBy","updateTime","submitBy"
        ,"submitTime","confirmBy","confirmTime","closeBy","closeTime", "btnStatus" }
        , allowGetters = true)
public class EnginOrderBean {

    private static final long serialVersionUID=1L;

    //    @NotEmpty(message = "请先保存订单", groups = { EditGroup.class })
    @ApiModelProperty(value = "id")
    private String enginOrderId;

    @ApiModelProperty(value = "企业id")
    private String adminCompanyId;

    @ApiModelProperty(value = "用户id")
    private String adminUserId;

    @ApiModelProperty(value = "部门id")
    private String adminWebsitId;

    @ApiModelProperty(value = "客户id")
    private String customerId;

    @ApiModelProperty(value = "客户编码")
    private String customerNumber;

    @ApiModelProperty(value = "客户名称")
    private String customerName;

    @ApiModelProperty(value = "工程类型 TRADE=商用 HOME=零售")
    private String enginOrderType;

    @ApiModelProperty(value = "工程订单编号")
    private String enginOrderNo;

    @ApiModelProperty(value = "订单日期")
//    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date orderDate;

//    @NotBlank(message = "家用工程订单品类id不能空", groups = { HomeOrderGroup.class, TradeOrderGroup.class })
//    @ApiModelProperty(value = "品类id")
//    private String mainId;
//
//    @NotBlank(message = "家用工程订单品类名称不能空", groups = { HomeOrderGroup.class, TradeOrderGroup.class })
//    @ApiModelProperty(value = "品类名称")
//    private String mainName;

    @NotBlank(message = "家用工程订单登录单账号不能空", groups = { HomeOrderGroup.class })
    @ApiModelProperty(value = "登录单账号")
    private String loginUserId;

    @NotBlank(message = "工程登录单号不能空", groups = { HomeOrderGroup.class, TradeOrderGroup.class })
    @ApiModelProperty(value = "工程登录单号")
    private String refEnginRecordNo;

    @ApiModelProperty(value = "项目类别")
    private String refProjectCategory;

    @ApiModelProperty(value = "项目名称")
    private String refProjectName;

    @ApiModelProperty(value = "项目类型")
    private String refProjectType;

    @ApiModelProperty(value = "项目说明")
    private String refProjectNote;

    @ApiModelProperty(value = "使用单位")
    private String refUseUnit;

    @ApiModelProperty(value = "购买单位名称")
    private String refBuyUnitName;

    @ApiModelProperty(value = "购买单位联系人")
    private String refBuyUnitCallMen;

    @ApiModelProperty(value = "购买单位固定电话")
    private String refBuyUnitTel;

    @ApiModelProperty(value = "购买单位手机")
    private String refBuyUnitPhone;

    @ApiModelProperty(value = "安装地址")
    private String refInstallAddress;

    @ApiModelProperty(value = "项目编号|工程编号")
    private String refProjectNo;

    @ApiModelProperty(value = "厂编号")
    private String refFactoryNo;

    @ApiModelProperty(value = "工程登录类型")
    private String refPromiseStatus;

    @ApiModelProperty(value = "行业类别")
    private String refTradeCategory;

    @ApiModelProperty(value = "联系人")
    private String refLinkman;

    @ApiModelProperty(value = "联系电话")
    private String refPhone;

    @ApiModelProperty(value = "固定电话")
    private String refTel;

    @ApiModelProperty(value = "第几申报")
    private String refDeclareNo;

    @ApiModelProperty(value = "权限分类")
    private String refPowerCategory;

    @ApiModelProperty(value = "机型类别")
    private String refMachineType;

    @ApiModelProperty(value = "区域")
    private String refRegionWork;

    @ApiModelProperty(value = "提交保证函（已保证，未保证）")
    private String refPromiseProvide;

    @ApiModelProperty(value = "合同变更批复结果")
    private String refContractResult;

    @ApiModelProperty(value = "合同变更审批意见")
    private String refContractIdea;

    @ApiModelProperty(value = "工程机转零售批复结果")
    private String refToRetailResult;

    @ApiModelProperty(value = "工程机转零售审批意见")
    private String refToRetailIdea;

    @ApiModelProperty(value = "资料延期批复结果")
    private String refDataDelayResult;

    @ApiModelProperty(value = "资料延期审批意见")
    private String refDataDelayIdea;

    @ApiModelProperty(value = "其他附件批复结果")
    private String refOtherAnnexResult;

    @ApiModelProperty(value = "其他附件审批意见")
    private String refOtherAnnexIdea;

    @ApiModelProperty(value = "登录有效期")
    private Date refBillsExpireDate;

    @NotBlank(message = "家用工程订单销售类型不能空", groups = { HomeOrderGroup.class })
    @ApiModelProperty(value = "销售类型")
    private String saleTypeId;

    @NotBlank(message = "家用工程订单销售类型编码不能空", groups = { HomeOrderGroup.class })
    @ApiModelProperty(value = "销售类型编码")
    private String saleTypeCode;

    @NotBlank(message = "家用工程订单销售类型名称不能空", groups = { HomeOrderGroup.class })
    @ApiModelProperty(value = "销售类型名称")
    private String saleTypeName;

    @ApiModelProperty(value = "业务员")
    private String serviceId;

    @ApiModelProperty(value = "业务员名称")
    private String serviceName;

    @ApiModelProperty(value = "文件编号")
    private String fileNo;

    @ApiModelProperty(value = "是否计划单 true=是 false=否")
    private Boolean isPlanOrder;

    @ApiModelProperty(value = "格力回复")
    private String geLiNote;

    @ApiModelProperty(value = "格力内部备注")
    private String geLiInerNote;

    @ApiModelProperty(value = "扣押金 false=扣 true=不扣")
    private Boolean takeDeposit;

    @ApiModelProperty(value = "备注")
    private String remark;

    @ApiModelProperty(value = "审核说明")
    private String examineNote;

    @ApiModelProperty(value = "单据状态 SAVE=保存 WAIT=待审核 OK=通过 FAIL=不通过 CLOSE=关闭")
    private String examineStatus;

    @ApiModelProperty(value = "发货日期")
    private Date deliverDate;

    @ApiModelProperty(value = "发货仓库")
    private String correspondId;

    @ApiModelProperty(value = "发货仓库名称")
    private String correspondName;

    @ApiModelProperty(value = "仓位")
    private String stockId;

    @ApiModelProperty(value = "创建人")
    private String createBy;

    @ApiModelProperty(value = "创建人名称")
    private String createName;

    @ApiModelProperty(value = "创建时间")
    private Date createTime;

    @ApiModelProperty(value = "更新人")
    private String updateBy;

    @ApiModelProperty(value = "更新人名称")
    private String updateName;

    @ApiModelProperty(value = "更新时间")
    private Date updateTime;

    @ApiModelProperty(value = "提交人")
    private String submitBy;

    @ApiModelProperty(value = "提交人名称")
    private String submitName;

    @ApiModelProperty(value = "提交时间")
    private Date submitTime;

    @ApiModelProperty(value = "审核人")
    private String confirmBy;

    @ApiModelProperty(value = "审核人名称")
    private String confirmName;

    @ApiModelProperty(value = "审核时间")
    private Date confirmTime;

    @ApiModelProperty(value = "弃审人")
    private String abandonBy;

    @ApiModelProperty(value = "弃审人名称")
    private String abandonName;

    @ApiModelProperty(value = "弃审时间")
    private Date abandonTime;

    @ApiModelProperty(value = "关闭人")
    private String closeBy;

    @ApiModelProperty(value = "关闭人名称")
    private String closeName;

    @ApiModelProperty(value = "关闭时间")
    private Date closeTime;

    @ApiModelProperty(value = "直调完结人")
    private String endDirectBy;

    @ApiModelProperty(value = "直调完结人名称")
    private String endDirectName;

    @ApiModelProperty(value = "直调完结时间")
    private Date endDirectTime;

    @ApiModelProperty(value = "金蝶同步状态 NOT=未同步 SALES=销售订单 OUTSTOCK=销售出库单 TRANSFER=直接调拨单 ")
    private String kingDeeSync;

    @ApiModelProperty(value = "金蝶单据id")
    private String kingDeeId;

    @Valid
    @NotEmpty(message = "订单明细不能为空")
    @ApiModelProperty(value = "订单明细")
    List<EnginOrderItemBean> items;

    @ApiModelProperty(value = "审批结果 0=驳回 1=通过")
    private boolean examineResult = false;

    @ApiModelProperty(value = "退订说明")
    private String refundNote;

    @ApiModelProperty(value = "直调状态 false=未完结 true=已完结")
    private Boolean directTransferStatus;

    @ApiModelProperty(value = "订单退订记录")
    List<EnginOrderRefundNote> refundNoteList;

    @JsonIgnore
    private EnginSysAgencyBills enginSysAgencyBills;
    @JsonIgnore
    private EnginInfoBean enginInfoBean;
    @JsonIgnore
    private String enginUserName;
    private Integer refCount;


    public EnginOrder handleAddHomeOrderInfo(AdminUserCom adminUser, Integer refCount, EnginOrder enginOrder) {
        if (Objects.isNull(enginOrder)) {
            if (StringUtils.isBlank(loginUserId)) {
                throw new RemoteServiceException("工程登录单用户不能为空");
            }
            this.setEnginOrderId(IdWorker.getIdStr());
            enginOrder = new EnginOrder();
            BeanUtils.copyProperties(this, enginOrder);
            enginOrder.setIsFirstOldOrder(IsEnum.NO.getKey())
                    .setTakeDeposit(false)
                    .setEnginUserName(this.loginUserId)
                    .setRefCount(refCount);
        } else {
            enginOrder.setRefProjectNo(this.refProjectNo)
                    .setRefBuyUnitName(this.refBuyUnitName)
                    .setRefBuyUnitCallMen(this.refBuyUnitCallMen)
                    .setRefBuyUnitPhone(this.refBuyUnitPhone)
                    .setRefBuyUnitTel(this.refBuyUnitTel)
                    .setRefLinkman(this.refLinkman)
                    .setRefPhone(this.refPhone)
                    .setRefTel(this.refTel)
                    .setRemark(this.remark)
                    .setSaleTypeId(this.saleTypeId)
                    .setSaleTypeCode(this.saleTypeCode)
                    .setSaleTypeName(this.saleTypeName)
                    .setUpdateBy(this.updateBy)
                    .setUpdateName(this.updateName);
            if (!adminUser.getIsCustomer()) {
                enginOrder.setOrderDate(this.orderDate)
                        .setServiceId(this.serviceId)
                        .setServiceName(this.serviceName)
                        .setRefProjectCategory(this.refProjectCategory)
                        .setRefProjectName(this.refProjectName)
                        .setRefProjectType(this.refProjectType)
                        .setRefProjectNote(this.refProjectNote)
                        .setRefUseUnit(this.refUseUnit)
                        .setRefInstallAddress(this.refInstallAddress)
                        .setRefProjectNo(this.refProjectNo)
                        .setRefFactoryNo(this.refFactoryNo)
                        .setRefPromiseStatus(this.refPromiseStatus)
                        .setRefTradeCategory(this.refTradeCategory)
                        .setRefDeclareNo(this.refDeclareNo)
                        .setRefPowerCategory(this.refPowerCategory)
                        .setRefMachineType(this.refMachineType)
                        .setRefRegionWork(this.refRegionWork)
                        .setRefBuyUnitName(this.refBuyUnitName)
                        .setRefPromiseProvide(this.refPromiseProvide)
                        .setRefOtherAnnexIdea(this.refOtherAnnexIdea)
                        .setRefOtherAnnexResult(this.refOtherAnnexResult)
                        .setRefContractIdea(this.refContractIdea)
                        .setRefContractResult(this.refContractResult)
                        .setRefDataDelayIdea(this.refDataDelayIdea)
                        .setRefDataDelayResult(this.refDataDelayResult)
                        .setRefToRetailIdea(this.refToRetailIdea)
                        .setRefToRetailResult(this.refToRetailResult)
                        .setTakeDeposit(this.takeDeposit)
                        .setFileNo(this.fileNo)
                        .setGeLiNote(this.geLiNote)
                        .setCorrespondName(this.getCorrespondName())
                        .setCorrespondId(this.getCorrespondId())
                        .setGeLiInerNote(this.geLiInerNote);
            }
        }
        return enginOrder;
    }

    public List<EnginOrderItem> handleAddHomeOrderItem(EnginOrder enginOrder) {
        List<EnginOrderItemBean> orderItemBeans = this.getItems();
        if (CollectionUtil.isEmpty(orderItemBeans)) {
            throw new RemoteServiceException("工程订单明细为空");
        }

        KingDeeMaterialService kingDeeMaterialService = ApplicationContextUtils.getBean(KingDeeMaterialService.class);

        List<KingDeeMaterial> kingDeeMaterials = kingDeeMaterialService.lambdaQuery()
                .in(KingDeeMaterial::getOldNumber, orderItemBeans.stream().map(EnginOrderItemBean::getMaterialOldNumber).collect(Collectors.toList()))
                .list();
        // 实装物料
        List<KingDeeMaterial> realKingDeeMaterials = kingDeeMaterialService.lambdaQuery()
                .in(KingDeeMaterial::getOldNumber, orderItemBeans.stream().map(EnginOrderItemBean::getRealMaterialOldNumber).collect(Collectors.toList()))
                .list();
        Map<String, KingDeeMaterial> kingDeeMaterialMap = kingDeeMaterials.stream()
                .collect(Collectors.toMap(KingDeeMaterial::getId, Function.identity(), (key1, key2) -> key2));

        Map<String, KingDeeMaterial> realKingDeeMaterialMap = realKingDeeMaterials.stream()
                .collect(Collectors.toMap(KingDeeMaterial::getId, Function.identity(), (key1, key2) -> key2));

        List<EnginOrderItem> orderItems = new ArrayList<>();

        for (EnginOrderItemBean itemBean : orderItemBeans) {
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialMap.get(itemBean.getMaterialId());
            if (Objects.isNull(kingDeeMaterial)) {
                throw new RemoteServiceException(itemBean.getSaleTypeName() + "销售类型的\"" + itemBean.getMaterialName() + "\"：找不到物料信息");
            }
            KingDeeMaterial realKingDeeMaterial = realKingDeeMaterialMap.get(itemBean.getRealMaterialId());
            if (Objects.isNull(realKingDeeMaterial)) {
                throw new RemoteServiceException(itemBean.getSaleTypeName() + "销售类型的实装产品\"" + itemBean.getMaterialName() + "\"：找不到物料信息");
            }
            EnginOrderItem enginOrderItem = new EnginOrderItem();
            enginOrderItem.setAdminUserId(enginOrder.getAdminUserId())
                    .setAdminWebsitId(enginOrder.getAdminWebsitId())
                    .setParentId(enginOrder.getEnginOrderId())
                    .setEnginOrderNo(enginOrder.getEnginOrderNo())
                    .setUseRefCount(enginOrder.getRefCount())
                    .setSaleTypeId(enginOrder.getSaleTypeId())
                    .setSaleTypeCode(enginOrder.getSaleTypeCode())
                    .setSaleTypeName(enginOrder.getSaleTypeName())
                    .setMaterialId(kingDeeMaterial.getId())
                    .setMaterialName(kingDeeMaterial.getName())
                    .setMaterialNumber(kingDeeMaterial.getNumber())
                    .setMaterialOldNumber(kingDeeMaterial.getOldNumber())
                    .setSpecification(kingDeeMaterial.getSpecification())
                    .setK3CategoryId(kingDeeMaterial.getCategoryId())
                    .setK3CategoryName(kingDeeMaterial.getCategoryName())
                    .setK3CategoryNumber(kingDeeMaterial.getCategoryNumber())
                    .setUnit(kingDeeMaterial.getBaseUnitId())
                    .setEnginPrice(itemBean.getEnginPrice())
                    .setEnginTotality(itemBean.getEnginTotality())
                    .setEnginNum(itemBean.getEnginNum())
                    .setPrice(itemBean.getPrice())
                    .setQty(itemBean.getQty())
                    .setTotalAmount(BigDecimal.valueOf(itemBean.getQty())
                            .multiply(itemBean.getPrice())
                            .setScale(6, BigDecimal.ROUND_HALF_UP))
                    .setDiscAmount(Optional.ofNullable(itemBean.getDiscAmount()).orElse(new BigDecimal("0")))
                    .setIsDirectTransfer(itemBean.getIsDirectTransfer())
                    .setCustomerWalletId(itemBean.getCustomerWalletId())
                    .setCustomerWalletId2(itemBean.getCustomerWalletId2())
                    .setRemark(itemBean.getRemark())
                    .setTax(kingDeeMaterial.getTaxRateId())
                    .setRefEnginRecordNo(enginOrder.getRefEnginRecordNo())
                    .setRealMaterialId(realKingDeeMaterial.getId())
                    .setRealMaterialName(realKingDeeMaterial.getName())
                    .setRealMaterialNumber(realKingDeeMaterial.getNumber())
                    .setRealMaterialOldNumber(realKingDeeMaterial.getOldNumber())
                    .setRealSpecification(realKingDeeMaterial.getSpecification());


            orderItems.add(enginOrderItem);
        }

        return orderItems;
    }

    public EnginOrder handleAddTradeOrderInfo(Integer refCount, EnginOrder enginOrder) {
        if (Objects.isNull(enginOrder)) {
            enginOrder = new EnginOrder();
            BeanUtils.copyProperties(this, enginOrder);
            enginOrder.setEnginOrderType(OrderTypeEnum.TRADE.getKey())
                    .setTakeDeposit(true)
                    .setRefCount(refCount);
        } else {
            enginOrder.setOrderDate(this.orderDate)
                    .setServiceId(this.serviceId)
                    .setServiceName(this.serviceName)
                    .setRefProjectCategory(this.refProjectCategory)
                    .setRefProjectName(this.refProjectName)
                    .setRefProjectType(this.refProjectType)
                    .setRefProjectNote(this.refProjectNote)
                    .setRefUseUnit(this.refUseUnit)
                    .setRefInstallAddress(this.refInstallAddress)
                    .setRefProjectNo(this.refProjectNo)
                    .setRefFactoryNo(this.refFactoryNo)
                    .setRefPromiseStatus(this.refPromiseStatus)
                    .setRefTradeCategory(this.refTradeCategory)
                    .setRefLinkman(this.refLinkman)
                    .setRefPhone(this.refPhone)
                    .setRefTel(this.refTel)
                    .setRefDeclareNo(this.refDeclareNo)
                    .setRefPowerCategory(this.refPowerCategory)
                    .setRefMachineType(this.refMachineType)
                    .setRefRegionWork(this.refRegionWork)
                    .setFileNo(this.fileNo)
                    .setRemark(this.remark)
                    .setGeLiNote(this.getGeLiNote())
                    .setGeLiInerNote(this.getGeLiInerNote())
                    .setUpdateBy(this.updateBy)
                    .setUpdateName(this.updateName);
        }

        return enginOrder;
    }

    public List<EnginOrderItem> handleAddTradeOrderItem(EnginOrder enginOrder) {
        if (CollectionUtil.isEmpty(this.getItems())) {
            throw new RemoteServiceException("工程订单明细为空");
        }
        // 覆盖可能存在的同一销售类型物料不同价格以后压前处理
        Map<String, EnginOrderItemBean> beanMap = this.getItems().stream()
                .collect(Collectors.toMap(v -> v.getSaleTypeId() + v.getMaterialId(), Function.identity(), (key1, key2) -> key2));
        List<EnginOrderItemBean> orderItemBeans = new ArrayList<>(beanMap.values());

        KingDeeMaterialService kingDeeMaterialService = ApplicationContextUtils.getBean(KingDeeMaterialService.class);
        EnginInfoOrderItemService enginInfoOrderItemService = ApplicationContextUtils.getBean(EnginInfoOrderItemService.class);

        List<EnginInfoOrderItem> infoOrderItemList = enginInfoOrderItemService.lambdaQuery()
                .eq(EnginInfoOrderItem::getEnginInfoNo, enginOrder.getRefEnginRecordNo())
                .list();

        Map<String, EnginInfoOrderItem> infoOrderItemMap = infoOrderItemList.stream()
                .collect(Collectors.toMap(v -> v.getSaleTypeId() + v.getMaterialId(), Function.identity()));

        // 查询物料信息
        List<KingDeeMaterial> kingDeeMaterials = kingDeeMaterialService.lambdaQuery()
                .in(KingDeeMaterial::getId, orderItemBeans.stream()
                        .map(EnginOrderItemBean::getMaterialId)
                        .distinct()
                        .collect(Collectors.toList()))
                .list();
        Map<String, KingDeeMaterial> kingDeeMaterialMap = kingDeeMaterials.stream()
                .collect(Collectors.toMap(KingDeeMaterial::getId, Function.identity()));

        List<EnginOrderItem> orderItems = new ArrayList<>();
        for (EnginOrderItemBean itemBean : orderItemBeans) {
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialMap.get(itemBean.getMaterialId());
            EnginInfoOrderItem infoOrderItem = infoOrderItemMap.get(itemBean.getSaleTypeId() + itemBean.getMaterialId());
            if (Objects.isNull(kingDeeMaterial)) {
                throw new RemoteServiceException(itemBean.getSaleTypeName() + "销售类型的" + itemBean.getMaterialName() + "：找不到物料信息");
            }
            if (Objects.isNull(infoOrderItem)) {
                throw new RemoteServiceException(itemBean.getSaleTypeName() + "销售类型的" + itemBean.getMaterialName() + "：信息单找不到物料信息");
            }
//            if (Objects.nonNull(infoOrderItem)) {
                // 剩余可订数量
                int surplusQty = infoOrderItem.getQty() - infoOrderItem.getHasOrderQty();
                if (itemBean.getQty() > surplusQty) {
                    throw new RemoteServiceException(itemBean.getSaleTypeName() + "销售类型的" + itemBean.getMaterialName() + "：数量不能大于信息单数量");
                }
                itemBean.setEnginPrice(infoOrderItem.getPrice())
                        .setEnginNum(infoOrderItem.getQty())
                        .setEnginTotality(infoOrderItem.getTotalAmount())
                        .setHistoryHasOrderQty(infoOrderItem.getHasOrderQty());
//            }

            EnginOrderItem enginOrderItem = new EnginOrderItem();
            enginOrderItem.setAdminUserId(enginOrder.getAdminUserId())
                    .setAdminWebsitId(enginOrder.getAdminWebsitId())
                    .setParentId(enginOrder.getEnginOrderId())
                    .setEnginOrderNo(enginOrder.getEnginOrderNo())
                    .setUseRefCount(enginOrder.getRefCount())
                    .setSaleTypeId(itemBean.getSaleTypeId())
                    .setSaleTypeCode(itemBean.getSaleTypeCode())
                    .setSaleTypeName(itemBean.getSaleTypeName())
                    .setMaterialId(kingDeeMaterial.getId())
                    .setMaterialName(kingDeeMaterial.getName())
                    .setMaterialNumber(kingDeeMaterial.getNumber())
                    .setMaterialOldNumber(kingDeeMaterial.getOldNumber())
                    .setSpecification(kingDeeMaterial.getSpecification())
                    .setK3CategoryId(kingDeeMaterial.getCategoryId())
                    .setK3CategoryName(kingDeeMaterial.getCategoryName())
                    .setK3CategoryNumber(kingDeeMaterial.getCategoryNumber())
                    .setUnit(kingDeeMaterial.getBaseUnitId())
                    .setEnginPrice(itemBean.getEnginPrice())
                    .setEnginTotality(itemBean.getEnginTotality())
                    .setEnginNum(itemBean.getEnginNum())
                    .setPrice(itemBean.getPrice())
                    .setQty(itemBean.getQty())
                    .setTotalAmount(BigDecimal.valueOf(enginOrderItem.getQty())
                            .multiply(enginOrderItem.getPrice())
                            .setScale(6, BigDecimal.ROUND_HALF_UP))
                    .setDiscAmount(Optional.ofNullable(itemBean.getDiscAmount()).orElse(new BigDecimal("0")))
                    .setIsDirectTransfer(itemBean.getIsDirectTransfer())
                    .setCustomerWalletId(itemBean.getCustomerWalletId())
                    .setCustomerWalletId2(itemBean.getCustomerWalletId2())
                    .setHistoryHasOrderQty(itemBean.getHistoryHasOrderQty())
                    .setRemark(itemBean.getRemark())
                    .setTax(kingDeeMaterial.getTaxRateId())
                    .setRefEnginRecordNo(enginOrder.getRefEnginRecordNo());
            orderItems.add(enginOrderItem);
        }

        return orderItems;
    }

}
