package com.gree.mall.manager.logic.material.manage;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.PayDetail;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.material.manage.WebsitPartsSalesBean;
import com.gree.mall.manager.bean.material.manage.WebsitPartsSalesItemBean;
import com.gree.mall.manager.bean.material.manage.WebsitPartsSalesVO;
import com.gree.mall.manager.bean.material.manage.WebsitPartsSalesWVO;
import com.gree.mall.manager.bean.material.stock.WebsitStockDTO;
import com.gree.mall.manager.bean.material.stock.WorkerStockDTO;
import com.gree.mall.manager.bean.material.worker.OldRefundManageRecordBean;
import com.gree.mall.manager.commonmapper.MaterialMapper;
import com.gree.mall.manager.constant.SybConstants;
import com.gree.mall.manager.enums.IsEnum;
import com.gree.mall.manager.enums.IsYesNoEnum;
import com.gree.mall.manager.enums.material.*;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.AllInPayLogic;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.material.stock.MaterialGoodsStockLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import io.jsonwebtoken.lang.Collections;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class WebsitPartsSalesOrderLogic {

    private final CommonLogic commonLogic;
    private final MaterialMapper materialMapper;
    private final WebsitPartsSalesService websitPartsSalesService;
    private final WebsitPartsSalesItemService websitPartsSalesItemService;
    private final AdminWebsitService adminWebsitService;
    private final WebsitGoodsService websitGoodsService;
    private final WebsitPartsRefundConfigService websitPartsRefundConfigService;
    private final WebsitStockService websitStockService;
    private final StorageService storageService;
    private final MaterialConfigService materialConfigService;
    private final WebsitSalesPayOrderService websitSalesPayOrderService;
    private final AdminWebsitPayConfigService adminWebsitPayConfigService;
    private final AllInPayLogic allInPayLogic;
    private final MaterialGoodsStockLogic materialGoodsStockLogic;

    public IPage<WebsitPartsSalesVO> list(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.materialParam(zfireParamBean, WebsitPartsSalesVO.class, adminUser);

        return materialMapper.websitPartsSalesPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    public IPage<WebsitPartsSalesWVO> websitList(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.materialParam(zfireParamBean, WebsitPartsSalesWVO.class, adminUser);

        return materialMapper.websitPartsSalesWPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    private Map<String, Object> validate(WebsitPartsSalesBean partsSalesOrderBean) {
        Map<String, Object> result = new HashMap<>();
        result.put("isSuccess" , Boolean.TRUE);

        if(StringUtils.isBlank(partsSalesOrderBean.getWebsitId())) {
            result.put("isSuccess", Boolean.FALSE);
            result.put("msg", "新增配件销售单失败，没有网点");
            return result;
        }

        if (StringUtils.isBlank(partsSalesOrderBean.getBuyPeople())) {
            result.put("isSuccess", Boolean.FALSE);
            result.put("msg", "请选择销售类型");
            return result;
        }

        if (BuyPeopleEnum.WORKER.getKey().equals(partsSalesOrderBean.getBuyPeople())) {
            if(StringUtils.isBlank(partsSalesOrderBean.getIdentity())) {
                result.put("isSuccess", Boolean.FALSE);
                result.put("msg", "新增配件销售单失败，服务人员身份证不能为空，请选择服务人员");
                return result;
            }
        }

        //获取申请类别
        if(StringUtils.isBlank(partsSalesOrderBean.getApplyCategory())) {
            result.put("isSuccess", Boolean.FALSE);
            result.put("msg", "新增配件销售单失败，请选择申请类别");
            return result;
        }

        // 获取对应网点
        AdminWebsit websit = adminWebsitService.getById(partsSalesOrderBean.getWebsitId());
        if (Objects.isNull(websit) || StringUtils.isBlank(websit.getPartsWebsitId())) {
            result.put("isSuccess", Boolean.FALSE);
            result.put("msg", "新增配件销售单失败，没有找到该网点" + partsSalesOrderBean.getWebsitId());
            return result;
        }
        partsSalesOrderBean.setWebsitName(websit.getName());
        partsSalesOrderBean.setPartsWebsitId(websit.getPartsWebsitId());
        if (StringUtils.isBlank(partsSalesOrderBean.getDeliveryUnit())) {
            partsSalesOrderBean.setDeliveryUnit(websit.getName());
        }

        if (StringUtils.isBlank(partsSalesOrderBean.getStorageId())) {
            final Storage storage = storageService.lambdaQuery()
                    .eq(Storage::getCompanyWechatId, partsSalesOrderBean.getCompanyWechatId())
                    .eq(Storage::getWebsitId, partsSalesOrderBean.getWebsitId())
                    .eq(Storage::getIsDefault, IsEnum.Y.getValue())
                    .one();
            partsSalesOrderBean.setStorageId(storage.getStorageId())
                    .setStorageName(storage.getStorageName());
        }

        if (Objects.isNull(partsSalesOrderBean.getApplyType())) {
            result.put("isSuccess", Boolean.FALSE);
            result.put("msg", "新增配件销售单失败，没有申请类型");
            return result;
        }
        if (Objects.isNull(partsSalesOrderBean.getDeliveryType())) {
            result.put("isSuccess", Boolean.FALSE);
            result.put("msg", "新增配件销售单失败，请先选择发货方式");
            return result;
        }
        if (Collections.isEmpty(partsSalesOrderBean.getItemList())) {
            result.put("isSuccess", Boolean.FALSE);
            result.put("msg", "新增配件销售单失败，没有配件明细信息");
            return result;
        }

        // 快递必填详细地址
        if (partsSalesOrderBean.getDeliveryType().equals(DeliveryTypeEnum.EXPRESS.getValue())
                && StringUtils.isBlank(partsSalesOrderBean.getAddr())) {
            result.put("isSuccess", Boolean.FALSE);
            result.put("msg", "新增配件销售单失败，请填写详细地址");
            return result;
        }
        //校验配件明细列表
        LinkedHashSet<String> partsNumbers = new LinkedHashSet<>();
        for(WebsitPartsSalesItem item : partsSalesOrderBean.getItemList()) {
            if(StringUtils.isEmpty(item.getPartsNumber())) {
                result.put("isSuccess", Boolean.FALSE);
                result.put("msg", "新增配件销售单失败，配件编码不能为空");
                return result;
            }
            if(Objects.isNull(item.getQty()) || Integer.parseInt(item.getQty().toString()) <= 0) {
                result.put("isSuccess", Boolean.FALSE);
                result.put("msg", "新增配件销售单失败，配件编码"+item.getPartsNumber() + "数量不能小于或等于0");
                return result;
            }
            item.setCompanyWechatId(partsSalesOrderBean.getCompanyWechatId())
                    .setWebsitId(partsSalesOrderBean.getWebsitId())
                    .setPartsWebsitId(partsSalesOrderBean.getPartsWebsitId());

            partsNumbers.add(item.getPartsNumber());
        }
        //根据配件编码查询对应的配件列表
        final List<WebsitGoods> partsList = websitGoodsService.lambdaQuery()
                .eq(WebsitGoods::getGoodsType, WebsitGoodsTypeEnum.P.getKey())
                .eq(WebsitGoods::getNormType, NormTypeEnum.M.getKey())
                .in(WebsitGoods::getGoodsCode, partsNumbers)
                .eq(WebsitGoods::getStatus, StateEnum.ON.getKey())
                .list();

        if(Collections.isEmpty(partsList)) {
            result.put("isSuccess", Boolean.FALSE);
            result.put("msg", "新增配件销售单失败，系统找不到该配件配件编码: " + String.join(",", partsNumbers));
            return result;
        }
        final Map<String, WebsitGoods> partsMap = partsList.stream().collect(Collectors.toMap(WebsitGoods::getGoodsCode, Function.identity()));
        //检验每个配件明细是否在数据库里查到
        LinkedHashSet<String> notExsistisPartsNumbers = new LinkedHashSet<>();
        for(String partsNumber : partsNumbers) {
            if( !partsMap.containsKey(partsNumber) || Objects.isNull(partsMap.get(partsNumber))) {
                notExsistisPartsNumbers.add(partsNumber);
            }
        }
        if(!Collections.isEmpty(notExsistisPartsNumbers)) {
            result.put("isSuccess", Boolean.FALSE);
            result.put("msg", "新增配件销售单失败，以下配件配件编码不存在: "+String.join(",", notExsistisPartsNumbers));
            return result;
        }
        List<WebsitPartsSalesItemBean> values = new ArrayList<>(partsSalesOrderBean.getItemList().stream()
                .collect(Collectors.toMap(WebsitPartsSalesItemBean::getPartsNumber, Function.identity(), (key1, key2) -> {
                    key1.setQty(key1.getQty().add(key2.getQty()));
                    return key1;
                })).values());
        partsSalesOrderBean.getItemList().clear();
        partsSalesOrderBean.setItemList(values);

        if(CollectionUtil.isNotEmpty(partsSalesOrderBean.getItemList())) {
            WebsitPartsRefundConfig partsConfig = websitPartsRefundConfigService.lambdaQuery()
                    .eq(WebsitPartsRefundConfig::getCompanyWechatId, partsSalesOrderBean.getCompanyWechatId())
                    .eq(WebsitPartsRefundConfig::getIsDefault, Boolean.TRUE)
                    .one();

            //检查是否有可用库存
            final List<WebsitStock> partsWebsitStockList = websitStockService.lambdaQuery()
                    .in(WebsitStock::getGoodsId, partsNumbers)
                    .eq(WebsitStock::getCompanyWechatId, partsSalesOrderBean.getCompanyWechatId())
                    .eq(WebsitStock::getWebsitId, partsSalesOrderBean.getWebsitId())
                    .list();

            for (WebsitPartsSalesItem item : partsSalesOrderBean.getItemList()) {
                if (!partsMap.containsKey(item.getPartsNumber()) || Objects.isNull(partsMap.get(item.getPartsNumber()))) {
                    continue;
                }
                if (StringUtils.isEmpty(item.getPartsWebsitId())) {
                    result.put("isSuccess", Boolean.FALSE);
                    result.put("msg", "配件网点编号不能为空");
                    break;
                }
                if (StringUtils.isEmpty(item.getPartsNumber())) {
                    result.put("isSuccess", Boolean.FALSE);
                    result.put("msg", "配件编号不能为空");
                    break;
                }
                // 非申请单检验配件网点库存是否大于0
                if (!partsSalesOrderBean.getIsApply()) {
                    if (!partsWebsitStockList.stream().filter(o ->
                            item.getPartsWebsitId().equals(o.getPartsWebsitId())
                                    && item.getPartsNumber().equals(o.getGoodsId())
                    ).findAny().isPresent()) {
                        result.put("isSuccess", Boolean.FALSE);
                        result.put("msg", String.join("配件编号:", item.getPartsNumber(), ",在网点编号:", partsSalesOrderBean.getWebsitId(), "没有库存"));
                        break;
                    }
                    List<WebsitStock> stockList = partsWebsitStockList.stream().filter(o ->
                            item.getPartsWebsitId().equals(o.getPartsWebsitId())
                                    && item.getPartsNumber().equals(o.getGoodsId())
                    ).collect(Collectors.toList());
                    if (item.getQty().compareTo(stockList.get(0).getQty()) > 0) {
                        result.put("isSuccess", Boolean.FALSE);
                        result.put("msg", String.join("配件编号:", item.getPartsNumber(), ", 不能大于网点库存"));
                        break;
                    }
                    WebsitGoods parts = partsMap.get(item.getPartsNumber());

                    item.setWebsitId(partsSalesOrderBean.getWebsitId());
                    item.setPartsId(parts.getGoodsId());
                    item.setMaterialGroupName(parts.getMaterialGroupName());
                    item.setGoodsStockUnit(parts.getGoodsStockUnit());
                    item.setPartsWebsitId(stockList.get(0).getPartsWebsitId());
                    item.setPartsNumber(stockList.get(0).getGoodsId());
                    item.setMarketPrice(parts.getMarketPrice());
                    item.setExamineQty(item.getQty());
                    item.setSecondPrice(parts.getSecondPrice());
                    computeSalesPrice(partsConfig, parts, item, result);
                } else {
                    WebsitGoods parts = partsMap.get(item.getPartsNumber());
                    item.setWebsitId(partsSalesOrderBean.getWebsitId());
                    item.setPartsId(parts.getGoodsId());
                    item.setMaterialGroupName(parts.getMaterialGroupName());
                    item.setGoodsStockUnit(parts.getGoodsStockUnit());
                    item.setPartsWebsitId(partsSalesOrderBean.getPartsWebsitId());
                    item.setPartsNumber(parts.getGoodsCode());
                    item.setMarketPrice(parts.getMarketPrice());
                    item.setExamineQty(item.getQty());
                    item.setSecondPrice(parts.getSecondPrice());
                    computeSalesPrice(partsConfig, parts, item, result);
                }
            }
        }
        return result;
    }

    private void computeSalesPrice(WebsitPartsRefundConfig partsConfig, WebsitGoods parts, WebsitPartsSalesItem item, Map<String, Object> result) {
        final MaterialConfig materialConfig = materialConfigService.lambdaQuery()
                .eq(MaterialConfig::getCompanyWechatId, partsConfig.getCompanyWechatId())
                .one();
        switch (Optional.ofNullable(parts.getPartType()).orElse("")) {
            case "":
                result.put("isSuccess", Boolean.FALSE);
                result.put("msg", "配件类型不能为空");
                break;
            case "空调":
                item.setSalesPrice(item.getMarketPrice().multiply(materialConfig.getPriceRate1()).setScale(2, BigDecimal.ROUND_HALF_UP));
                break;
            case "冰箱":
                item.setSalesPrice(item.getMarketPrice().multiply(materialConfig.getPriceRate2()).setScale(2, BigDecimal.ROUND_HALF_UP));
                break;
            case "生活电器":
                item.setSalesPrice(item.getMarketPrice().multiply(materialConfig.getPriceRate3()).setScale(2, BigDecimal.ROUND_HALF_UP));
                break;
            default:
                item.setSalesPrice(item.getMarketPrice().multiply(new BigDecimal("1.2")).setScale(2, BigDecimal.ROUND_HALF_UP));
                break;
        }
    }

    @Transactional
    public void add(WebsitPartsSalesBean partsSalesOrderBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }
        partsSalesOrderBean.setCompanyWechatId(adminUser.getCompanyWechatId())
                .setCompanyWechatName(adminUser.getCompanyName());
        //一系列校验
        Map<String, Object> validateMap = this.validate(partsSalesOrderBean);
        if(validateMap.containsKey("isSuccess") && !Boolean.parseBoolean(validateMap.get("isSuccess").toString())) {
            throw new RemoteServiceException(validateMap.get("msg").toString());
        }
        //获取登录人昵称
        DateTime curDate = DateUtil.date();

        if (Objects.isNull(partsSalesOrderBean.getPayType())) {
            // 默认通联
            partsSalesOrderBean.setPayType(PayTypeEnum.ALLINPAY.getKey());
        }
        List<WebsitPartsSalesItemBean> itemList = partsSalesOrderBean.getItemList();
        BigDecimal totalPrice = BigDecimal.ZERO;

        if (CollectionUtil.isEmpty(itemList)) {
            throw new RemoteServiceException("请选择配件");
        }

        for(WebsitPartsSalesItem partsSalesOrderItem : itemList) {
            partsSalesOrderItem.setTotalAmount(partsSalesOrderItem.getSalesPrice().multiply(partsSalesOrderItem.getQty())
                    .setScale(2, BigDecimal.ROUND_HALF_UP));
            totalPrice = totalPrice.add(partsSalesOrderItem.getTotalAmount());
        }

        // 记录总金额
        partsSalesOrderBean.setTotalAmount(totalPrice);
        partsSalesOrderBean.setStatus(PartsOrderStatusEnum.SAVE.getKey());
        partsSalesOrderBean.setDel(false);
        // 生成订单号
        String sheetId = commonLogic.generateMaterialNo(adminUser.getCompanyWechatId(), "PJ", PartsRefTypeEnum.SALES.getKey(), 13);
        partsSalesOrderBean.setId(sheetId);
        websitPartsSalesService.save(partsSalesOrderBean);

        // 保存销售单明细
        List<WebsitPartsSalesItem> partsSalesOrderItems = this.createSalesOrderItem(partsSalesOrderBean, itemList);
        websitPartsSalesItemService.saveBatch(partsSalesOrderItems);
    }

    private List<WebsitPartsSalesItem> createSalesOrderItem(WebsitPartsSalesBean partsSalesOrderBean, List<WebsitPartsSalesItemBean> itemList) {
        List<WebsitPartsSalesItem> partsSalesOrderItems = new ArrayList<>();
        for(WebsitPartsSalesItemBean partsSalesOrderItemBean : itemList) {
            WebsitPartsSalesItem partsSalesOrderItem = new WebsitPartsSalesItem();
            BeanUtils.copyProperties(partsSalesOrderItemBean, partsSalesOrderItem);
            partsSalesOrderItem.setSalesId(partsSalesOrderBean.getId())
                    .setWebsitId(partsSalesOrderBean.getWebsitId())
                    .setIdentity(partsSalesOrderBean.getIdentity());
            partsSalesOrderItems.add(partsSalesOrderItem);
        }
        return partsSalesOrderItems;
    }

    public WebsitPartsSalesBean loadSalesOrderById(String id) {
        WebsitPartsSales partsSalesOrder = websitPartsSalesService.getById(id);

        if(Objects.isNull(partsSalesOrder)) {
            throw new RemoteServiceException("获取配件销售单失败") ;
        }

        WebsitPartsSalesBean partsSalesOrderBean = new WebsitPartsSalesBean();
        BeanUtils.copyProperties(partsSalesOrder, partsSalesOrderBean, WebsitPartsSalesBean.class);
        List<WebsitPartsSalesItemBean> itemList = materialMapper.selectItemBySalesOrderId(partsSalesOrderBean.getId());
        partsSalesOrderBean.setItemList(Collections.isEmpty(itemList) ? null : itemList);
        List<WebsitSalesPayOrder> payList = websitSalesPayOrderService.lambdaQuery()
                .eq(WebsitSalesPayOrder::getCompanyWechatId, partsSalesOrder.getCompanyWechatId())
                .eq(WebsitSalesPayOrder::getPayFlag, IsYesNoEnum.YES.getKey())
                .eq(WebsitSalesPayOrder::getOrderId, partsSalesOrderBean.getId())
                .list();
        List<WebsitSalesPayOrder> allPayList = websitSalesPayOrderService.lambdaQuery()
                .eq(WebsitSalesPayOrder::getCompanyWechatId, partsSalesOrder.getCompanyWechatId())
                .eq(WebsitSalesPayOrder::getOrderId, partsSalesOrderBean.getId())
                .list();

        partsSalesOrderBean.setPayList(payList);
        partsSalesOrderBean.setAllPayList(allPayList);

        // 配件使用记录
        List<OldRefundManageRecordBean> oldRefundManageRecordBeans = materialMapper.queryOldRefundRecordById(partsSalesOrder.getId());
        partsSalesOrderBean.setOldRefundManageRecordBeanList(oldRefundManageRecordBeans);


        return partsSalesOrderBean;
    }

    @Transactional
    public void update(WebsitPartsSalesBean partsSalesOrderBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitPartsSales partsSalesOrder = websitPartsSalesService.getById(partsSalesOrderBean.getId());
        if(Objects.isNull(partsSalesOrder)) {
            throw new RemoteServiceException("该配件销售单不存在");
        }
        partsSalesOrderBean.setIsApply(partsSalesOrder.getIsApply());
        //订单已提交，不能修改
        if(!partsSalesOrder.getStatus().equals(PartsOrderStatusEnum.SAVE.getKey())) {
            throw new RemoteServiceException("该配件销售单已提交，不能修改");
        }
        //一系列校验
        Map<String, Object> validateMap = validate(partsSalesOrderBean);
        if(validateMap.containsKey("isSuccess") && !Boolean.parseBoolean(validateMap.get("isSuccess").toString())) {
            throw new RemoteServiceException(validateMap.get("msg").toString());
        }

        if (CollectionUtil.isEmpty(partsSalesOrderBean.getItemList())) {
            throw new RemoteServiceException("请选择配件");
        }

        if (Objects.isNull(partsSalesOrderBean.getPayType())) {
            // 默认通联
            partsSalesOrderBean.setPayType(PayTypeEnum.ALLINPAY.getKey());
        }

        List<WebsitPartsSalesItemBean> itemList = partsSalesOrderBean.getItemList();
        BigDecimal totalPrice = BigDecimal.ZERO;
        for(WebsitPartsSalesItem partsSalesOrderItem : itemList) {
            partsSalesOrderItem.setTotalAmount(partsSalesOrderItem.getSalesPrice().multiply(partsSalesOrderItem.getQty())
                    .setScale(2, BigDecimal.ROUND_HALF_UP));
            totalPrice = totalPrice.add(partsSalesOrderItem.getTotalAmount());
        }

        // 记录总金额
        partsSalesOrderBean.setTotalAmount(totalPrice);
        websitPartsSalesService.updateById(partsSalesOrderBean);
        // 删除销售单配件明细
        websitPartsSalesItemService.lambdaUpdate()
                .eq(WebsitPartsSalesItem::getSalesId, partsSalesOrderBean.getId())
                .remove();

        // 保存销售单明细
        List<WebsitPartsSalesItem> partsSalesOrderItems = this.createSalesOrderItem(partsSalesOrderBean, itemList);
        websitPartsSalesItemService.saveBatch(partsSalesOrderItems);
    }

    /**
     * 根据网点编码，配件网点编号，配件编码查询配件网点库存，前端下拉配件编码的时候带出可用库存
     * @param websitId
     * @param partsWebsitId
     * @param partsNumber
     * @return
     */
    public WebsitStock queryPartsNewQty(String websitId, String partsWebsitId, String partsNumber) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        final Storage storage = storageService.lambdaQuery()
                .eq(Storage::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(Storage::getWebsitId, websitId)
                .eq(Storage::getIsDefault, IsEnum.Y.getValue())
                .one();
        return websitStockService.lambdaQuery()
                .eq(WebsitStock::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(WebsitStock::getGoodsType, WebsitGoodsTypeEnum.P.getKey())
                .eq(WebsitStock::getGoodsId, partsNumber)
                .eq(WebsitStock::getWebsitId, websitId)
                .eq(WebsitStock::getStorageId, storage.getStorageId())
                .eq(WebsitStock::getPartsWebsitId, partsWebsitId)
                .one();
    }

    @Transactional
    public WebsitPartsSalesBean submit(String id) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitPartsSalesBean partsSalesOrderBean = loadSalesOrderById(id);
        if(Objects.isNull(partsSalesOrderBean)) {
            throw new RemoteServiceException("配件单提交失败，销售单信息不能为空") ;
        }
        if(!partsSalesOrderBean.getStatus().equals(PartsOrderStatusEnum.SAVE.getKey())) {
            throw new RemoteServiceException("该配件销售单已提交，不能重复提交");
        }
		// 先保存一下页面信息，再提交状态

        // 更新状态为1-已提交
        partsSalesOrderBean.setStatus(PartsOrderStatusEnum.SUBMIT.getKey());
        partsSalesOrderBean.setSubmitBy(adminUser.getNickName());
        partsSalesOrderBean.setSubmitTime(DateUtil.date());

        websitPartsSalesService.saveOrUpdate(partsSalesOrderBean);
        return loadSalesOrderById(id);
    }

    @Transactional
    public PayDetail generateCode(String salesId, String payConfigId) {
        WebsitPartsSales sales = websitPartsSalesService.getById(salesId);
        if (Objects.isNull(sales)) {
            throw new RemoteServiceException("销售单号不存在");
        }

        final AdminWebsitPayConfig payConfig = adminWebsitPayConfigService.getById(payConfigId);
        if (Objects.isNull(payConfig) || !payConfig.getStatus()) {
            throw new RemoteServiceException("支付配置信息异常");
        }

        // 通联扫码支付
        WebsitSalesPayOrder payOrder = new WebsitSalesPayOrder();
        payOrder.setId(IdWorker.getIdStr())
                .setCompanyWechatId(sales.getCompanyWechatId())
                .setCompanyWechatName(sales.getCompanyWechatName())
                .setGoodsType(WebsitGoodsTypeEnum.P.getKey())
                .setWebsitId(sales.getWebsitId())
                .setWebsitName(sales.getWebsitName())
                .setOrderId(sales.getId())
                .setOutTradeNo(payOrder.getId())
                .setPayType(PayTypeEnum.ALLINPAY.getKey())
                .setOrderCreateTime(sales.getCreateTime())
                .setPayValue(sales.getTotalAmount())
                .setOrgId(payConfig.getOrgId())
                .setMchNo(payConfig.getMchNo())
                .setAppid(payConfig.getAppid())
                .setOrderType(PayOrderTypeEnum.S.getKey())
                .setRunTime(DateUtil.offsetSecond(DateUtil.date(), 15))
                .setOrderSource(OrderSourceEnum.P_SALES.getKey())
                .setIsDeliver(false);


        // 请求通联得到结果
        Map<String, String> resMap = allInPayLogic.serviceUnifiedOrder(payOrder, SybConstants.PAY_TYPE_W01);

        if (!resMap.get("trxstatus").equals("0000")) {
            throw new RemoteServiceException("通联统一支付接口执行失败：" + resMap.get("errmsg"));
        }

        payOrder.setOrderNo(resMap.get("trxid"))
                .insert();

        PayDetail payDetail = new PayDetail();
        payDetail.setCodeUrl(resMap.get("payinfo"));
        payDetail.setId(payOrder.getId());
        payDetail.setPayAmount(sales.getTotalAmount());
        log.info("通联支付payDetail:{}", JSONObject.toJSONString(payDetail));
        return payDetail;
    }

    @Transactional
    public WebsitPartsSalesBean changeCash(String id) throws Exception {
        WebsitPartsSalesBean partsSalesOrderBean = this.loadSalesOrderById(id);
        AdminWebsit websit = adminWebsitService.getById(partsSalesOrderBean.getWebsitId());
        if (!websit.getPartsIsCash()) {
            throw new RemoteServiceException("当前配件网点不支付现金方式");
        }
        if (partsSalesOrderBean.getIsApply().equals(IsEnum.Y.getValue())) {
            throw new RemoteServiceException("申请单不能现金支付");
        }

        // 现金订单改为已支付未提货状态
        partsSalesOrderBean.setStatus(PartsOrderStatusEnum.PAYED.getKey());
        partsSalesOrderBean.setPayFlag(PartsPayFlagEnum.PAY_NOT_TAKE.getKey());
        partsSalesOrderBean.setPayType(PayTypeEnum.CASH.getKey());

        this.handleForwardWebsitAndWorkerStock(partsSalesOrderBean);


        websitPartsSalesService.saveOrUpdate(partsSalesOrderBean);
        return partsSalesOrderBean;
    }

    private void handleForwardWebsitAndWorkerStock(WebsitPartsSalesBean partsSalesOrderBean) throws Exception {
        // 扣减网点库存
        List<WebsitStockDTO> shopStockDTOList = this.getWebsitStock(partsSalesOrderBean, DirectFlagEnum.SUB, PartsRefTypeEnum.SALES.getRemark());
        materialGoodsStockLogic.handleWebsitStock(shopStockDTOList);

        if (DeliveryTypeEnum.EXPRESS.getValue().equals(partsSalesOrderBean.getDeliveryType())
                && BuyPeopleEnum.WORKER.getKey().equals(partsSalesOrderBean.getBuyPeople())) {
            // 如果是快递并且销售类型为“服务人员”的单，需要增加师傅在途库存
            // 增加师傅在途库存
            List<WorkerStockDTO> workerStockDTOList = this.getWorkerStock(partsSalesOrderBean,
                    PartsRefTypeEnum.SALES.getRemark(), null, PartsAttrEnum.WAY.getKey());

            materialGoodsStockLogic.handleWorkerStock(workerStockDTOList);
        }
    }

    private void handleReverseWebsitAndWorkerStock(WebsitPartsSalesBean partsSalesOrderBean) throws Exception {
        //网点库存要加回去
        List<WebsitStockDTO> shopStockDTOList = this.getWebsitStock(partsSalesOrderBean, DirectFlagEnum.ADD, PartsRefTypeEnum.SALES.getRemark());

        materialGoodsStockLogic.handleWebsitStock(shopStockDTOList);

        if (DeliveryTypeEnum.EXPRESS.getValue().equals(partsSalesOrderBean.getDeliveryType())
                && BuyPeopleEnum.WORKER.getKey().equals(partsSalesOrderBean.getBuyPeople())) {
            // 如果是快递并且销售类型为“服务人员”的单，需要减师傅在途库存
            // 减师傅在途库存
            List<WorkerStockDTO> workerStockDTOList = this.getWorkerStock(partsSalesOrderBean,
                    PartsRefTypeEnum.SALES.getRemark(), PartsAttrEnum.WAY.getKey(), null);
            materialGoodsStockLogic.handleWorkerStock(workerStockDTOList);
        }
    }

    @Transactional
    public void confirmDelivery(String id, String logisticsNo) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitPartsSalesBean partsSalesOrderBean = this.loadSalesOrderById(id);
        if(Objects.isNull(partsSalesOrderBean)) {
            throw new RemoteServiceException("配件单提交失败，单号=" + id) ;
        }

        if(!PartsOrderStatusEnum.PAYED.getKey().equals(partsSalesOrderBean.getStatus())) {
            throw new RemoteServiceException("非已支付状态，不能提货");
        }

        DateTime curDate = DateUtil.date();
        partsSalesOrderBean.setLogisticsNo(logisticsNo);
        partsSalesOrderBean.setWebsitConfirmBy(adminUser.getNickName());
        partsSalesOrderBean.setWebsitConfirmDate(curDate);

        if (this.checkOrderAttr(partsSalesOrderBean)) {
            partsSalesOrderBean.setStatus(PartsOrderStatusEnum.END.getKey());
            partsSalesOrderBean.setEndTime(curDate);
            partsSalesOrderBean.setExamineBy(adminUser.getNickName());
            partsSalesOrderBean.setExamineTime(curDate);
            partsSalesOrderBean.setPushFlag(PartsPushFlagEnum.SALES.getKey());
            partsSalesOrderBean.setPayFlag(PartsPayFlagEnum.PAY_TAKE.getKey());

            if (BuyPeopleEnum.WORKER.getKey().equals(partsSalesOrderBean.getBuyPeople())) {
                // 增加师傅库存
                List<WorkerStockDTO> workerStockDTOList = this.getWorkerStock(partsSalesOrderBean, PartsRefTypeEnum.SALES.getRemark(),
                        Objects.nonNull(partsSalesOrderBean.getWorkerConfirmDate()) ? PartsAttrEnum.WAY.toString() : null,
                        PartsAttrEnum.NEW.getKey());

                materialGoodsStockLogic.handleWorkerStock(workerStockDTOList);
            }
            // 更新销售单明细信息
            this.updateSalesItem(partsSalesOrderBean);
        }

        websitPartsSalesService.updateById(partsSalesOrderBean);
    }

    private boolean checkOrderAttr(WebsitPartsSalesBean partsSalesOrderBean) {
        return !DeliveryTypeEnum.EXPRESS.getValue().equals(partsSalesOrderBean.getDeliveryType())
                || !BuyPeopleEnum.WORKER.getKey().equals(partsSalesOrderBean.getBuyPeople())
                || Objects.nonNull(partsSalesOrderBean.getWorkerConfirmDate());
    }

    /**
     * 更新销售明细的信息
     * @param partsSalesOrderBean
     */
    private void updateSalesItem(WebsitPartsSalesBean partsSalesOrderBean) {
        if(CollectionUtil.isNotEmpty(partsSalesOrderBean.getItemList())) {
            List<WebsitPartsSalesItem> itemList = new ArrayList<>();
            for(WebsitPartsSalesItemBean itemBean : partsSalesOrderBean.getItemList()) {
                itemBean.setPushFlag(partsSalesOrderBean.getPushFlag());
                itemBean.setExamineTime(partsSalesOrderBean.getExamineTime());
                if (partsSalesOrderBean.getPayType().equals(PayTypeEnum.CASH.getKey())) {
                    itemBean.setRefundAmountMode(PayTypeEnum.CASH.getKey());
                } else {
                    itemBean.setRefundAmountMode(PayTypeEnum.WECHAT.getKey());
                }
                itemList.add(itemBean);
            }
            websitPartsSalesItemService.saveOrUpdateBatch(itemList);
        }
    }

    /**
     * 删除配件销售单(软删除)
     * @param id
     */
    @Transactional
    public void deleteById(String id) {
        WebsitPartsSales partsSalesOrder = websitPartsSalesService.getById(id);
        List<String> stateList = Arrays.asList(PartsOrderStatusEnum.SUBMIT.getKey(), PartsOrderStatusEnum.PAYED.getKey(),
                PartsOrderStatusEnum.END.getKey(), PartsOrderStatusEnum.EXCEPTION.getKey());
        if(Objects.isNull(partsSalesOrder)) {
            throw new RemoteServiceException("找不到该配件销售单, 请刷新一下列表");
        }
        //不是该网点不能删除
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (adminUser.getType() != 0) {
            throw new RemoteServiceException("不是网点用户，没有删除权限");
        }
        if(!adminUser.getAdminWebsitIds().contains(partsSalesOrder.getWebsitId())) {
            throw new RemoteServiceException("不是该网点用户，没有删除权限");
        }
        if(stateList.contains(partsSalesOrder.getStatus())) {
            throw new RemoteServiceException("该订单非保存或已取消状态，不能删除: 订单号: "+partsSalesOrder.getId());
        }
        websitPartsSalesService.removeById(partsSalesOrder);
    }

    /**
     * 退回0-保存状态
     * @param id
     * @throws InterruptedException
     */
    @Transactional
    public Object backToSave(String id) {
        WebsitPartsSalesBean partsSalesOrderBean = loadSalesOrderById(id);
        if (Objects.isNull(partsSalesOrderBean)) {
            throw new RemoteServiceException("配件销售单状态退回失败，没有该销售单号: " + id) ;
        }
        // 不是该网点不能退回
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }
        if (!adminUser.getAdminWebsitIds().contains(partsSalesOrderBean.getWebsitId())) {
            throw new RemoteServiceException("不是该网点用户，没有操作权限");
        }
        // 检查是否提交或之前的状态，若是提交后的状态不能再退回
        if (!partsSalesOrderBean.getStatus().equals(PartsOrderStatusEnum.SUBMIT.getKey())) {
            throw new RemoteServiceException("该配件销售单已支付，不能退回修改");
        }

        if (partsSalesOrderBean.getPayType().equals(PayTypeEnum.ALLINPAY.getKey())) {
            WebsitSalesPayOrder salesPayList = getPayList(partsSalesOrderBean);
            if (Objects.nonNull(salesPayList)) {
                throw new RemoteServiceException("已有支付记录，不能退回修改");
            }
        }

        //更新状态为0-保存状态
        partsSalesOrderBean.setStatus(PartsOrderStatusEnum.SAVE.getKey());
        if (partsSalesOrderBean.getPayType().equals(PayTypeEnum.CASH.getKey())) {
            // 现金订单提交直接改为未支付状态
            partsSalesOrderBean.setPayFlag(PartsPayFlagEnum.NOT.getKey());
        }

        //清空提交状态
        partsSalesOrderBean.setSubmitTime(null);
        partsSalesOrderBean.setSubmitBy(null);
        websitPartsSalesService.updateById(partsSalesOrderBean);
        log.info("backToSave: partsSalesOrderBean status: {}", partsSalesOrderBean.getStatus());
        return partsSalesOrderBean;
    }

    /**
     * 获取支付记录
     * @param partsSalesOrderBean
     * @return
     */
    @Transactional
    public WebsitSalesPayOrder getPayList(WebsitPartsSalesBean partsSalesOrderBean) {
        WebsitSalesPayOrder salesPayList;
        List<WebsitSalesPayOrder> payList = websitSalesPayOrderService.lambdaQuery()
                .eq(WebsitSalesPayOrder::getCompanyWechatId, partsSalesOrderBean.getCompanyWechatId())
                .eq(WebsitSalesPayOrder::getWebsitId, partsSalesOrderBean.getWebsitId())
                .eq(WebsitSalesPayOrder::getOrderId, partsSalesOrderBean.getId())
                .eq(WebsitSalesPayOrder::getPayType, PayTypeEnum.ALLINPAY.getKey())
                .in(WebsitSalesPayOrder::getOrderType, PayOrderTypeEnum.S.getKey())
                .orderByAsc(WebsitSalesPayOrder::getCreateTime)
                .list();
        for (WebsitSalesPayOrder payRecord : payList) {
            if (payRecord.getPayFlag().equals(IsYesNoEnum.YES.getKey())) {
                salesPayList = payRecord;
                return salesPayList;
            } else if (payRecord.getPayFlag().equals(IsYesNoEnum.NO.getKey())) {
                allInPayLogic.serviceCloseOrder(payRecord);
            }
        }
        return null;
    }

    @Transactional
    public void cancel(String id) throws Exception {
        WebsitPartsSalesBean partsSalesOrderBean = loadSalesOrderById(id);
        if(Objects.isNull(partsSalesOrderBean)) {
            throw new RemoteServiceException("配件单状态取消失败，没有该配件单号: " + id) ;
        }
        if(Objects.isNull(partsSalesOrderBean.getStatus())) {
            throw new RemoteServiceException("配件单状态取消失败，该订单状态为空, 单号: " + id) ;
        }
        if(PartsOrderStatusEnum.END.getKey().equals(partsSalesOrderBean.getStatus())) {
            throw new RemoteServiceException("配件单状态取消失败，该订单已完成，不能取消: " + id) ;
        }

        if (Objects.nonNull(partsSalesOrderBean.getWebsitConfirmDate())
                || Objects.nonNull(partsSalesOrderBean.getWorkerConfirmDate())) {
            // 网点或师傅确认时间不为空，则说明已提货，不能取消
            throw new RemoteServiceException("该订单已提货，不能取消: " + id);
        }

        WebsitSalesPayOrder salesPayList = null;

        if (partsSalesOrderBean.getPayType().equals(PayTypeEnum.ALLINPAY.getKey())) {
            salesPayList = getPayList(partsSalesOrderBean);
            if (Objects.nonNull(salesPayList)) {
                // 有支付记录，共用退款方法
                this.commonRefundAmountMethod(partsSalesOrderBean);
            }
        }

        if (partsSalesOrderBean.getIsApply().equals(IsEnum.N.getValue())) {
            if ((PartsOrderStatusEnum.SUBMIT.getKey().equals(partsSalesOrderBean.getStatus()) && Objects.nonNull(salesPayList))
                    || PartsOrderStatusEnum.PAYED.getKey().equals(partsSalesOrderBean.getStatus())) {
                // 已提交有支付记录 或 已支付订单状态，处理库存
                this.handleReverseWebsitAndWorkerStock(partsSalesOrderBean);
            }
        }
        partsSalesOrderBean.setStatus(PartsOrderStatusEnum.CANCEL.getKey());
        websitPartsSalesService.saveOrUpdate(partsSalesOrderBean);
    }

    private void commonRefundAmountMethod(WebsitPartsSalesBean partsSalesOrderBean) {
        //有支付记录，需要增加退款记录
        WebsitPartsRefundRecord partsRefundRecord = new WebsitPartsRefundRecord();
        partsRefundRecord.setRefundNo(IdWorker.getIdStr())
                .setRecordId(partsSalesOrderBean.getId())
                .setCompanyWechatId(partsSalesOrderBean.getCompanyWechatId())
                .setCompanyWechatName(partsSalesOrderBean.getCompanyWechatName())
                .setWebsitId(partsSalesOrderBean.getWebsitId())
                .setWebsitName(partsSalesOrderBean.getWebsitName())
                .setPartsWebsitId(partsSalesOrderBean.getPartsWebsitId())
                .setIdentity(partsSalesOrderBean.getIdentity())
                .setWorkerId(partsSalesOrderBean.getWorkerId())
                .setWorkerName(partsSalesOrderBean.getWorkerName())
                .setSalesId(partsSalesOrderBean.getId())
                .setRef(partsSalesOrderBean.getId())
                .setRefType(PartsRefTypeEnum.SALES.toString())
                .setRefundAmount(partsSalesOrderBean.getTotalAmount())
                .setRefundState(PartsRefundStateEnum.WAIT.getKey())
                .setIsExec(IsEnum.N.getValue())
                .insert();
    }

    @Transactional
    public void transNotApply(String id) throws Exception {
        WebsitPartsSalesBean partsSalesOrderBean = loadSalesOrderById(id);
        if(Objects.isNull(partsSalesOrderBean)) {
            throw new RemoteServiceException("销售申请单转销售单失败，没有该单号: " + id) ;
        }

        this.handleForwardWebsitAndWorkerStock(partsSalesOrderBean);

        websitPartsSalesService.lambdaUpdate()
                .set(WebsitPartsSales::getIsApply, IsEnum.N.getValue())
                .set(WebsitPartsSales::getTransNotApplyDate, DateUtil.date())
                .eq(WebsitPartsSales::getId, partsSalesOrderBean.getId())
                .update();
    }

    public WebsitSalesPayOrder queryPayStatus(String websitId, String id, String outTradeNo) {

        // 查询支付订单记录
        WebsitSalesPayOrder pay = websitSalesPayOrderService.lambdaQuery()
                .eq(WebsitSalesPayOrder::getWebsitId, websitId)
                .eq(WebsitSalesPayOrder::getOrderId, id)
                .eq(WebsitSalesPayOrder::getOutTradeNo, outTradeNo)
                .one();
        if (Objects.isNull(pay)) {
            throw new RemoteServiceException("支付订单记录不存在");
        }

        return pay;
    }

    private List<WorkerStockDTO> getWorkerStock(WebsitPartsSalesBean partsSalesOrderBean, String refType, String partsAttr1, String partsAttr2) {
        if(Collections.isEmpty(partsSalesOrderBean.getItemList())) {
            return null;
        }
        List<WorkerStockDTO> workerStockDTOList = new ArrayList<>();

        for (WebsitPartsSalesItem item : partsSalesOrderBean.getItemList()) {
            if (StringUtils.isNotBlank(partsAttr1)) {
                WorkerStockDTO workerStockDTO = new WorkerStockDTO();
                workerStockDTO.setCompanyWechatId(partsSalesOrderBean.getCompanyWechatId());
                workerStockDTO.setCompanyWechatName(partsSalesOrderBean.getCompanyWechatName());
                workerStockDTO.setIdentity(item.getIdentity());
                workerStockDTO.setWorkerId(partsSalesOrderBean.getWorkerId());
                workerStockDTO.setWorkerName(partsSalesOrderBean.getWorkerName());
                workerStockDTO.setWebsitId(partsSalesOrderBean.getWebsitId());
                workerStockDTO.setWebsitName(partsSalesOrderBean.getWebsitName());
                workerStockDTO.setSdate(DateUtil.date());
                workerStockDTO.setPartsWebsitId(item.getPartsWebsitId());
                workerStockDTO.setGoodsType(WebsitGoodsTypeEnum.P.getKey());
                workerStockDTO.setGoodsId(item.getPartsNumber());
                workerStockDTO.setGoodsName(item.getPartsName());
                workerStockDTO.setMaterialGroupName(item.getMaterialGroupName());
                workerStockDTO.setPrice(item.getMarketPrice());
                workerStockDTO.setGoodsStockUnit(item.getGoodsStockUnit());
                workerStockDTO.setRef(partsSalesOrderBean.getId());
                workerStockDTO.setRefType(refType);
                workerStockDTO.setPartsAttr(partsAttr1);
                workerStockDTO.setChangeQty(item.getQty());
                workerStockDTO.setDirectFlag(DirectFlagEnum.SUB.getKey());
                workerStockDTO.setRemark(partsSalesOrderBean.getRemark());
                workerStockDTO.setOperateBy(partsSalesOrderBean.getWorkerName());
                workerStockDTO.setOperateTime(DateUtil.date());
                workerStockDTOList.add(workerStockDTO);
            }
            if (StringUtils.isNotBlank(partsAttr2)) {
                WorkerStockDTO workerStockDTO = new WorkerStockDTO();
                workerStockDTO.setCompanyWechatId(partsSalesOrderBean.getCompanyWechatId());
                workerStockDTO.setCompanyWechatName(partsSalesOrderBean.getCompanyWechatName());
                workerStockDTO.setIdentity(item.getIdentity());
                workerStockDTO.setWorkerId(partsSalesOrderBean.getWorkerId());
                workerStockDTO.setWorkerName(partsSalesOrderBean.getWorkerName());
                workerStockDTO.setWebsitId(partsSalesOrderBean.getWebsitId());
                workerStockDTO.setWebsitName(partsSalesOrderBean.getWebsitName());
                workerStockDTO.setSdate(DateUtil.date());
                workerStockDTO.setPartsWebsitId(item.getPartsWebsitId());
                workerStockDTO.setGoodsType(WebsitGoodsTypeEnum.P.getKey());
                workerStockDTO.setGoodsId(item.getPartsNumber());
                workerStockDTO.setGoodsName(item.getPartsName());
                workerStockDTO.setMaterialGroupName(item.getMaterialGroupName());
                workerStockDTO.setPrice(item.getMarketPrice());
                workerStockDTO.setGoodsStockUnit(item.getGoodsStockUnit());
                workerStockDTO.setRef(partsSalesOrderBean.getId());
                workerStockDTO.setRefType(refType);
                workerStockDTO.setPartsAttr(partsAttr2);
                workerStockDTO.setChangeQty(item.getQty());
                workerStockDTO.setDirectFlag(DirectFlagEnum.ADD.getKey());
                workerStockDTO.setRemark(partsSalesOrderBean.getRemark());
                workerStockDTO.setOperateBy(partsSalesOrderBean.getWorkerName());
                workerStockDTO.setOperateTime(DateUtil.date());
                workerStockDTOList.add(workerStockDTO);
            }
        }
        return workerStockDTOList;
    }

    private List<WebsitStockDTO> getWebsitStock(WebsitPartsSalesBean partsSalesOrderBean, DirectFlagEnum directFlag, String refType) {
        if(Collections.isEmpty(partsSalesOrderBean.getItemList())) {
            return null;
        }
        List<WebsitStockDTO> websitStockDTOList = new ArrayList<>();
        for(WebsitPartsSalesItem item : partsSalesOrderBean.getItemList()) {
            WebsitStockDTO websitStockDTO = new WebsitStockDTO();
            websitStockDTO.setCompanyWechatId(partsSalesOrderBean.getCompanyWechatId());
            websitStockDTO.setCompanyWechatName(partsSalesOrderBean.getCompanyWechatName());
            websitStockDTO.setWebsitId(partsSalesOrderBean.getWebsitId());
            websitStockDTO.setWebsitName(partsSalesOrderBean.getWebsitName());
            websitStockDTO.setSdate(new Date());
            websitStockDTO.setPartsWebsitId(item.getPartsWebsitId());
            websitStockDTO.setGoodsType(WebsitGoodsTypeEnum.P.getKey());
            websitStockDTO.setGoodsId(item.getPartsNumber());
            websitStockDTO.setGoodsName(item.getPartsName());
            websitStockDTO.setMaterialGroupName(item.getMaterialGroupName());
            websitStockDTO.setGoodsStockUnit(item.getGoodsStockUnit());
            websitStockDTO.setPrice(item.getMarketPrice());
            websitStockDTO.setRef(partsSalesOrderBean.getId());
            websitStockDTO.setRefType(refType);
            websitStockDTO.setVoucherNo(partsSalesOrderBean.getId());
            websitStockDTO.setApplyNo(partsSalesOrderBean.getId());
            websitStockDTO.setObj(partsSalesOrderBean.getBuyPeople().equals(BuyPeopleEnum.CUSTOMER.getKey()) ? BuyPeopleEnum.CUSTOMER.getRemark() : BuyPeopleEnum.WORKER.getRemark());
            websitStockDTO.setPartsAttr(PartsAttrEnum.NEW.getKey());
            websitStockDTO.setChangeQty(item.getQty());
            websitStockDTO.setDirectFlag(directFlag.getKey());
            websitStockDTO.setRemark(partsSalesOrderBean.getRemark());
            websitStockDTO.setOperateBy(partsSalesOrderBean.getSubmitBy());
            websitStockDTO.setOperateTime(new Date());
            websitStockDTO.setStorageId(partsSalesOrderBean.getStorageId());
            websitStockDTOList.add(websitStockDTO);
        }
        return websitStockDTOList;
    }

}
