package com.gree.mall.miniapp.logic.workorder;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.gree.mall.miniapp.bean.order.OldProductManagerAdd;
import com.gree.mall.miniapp.bean.order.OrderOldProductAdd;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.bean.workorder.OrderFlagLogic;
import com.gree.mall.miniapp.bean.workorder.PgOrderProductDetailCount;
import com.gree.mall.miniapp.bean.workorder.PgOrderProductDetailVO;
import com.gree.mall.miniapp.enums.PayStatusEnum;
import com.gree.mall.miniapp.enums.workorder.OrderBaseStatusEnum;
import com.gree.mall.miniapp.enums.workorder.OrderFlagEnum;
import com.gree.mall.miniapp.enums.workorder.OrderOperatorLogTypeEnum;
import com.gree.mall.miniapp.enums.workorder.OrderTypeEnum;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.logic.order.OrderLogic;
import com.gree.mall.miniapp.plus.entity.*;
import com.gree.mall.miniapp.plus.service.*;
import com.gree.mall.miniapp.utils.CommonUtils;
import com.gree.mall.miniapp.utils.StringUtil;
import com.gree.mall.miniapp.utils.image.ImageHandlerUtils;
import com.gree.mall.miniapp.utils.oss.OSSUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ChangeOrderLogic {

    @Autowired
    PgOrderBaseService pgOrderBaseService;

    @Autowired
    UserService userService;

    @Autowired
    AdminWebsitService adminWebsitService;

    @Autowired
    PgOrderWorkerService pgOrderWorkerService;

    @Autowired
    PgOrderProductService pgOrderProductService;

    @Autowired
    PgOrderDetailService pgOrderDetailService;

    @Autowired
    OSSUtil ossUtil;

    @Autowired
    OrderBaseLogic orderBaseLogic;

    @Autowired
    OrderLogLogic orderLogLogic;

    @Autowired
    PgOrderProductDetailService pgOrderProductDetailService;

    @Autowired
    OrderLogic orderLogic;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    OrderFlagLogic orderFlagLogic;

    @Autowired
    PgIncreOrderService pgIncreOrderService;

    @Resource
    OrderEnginBaseService orderEnginBaseService;

    @Resource
    WebsitSalesService websitSalesService;

    @Resource
    GoodsCategoryItemService goodsCategoryItemService;

    @Value("${ali.oss.endpoint.ww}")
    private String OSS_WW;

    @Value("${sys.url}")
    private String sysUrl;

    @Value("${server.servlet.context-path}")
    private String contextPath;


    private final OldProductManagerService oldProductManagerService;
    private final OldProductManagerItemService oldProductManagerItemService;
    private final OldProductManagerItemAttributeService oldProductManagerItemAttributeService;
    private final OrderInfoService orderInfoService;
    private final OrderOldProductService orderOldProductService;
    private final OrderOldProductItemService orderOldProductItemService;

    @Transactional(rollbackFor = Exception.class)
    public void changeAppointmentTime(String id, String appointmentTime, String appointmentEndTime,String remark) {
        pgOrderBaseService.lambdaUpdate()
                .eq(PgOrderBase::getId,id)
                .set(PgOrderBase::getAppointmentTime,appointmentTime)
                .set(!StringUtils.isEmpty(remark),PgOrderBase::getChangeRemark,remark)
                .set(PgOrderBase::getAppointmentEndTime,appointmentEndTime)
                .set(PgOrderBase::getLastOperatorAppointmentTime,new Date())
                .update();

        this.addLog(id,remark);
    }

    private void addLog(String id,String remark) {
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(id);

        PgOrderOperatorLog pgOrderOperatorLog = new PgOrderOperatorLog();
        pgOrderOperatorLog.setOrderBaseId(id);
        pgOrderOperatorLog.setType(OrderOperatorLogTypeEnum.GAIYUE.getRemark());
        pgOrderOperatorLog.setTypeText(OrderOperatorLogTypeEnum.GAIYUE.getRemark());
        pgOrderOperatorLog.setAppointmentTime(pgOrderBase.getAppointmentTime());
        pgOrderOperatorLog.setAppointmentEndTime(pgOrderBase.getAppointmentEndTime());
        pgOrderOperatorLog.setContent(remark);
        orderLogLogic.addLog(pgOrderOperatorLog);
    }

    public List<PgOrderProductDetail> getOrderProduct(String id, List<String> status) {

        return  pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderBaseId, id)
                    .in(PgOrderProductDetail::getStatus,status).list();


    }

    public PgOrderProductDetailVO productDetail(String id) {
        PgOrderProductDetail pgOrderProduct = pgOrderProductDetailService.getById(id);

        PgOrderProductDetailVO pgOrderProductDetail = BeanUtil.toBean(pgOrderProduct, PgOrderProductDetailVO.class);

        List<PgOrderDetail> list = pgOrderDetailService.lambdaQuery().eq(PgOrderDetail::getProductDetailId, id).list();

        pgOrderProductDetail.setPgOrderProductDetails(list);

        List<PgOrderWorker> list1 = pgOrderWorkerService.lambdaQuery().eq(PgOrderWorker::getOrderBaseId, pgOrderProductDetail.getOrderBaseId()).list();
        pgOrderProductDetail.setPgOrderWorkers(list1);

        PgOrderBase pgOrderBase = pgOrderBaseService.getById(pgOrderProduct.getOrderBaseId());

        pgOrderProductDetail.setPgOrderBase(pgOrderBase);


        return pgOrderProductDetail;

    }

    @Transactional(rollbackFor = Exception.class)
    public void submit(PgOrderProductDetailVO pgOrderProductDetail) {

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        pgOrderProductDetail.setGiveTime(new Date());
        pgOrderProductDetail.setWorkerId(currentCompanyWechat.getUserId());
        pgOrderProductDetail.setWorkerMobile(currentCompanyWechat.getUser().getMobile());
        pgOrderProductDetail.setWorkerName(currentCompanyWechat.getUser().getNickName());
        pgOrderProductDetail.updateById();
        for (PgOrderDetail orderProductDetail : pgOrderProductDetail.getPgOrderProductDetails()) {
            orderProductDetail.setProductDetailId(pgOrderProductDetail.getId());
            orderProductDetail.setPgOrderDetailId(null);
            orderProductDetail.setOrderBaseId(pgOrderProductDetail.getOrderBaseId());
        }
        pgOrderDetailService.lambdaUpdate().eq(PgOrderDetail::getProductDetailId,pgOrderProductDetail.getId()).remove();
        pgOrderDetailService.saveBatch(pgOrderProductDetail.getPgOrderProductDetails());

        PgOrderBase pgOrderBase = pgOrderBaseService.getById(pgOrderProductDetail.getOrderBaseId());
        if (pgOrderBase.getOrderType().equals(OrderTypeEnum.REPAIR.getKey()) && !StringUtil.isEmpty(pgOrderProductDetail.getInsideCode())){
            List<PgOrderProductDetail> list = pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderBaseId, pgOrderProductDetail.getOrderBaseId())
                    .list();
            List<String> collect = list.stream().filter(item -> !StringUtil.isEmpty(item.getInsideCode())).map(PgOrderProductDetail::getInsideCode).distinct().collect(Collectors.toList());

            if (pgIncreOrderService.lambdaQuery().in(PgIncreOrder::getInsideCode,collect)
                    .eq(PgIncreOrder::getPayStatus, PayStatusEnum.PAID.getKey()).count() > 0) {

                PgIncreOrder one = pgIncreOrderService.lambdaQuery().in(PgIncreOrder::getInsideCode, collect)
                        .eq(PgIncreOrder::getPayStatus, PayStatusEnum.PAID.getKey()).last("limit 1").one();
                pgOrderBaseService.lambdaUpdate()
                        .eq(PgOrderBase::getId,pgOrderProductDetail.getOrderBaseId())
                        .set(PgOrderBase::getPgIncreId,one.getPgIncreId())
                        .set(PgOrderBase::getPgIncreItemId,one.getPgIncreItemId())
                        .set(PgOrderBase::getPgIncreOrderId,one.getId())
                        .set(PgOrderBase::getPgIncreWebsitId,one.getWebsitId())
                        .set(PgOrderBase::getPgIncreWebsitName,one.getWebsitName())
                        .update();

                orderFlagLogic.saveOrderFlag(Lists.newArrayList(pgOrderProductDetail.getOrderBaseId()), OrderFlagEnum.YB);
            }else {
                orderFlagLogic.deleteOrderFlag(pgOrderProductDetail.getOrderBaseId(), OrderFlagEnum.YB);
            }
        }
    }

    /**
     * 图片生成水印
     * @param productId
     * @param positionName
     */
    public String imageGenerateWatermark(String productId,String patch, String positionName) throws Exception {

        pgOrderProductDetailService.lambdaUpdate().eq(PgOrderProductDetail::getId,productId)
                .set(PgOrderProductDetail::getGiveAddress,positionName).update();

        String path = System.getProperty("user.dir");

        // 拼接后的文件名
        String fileName = path + "/tmp/report";
        // 生成的文件的存放路径
        File mkdir = FileUtil.mkdir(path + "/tmp/report" );

        File file= CommonUtils.getFileByHttpURL(patch, mkdir.getPath(), OSS_WW, sysUrl + contextPath);


        String contentType = FileNameUtil.getSuffix(patch);
        if (org.apache.commons.lang3.StringUtils.isBlank(contentType)) {
            throw new RemoteServiceException("请上传图片格式");
        }
        contentType = contentType.toUpperCase();
        if (!(contentType.contains("JPG") || contentType.contains("PNG") || contentType.contains("JPEG"))) {
            throw new RemoteServiceException("请上传图片格式");
        }

        String fileSuffix = file.getName().substring(file.getName().lastIndexOf("."));

        if (!FileUtil.exist(path + "/tmp/image/compress")) {
            FileUtil.mkdir(path + "/tmp/image/compress");
        }

        if (!FileUtil.exist(path + "/tmp/image/watermark")) {
            FileUtil.mkdir(path + "/tmp/image/watermark");
        }

        if (positionName.length() > 27) {
            int count = (int) Math.ceil(new BigDecimal("" + positionName.length()).divide(new BigDecimal("27"), 2, BigDecimal.ROUND_UP).doubleValue());
            StringBuilder changeStr = new StringBuilder();
            int index = 0;
            for (int i = 0; i < count; i++) {
                if (i == 0) {
                    changeStr.append(positionName, index, 27).append("||");
                    index = index + 27;
                    continue;
                }
                if ((count - 1) == i) {
                    changeStr.append(positionName.substring(index));
                    continue;
                }
                changeStr.append(positionName, index, index + 27).append("||");
                index = index + 27;
            }
            positionName = changeStr.toString();
        }

        String curSdf = DateUtil.formatDateTime(DateUtil.date());
        positionName = positionName + "||" + curSdf;
        String fileOrgName = IdUtil.simpleUUID() + DateUtil.date().getTime() + fileSuffix;

        //        // 压缩并调整分辩率
//        ImageHandlerUtils.compressPicForScale(inputStream, path + "/tmp/image/compress/" + fileOrgName,
//               1000, 0.90f, 720, 960);

        // 上传原图阿里云
        String ossOrgObjectKey = ossUtil.getFilePath()+"/gather/org/" + fileOrgName;
        ossUtil.uploadFile(ossOrgObjectKey, file);

        String style = "image/auto-orient,1/resize,m_lfit,w_720/quality,q_100";

        ossUtil.imageHandle(ossOrgObjectKey, style, path + "/tmp/image/compress/" + fileOrgName);

        // 图片水印
        ImageHandlerUtils.waterPress(path + "/tmp/image/compress/" + fileOrgName,
                path + "/tmp/image/watermark/" + fileOrgName, Color.RED, 24, positionName, fileSuffix.replace(".",""));

        File ossFile = FileUtil.file(path + "/tmp/image/watermark/" + fileOrgName);

        // 上传oss
        String ossObjectKey = ossUtil.getFilePath()+"/watermark/" + fileOrgName;
        ossUtil.uploadFile(ossObjectKey, ossFile);

        // 删除本地文件
        if (FileUtil.exist(path + "/tmp/image/compress/" + fileOrgName)) {
            FileUtil.del(path + "/tmp/image/compress/" + fileOrgName);
        }

        if (FileUtil.exist(path + "/tmp/image/watermark/" + fileOrgName)) {
            FileUtil.del(path + "/tmp/image/watermark/" + fileOrgName);
        }

        return ossUtil.getAccessUrl()+ossObjectKey;
    }


    public String submitPic(String productId,String patch, String positionName) throws IOException {




        String path = System.getProperty("user.dir");

        // 拼接后的文件名
        String fileName = path + "/tmp/report";
        // 生成的文件的存放路径
        File mkdir = FileUtil.mkdir(path + "/tmp/report" );

        File fileByHttpURL = CommonUtils.getFileByHttpURL(patch, mkdir.getPath(), OSS_WW, sysUrl + contextPath);
        File file = FileUtil.file(fileName+"/test2_result.png");

        URL url = new URL(patch);
//将URL对象输入流转化为图片对象 (url.openStream()方法，获得一个输入流)
        Image srcImg = ImageIO.read(url.openStream());

        int widthIf = srcImg.getWidth(null);
        int heightIf = srcImg.getHeight(null);

        if (widthIf < 500 || heightIf <500)
            throw new RemoteServiceException("图片太小，不符合拍照要求,请上传正确图片");

        Integer d = Convert.toInt(positionName.length()*5.2);

        int width = srcImg.getWidth(null)/2*-1+d;
        int height = srcImg.getHeight(null)/2;

        ImgUtil.pressText(fileByHttpURL,file ,positionName, Color.RED,
                new Font("黑体",Font.BOLD,30),
                width,
                height-40,
                0.8f);
        File fileTwo = FileUtil.file(fileName+"/test3_result.png");

        String format = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

        ImgUtil.pressText(file,fileTwo ,format, Color.RED,
                new Font("黑体",Font.BOLD,30),
                width-95,
                height,
                0.8f);

        String filePath = ossUtil.getFilePath()+"/" + UUID.randomUUID().toString() + ".png";

        ossUtil.uploadFile(filePath, fileTwo);

        return ossUtil.getAccessUrl()+filePath;

    }

    public List<PgOrderProductDetailVO> productDetailList(String workerOrderId) {
        List<PgOrderProductDetail> pgOrderProducts = pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderBaseId, workerOrderId).list();

        List<PgOrderProductDetailVO> pgOrderProductDetails = BeanUtil.copyToList(pgOrderProducts, PgOrderProductDetailVO.class);
        for (PgOrderProductDetailVO pgOrderProductDetail : pgOrderProductDetails) {
            List<PgOrderDetail> list = pgOrderDetailService.lambdaQuery().eq(PgOrderDetail::getProductDetailId, pgOrderProductDetail.getId()).list();

            pgOrderProductDetail.setPgOrderProductDetails(list);

            List<PgOrderWorker> list1 = pgOrderWorkerService.lambdaQuery().eq(PgOrderWorker::getOrderBaseId, pgOrderProductDetail.getOrderBaseId()).list();
            pgOrderProductDetail.setPgOrderWorkers(list1);
        }


        return pgOrderProductDetails;
    }

    @Transactional(rollbackFor = Exception.class)
    public void submitAll(String orderBaseId, String overRemark, String userSign,String address) {
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);
        if (pgOrderBase.getOrderStatus().equals(OrderBaseStatusEnum.YWG.getKey()) || pgOrderBase.getOrderStatus().equals(OrderBaseStatusEnum.YJS.getKey())
        || pgOrderBase.getOrderStatus().equals(OrderBaseStatusEnum.YQX.getKey())){
            throw new RemoteServiceException("订单无需完工提交");
        }
        if(pgOrderBase.getAppointmentTime() == null){
            throw new RemoteServiceException("操作失败，请先预约");
        }
        Date date = new Date();
        pgOrderBaseService.lambdaUpdate().eq(PgOrderBase::getId,orderBaseId)
                .set(PgOrderBase::getOverRemark,overRemark)
                .set(PgOrderBase::getOverTime,date)
                .set(PgOrderBase::getOverDate,date)
                .set(PgOrderBase::getOrderStatus,OrderBaseStatusEnum.YWG.getKey())
                .set(PgOrderBase::getOrderStatusText,OrderBaseStatusEnum.YWG.getRemark())
                .set(PgOrderBase::getUserSign,userSign).update();

        if (pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderBaseId,orderBaseId)
                .notIn(PgOrderProductDetail::getStatus,"WAIT_OK","OK").count() > 0) {
            throw new RemoteServiceException("存在未完成采集数据");
        }

        pgOrderProductDetailService.lambdaUpdate().eq(PgOrderProductDetail::getOrderBaseId,orderBaseId)
                .set(PgOrderProductDetail::getStatus,"OK")
                .set(PgOrderProductDetail::getSumbitAddress,address).update();

        PgOrderBase pgOrderBaseU = pgOrderBaseService.getById(orderBaseId);
        List<PgOrderProduct> list = pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId, orderBaseId).list();
        orderLogic.insertSettleOrderMethod(pgOrderBaseU,list);

        this.addAllLog(orderBaseId);

        this.addFlag(orderBaseId);

        // 销售类型=工程 更新结束时间
        if (pgOrderBase.getSaleType().equals(2)) {
            this.updateEndTime(pgOrderBase.getProjectNo());
        }

        if (pgOrderBase.getIsCj())
            this.addOldManager(pgOrderBase.getId());

    }

    private void addOldManager(String id) {
        if (oldProductManagerService.lambdaQuery().eq(OldProductManager::getPgOrderId,id).count() > 0) {
            return;
        }

        PgOrderBase pgOrderBase = pgOrderBaseService.getById(id);

        OrderInfo orderInfo = orderInfoService.getById(pgOrderBase.getSaleOrderId());

        List<OrderOldProduct> list = orderOldProductService.lambdaQuery().eq(OrderOldProduct::getOrderId, pgOrderBase.getSaleOrderId()).list();

        List<OrderOldProductItem> orderOldProductItems = orderOldProductItemService.lambdaQuery().eq(OrderOldProductItem::getOrderId, pgOrderBase.getSaleOrderId()).list();

        OldProductManagerAdd oldProductManagerAdd = new OldProductManagerAdd();
        oldProductManagerAdd.setCompanyName(orderInfo.getCompanyName());
        oldProductManagerAdd.setCompanyWechatId(orderInfo.getCompanyWechatId());
        oldProductManagerAdd.setOrderId(orderInfo.getOrderId());
        oldProductManagerAdd.setPgOrderId(pgOrderBase.getId());
        oldProductManagerAdd.setStatus("IN");
        oldProductManagerAdd.setUserName(pgOrderBase.getUserName());
        oldProductManagerAdd.setUserPhone(pgOrderBase.getUserMobile());
        oldProductManagerAdd.setUserAddress(pgOrderBase.getAddress());
        oldProductManagerAdd.setSaleType(orderInfo.getSaleType());
        oldProductManagerAdd.setOverTime(pgOrderBase.getOverTime());
        oldProductManagerAdd.setRemark(pgOrderBase.getRemark());
        oldProductManagerAdd.setProvince(pgOrderBase.getProvince());
        oldProductManagerAdd.setProvinceId(pgOrderBase.getProvinceId());
        oldProductManagerAdd.setCityId(pgOrderBase.getCityId());
        oldProductManagerAdd.setCity(pgOrderBase.getCity());
        oldProductManagerAdd.setArea(pgOrderBase.getArea());
        oldProductManagerAdd.setAreaId(pgOrderBase.getAreaId());
        oldProductManagerAdd.setStreet(pgOrderBase.getStreet());
        oldProductManagerAdd.setStreetId(pgOrderBase.getStreetId());
        oldProductManagerAdd.setOrderSmallType(pgOrderBase.getOrderSmallType());
        oldProductManagerAdd.setOrderSmallTypeText(pgOrderBase.getOrderSmallTypeText());

        OrderOldProductAdd orderOldProductAdd = new OrderOldProductAdd();

        orderOldProductAdd.setId(list.get(0).getSpecId());
        orderOldProductAdd.setNum(1);
        orderOldProductAdd.setPayAmount(list.get(0).getPayAmount());
        orderOldProductAdd.setItemIds(orderOldProductItems.stream().map(OrderOldProductItem::getGoodsCategoryItemId).collect(Collectors.toList()));

        List<OrderOldProductAdd> orderOldProductAdds = new ArrayList<>();
        orderOldProductAdds.add(orderOldProductAdd);
        oldProductManagerAdd.setOrderOldProductAdds(orderOldProductAdds);
        this.addItem(oldProductManagerAdd);
    }


    @Transactional(rollbackFor = Exception.class)
    public void addItem(OldProductManagerAdd oldProductManagerAdd) {

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();

        oldProductManagerAdd.setCompanyWechatId(currentCompanyWechat.getCompanyWechatId());
        oldProductManagerAdd.setCompanyName(currentCompanyWechat.getCompanyName());

        oldProductManagerAdd.insert();

        //旧机回收

        if (!org.springframework.util.CollectionUtils.isEmpty(oldProductManagerAdd.getOrderOldProductAdds())) {

            List<OldProductManagerItem> oldProductManagerItems = new ArrayList<>();
            List<OldProductManagerItemAttribute> oldProductManagerItemAttributes = new ArrayList<>();

            for (OrderOldProductAdd orderOldProductDTO : oldProductManagerAdd.getOrderOldProductAdds()) {

                GoodsCategoryItem goodsCategoryItemDto = goodsCategoryItemService.getById(orderOldProductDTO.getId());

                OldProductManagerItem oldProductManagerItem = BeanUtil.toBean(goodsCategoryItemDto, OldProductManagerItem.class);


                oldProductManagerItem.setId(IdWorker.getIdStr());
                oldProductManagerItem.setNum(orderOldProductDTO.getNum());
                oldProductManagerItem.setPayAmount(orderOldProductDTO.getPayAmount());
                oldProductManagerItem.setSpecId(goodsCategoryItemDto.getId());
                oldProductManagerItem.setSpecName(goodsCategoryItemDto.getDictName());
                oldProductManagerItem.setOldProductManagerId(oldProductManagerAdd.getId());

                for (String goodsCategoryItem : orderOldProductDTO.getItemIds()) {

                    GoodsCategoryItem goodsCategoryItems = goodsCategoryItemService.getById(goodsCategoryItem);
                    OldProductManagerItemAttribute oldProductManagerItemAttribute = BeanUtil.toBean(goodsCategoryItems, OldProductManagerItemAttribute.class);

                    oldProductManagerItemAttribute.setOldProductManagerItemId(oldProductManagerItem.getId());
                    oldProductManagerItemAttribute.setOldProductManagerId(oldProductManagerAdd.getId());
                    oldProductManagerItemAttribute.setGoodsCategoryItemId(goodsCategoryItems.getId());
                    oldProductManagerItemAttribute.setId(null);

                    oldProductManagerItem.setItemName((StringUtil.isEmpty(oldProductManagerItem.getItemName())?"":oldProductManagerItem.getItemName())+goodsCategoryItems.getDictName()+",");


                    oldProductManagerItemAttributes.add(oldProductManagerItemAttribute);

                }

                if (!StringUtil.isEmpty(oldProductManagerItem.getItemName())){
                    String substring = oldProductManagerItem.getItemName().substring(0, oldProductManagerItem.getItemName().length() - 1);
                    oldProductManagerItem.setItemName(substring);
                }


                oldProductManagerItems.add(oldProductManagerItem);


            }


            if (!org.springframework.util.CollectionUtils.isEmpty(oldProductManagerItems)) {
                oldProductManagerItemService.saveBatch(oldProductManagerItems);
            }

            if (!org.springframework.util.CollectionUtils.isEmpty(oldProductManagerItemAttributes)) {
                oldProductManagerItemAttributeService.saveBatch(oldProductManagerItemAttributes);
            }


        }

    }

    private void addFlag(String orderBaseId) {

        orderFlagLogic.saveOrderFlag(Lists.newArrayList(orderBaseId), OrderFlagEnum.YWG);
    }

    private void addAllLog(String id) {
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(id);

        PgOrderOperatorLog pgOrderOperatorLog = new PgOrderOperatorLog();
        pgOrderOperatorLog.setOrderBaseId(id);
        pgOrderOperatorLog.setType(OrderOperatorLogTypeEnum.WGFK.getRemark());
        pgOrderOperatorLog.setTypeText(OrderOperatorLogTypeEnum.WGFK.getRemark());
        String overRemark =
        StringUtil.isEmpty(pgOrderBase.getOverRemark())?"": pgOrderBase.getOverRemark();

        pgOrderOperatorLog.setContent("师傅完工反馈"+overRemark
        );


        orderLogLogic.addLog(pgOrderOperatorLog);
    }

    public PgOrderProductDetailCount getOrderProductCount(String id) {
        PgOrderProductDetailCount pgOrderProductDetailCount = new PgOrderProductDetailCount();
        Integer count = pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderBaseId, id)
                .in(PgOrderProductDetail::getStatus, "WAIT", "WAIT_SAVE").count();
        Integer ycj = pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderBaseId, id)
                .in(PgOrderProductDetail::getStatus, "WAIT_OK", "OK").count();

        Integer qb = pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderBaseId, id)
            .count();
        pgOrderProductDetailCount.setWcj(count);
        pgOrderProductDetailCount.setYcj(ycj);
        pgOrderProductDetailCount.setQb(qb);
        return pgOrderProductDetailCount;
    }

    @Transactional(rollbackFor = Exception.class)
    public void submitProductDetail(String orderBaseId,String address) {

        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);

        if (pgOrderBase.getOrderType().equals(OrderTypeEnum.REPAIR.getKey())){
            List<PgOrderProductDetail> list = pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderBaseId, orderBaseId)
                    .list();
            List<String> collect = list.stream().filter(item -> !StringUtil.isEmpty(item.getInsideCode())).map(PgOrderProductDetail::getInsideCode).distinct().collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(collect)) {

                if (pgIncreOrderService.lambdaQuery().in(PgIncreOrder::getInsideCode, collect)
                        .eq(PgIncreOrder::getPayStatus, PayStatusEnum.PAID.getKey()).count() > 0) {
                    orderFlagLogic.saveOrderFlag(Lists.newArrayList(orderBaseId), OrderFlagEnum.YB);
                } else {
                    orderFlagLogic.deleteOrderFlag(orderBaseId, OrderFlagEnum.YB);
                }
            }
        }

        if (pgOrderProductDetailService.lambdaQuery().eq(PgOrderProductDetail::getOrderBaseId,orderBaseId)
                .notIn(PgOrderProductDetail::getStatus,"WAIT_OK","OK").count() > 0) {
            throw new RemoteServiceException("存在未完成采集数据");
        }
        pgOrderProductDetailService.lambdaUpdate().eq(PgOrderProductDetail::getOrderBaseId,orderBaseId)
                .set(PgOrderProductDetail::getStatus,"OK")
                .set(PgOrderProductDetail::getSumbitAddress,address).update();

        pgOrderBaseService.lambdaUpdate().eq(PgOrderBase::getId,orderBaseId)
                .set(PgOrderBase::getIsGather,"YES").update();

        orderBaseLogic.reNum(orderBaseId);

    }

    private void updateEndTime(String id) {
        orderEnginBaseService.lambdaUpdate()
                .set(OrderEnginBase::getEndTime, DateUtil.date())
                .eq(OrderEnginBase::getProjectNo, id)
                .update();

        websitSalesService.lambdaUpdate()
                .set(WebsitSales::getEndTime, DateUtil.date())
                .eq(WebsitSales::getProjectNo, id)
                .update();
    }
}
