package com.zfire.mall.manager.logic.pick;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.CommonCountBean;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.PoySaleCountBean;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.invoice.InvoiceApplicationPick;
import com.zfire.mall.manager.bean.invoice.InvoiceBean;
import com.zfire.mall.manager.bean.invoice.InvoicePickBean;
import com.zfire.mall.manager.bean.invoice.InvoiceProjectVO;
import com.zfire.mall.manager.bean.listV2.dto.InvoiceProjectDTO;
import com.zfire.mall.manager.bean.pick.*;
import com.zfire.mall.manager.bean.ship.RetreatDocumentDetail;
import com.zfire.mall.manager.bean.ship.ShipDocumentBean;
import com.zfire.mall.manager.bean.ship.ShipDocumentDetail;
import com.zfire.mall.manager.bean.ship.ShipDocumentProjectBean;
import com.zfire.mall.manager.commonmapper.CommonCountMapper;
import com.zfire.mall.manager.commonmapper.InvoiceMapper;
import com.zfire.mall.manager.commonmapper.ShipMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.enums.PickStatusEnum;
import com.zfire.mall.manager.enums.SMSTypeEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.helper.ResponseHelper;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.common.SMSLogic;
import com.zfire.mall.manager.logic.front.CustomerFrontLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import com.zfire.mall.manager.utils.CommonUtils;
import com.zfire.mall.manager.utils.RedisUtil;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.rmi.RemoteException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author change
 */
@Service
@Slf4j
public class PickLogic {

    @Autowired
    ShipMapper shipMapper;

    @Autowired
    PickManagerShipService pickManagerShipService;

    @Autowired
    ShipDocumentService shipDocumentService;

    @Autowired
    SMSLogic smsLogic;

    @Resource
    RedisUtil redisUtil;

    @Resource
    TakerRecordService takerRecordService;

    @Resource
    InvoiceMapper invoiceMapper;

    @Resource
    ShipDocumentPasswordService shipDocumentPasswordService;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    InvoiceApplicationOrderService invoiceApplicationOrderService;

    @Autowired
    InvoiceApplicationService invoiceApplicationService;

    @Autowired
    SysDictService sysDictService;

    @Autowired
    PickManagerService pickManagerService;

    @Autowired
    StockCorrespondService stockCorrespondService;

    @Autowired
    CommonCountMapper commonCountMapper;

    @Autowired
    PickManagerLogService pickManagerLogService;

    @Autowired
    LogisticsConfigurationService logisticsConfigurationService;

    @Autowired
    PickManagerPushService pickManagerPushService;

    @Autowired
    AdminUserStockService adminUserStockService;

    @Autowired
    CustomerStockService customerStockService;

    @Autowired
    KingDeeCustomerService kingDeeCustomerService;

    @Autowired
    CustomerFrontLogic customerFrontLogic;

    @Autowired
    OrderTrackService orderTrackService;

    @Autowired
    KingDeeCustomerCategoryService kingDeeCustomerCategoryService;

    @Autowired
    KingDeeMaterialService kingDeeMaterialService;

    @Autowired
    TakeCarRecordService takeCarRecordService;

    @Autowired
    SalesOrderService salesOrderService;



    public IPage<PickManagerBean> list(String logisticsId,String printStartTime,String printEndTime,String salesOrderId,String customerIds,String takerPhone, String takerId, String invoiceId, String createBy, String correspondId, String pickStartTime, String pickEndTime,
                                       String startTime, String endTime, String customerNumber, String customerName, Integer pageNum, Integer pageSize, Integer status) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        List<String> collect = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, adminUser.getAdminUserId()).select(AdminUserStock::getCorrespondId).list()
                .stream().map(AdminUserStock::getCorrespondId).distinct().collect(Collectors.toList());

        IPage<PickManagerBean> pickManagerBeanIPage = shipMapper.listPick(new Page<>(pageNum, pageSize),logisticsId,printStartTime,printEndTime,salesOrderId,
                customerIds,takerPhone, takerId, invoiceId, createBy, correspondId, pickStartTime, pickEndTime,
                null, startTime, endTime, customerNumber, customerName, customerId, adminUser.getServiceIds(), status, collect, adminUser.getK3CategoryIds());
        return pickManagerBeanIPage;
    }


    public PoySaleCountBean listCount(String takerId, String invoiceId, String createBy, String correspondId, String pickStartTime, String pickEndTime,
                                      String startTime, String endTime, String customerNumber, String customerName, Integer status) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        PoySaleCountBean commonCountBean = commonCountMapper.pickCount(takerId, invoiceId, createBy, correspondId, pickStartTime, pickEndTime,
                null, startTime, endTime, customerNumber, customerName, customerId, adminUser.getServiceIds(), status, adminUser.getK3CategoryIds());
        return commonCountBean;
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(PickManagerRequest pickManagerRequest, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        pickManagerRequest.setInformationKey(IdWorker.getIdStr().substring(11));
     /*   pickManagerRequest.setPickTime(new Date());*/

        if(DateUtil.beginOfDay(new Date()).after(pickManagerRequest.getPickTime())){
            throw new RemoteServiceException("不能晚于当前日期");
        }

        verificationPick(pickManagerRequest,adminUser);

        //生成订单流水号
        String yyyyMM = DateUtil.format(new Date(), "yyyyMM");
        String order = yyyyMM.substring(yyyyMM.length() - 4);
        if (redisUtil.get(order) == null) {
            redisUtil.set(order, "0000", 60 * 60 * 24 * 31);
        }
        Object water = redisUtil.get(order);
        String s = generateNum(4, Convert.toStr(water));
        pickManagerRequest.setPickOrderWater(order + s);

        if (pickManagerService.lambdaQuery().eq(PickManager::getPickOrderWater, order + s).count() > 0) {
            throw new RemoteServiceException("请勿频繁新增，稍等一会");
        }
        redisUtil.set(order, s, 60 * 60 * 24 * 31);


        StockCorrespond stockCorrespond = stockCorrespondService.getById(pickManagerRequest.getCorrespondId());
        pickManagerRequest.setCorrespondName(stockCorrespond.getName());
        pickManagerRequest.setCustomerNumber(adminUser.getCustomerNumber());
        pickManagerRequest.setCustomerName(adminUser.getCustomerName());
        pickManagerRequest.setCustomerId(adminUser.getCustomerId());

        if (!adminUser.getIsCustomer())
            throw new RemoteServiceException("操作员请勿给商家进行提货");
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(pickManagerRequest.getCustomerId());

        if (!StringUtils.isEmpty(pickManagerRequest.getTakerId())) {
            TakerRecord takerRecord = takerRecordService.getById(pickManagerRequest.getTakerId());
            pickManagerRequest.setTakerPhone(takerRecord.getPhone());
        }

        if (!StringUtils.isEmpty(pickManagerRequest.getTakerCarId())) {
            TakeCarRecord takeCarRecord = takeCarRecordService.getById(pickManagerRequest.getTakerCarId());
            pickManagerRequest.setCarBrand(takeCarRecord.getCarBrand());
            pickManagerRequest.setPickCar(takeCarRecord.getCarBrand());
        }

        pickManagerRequest.insert();
        List<PickManagerShip> pickManagers = new ArrayList<>();

        HashMap<String, String> integer = new HashMap<>();

        //新增提货预约
        for (PickManagerShip shipDocumentBean : pickManagerRequest.getInvoiceOrderIds()) {
            InvoiceApplicationOrder invoiceApplicationOrder = invoiceApplicationOrderService.getById(shipDocumentBean.getInvoiceOrderId());
            InvoiceApplication invoiceApplication = invoiceApplicationService.getById(invoiceApplicationOrder.getInvoiceId());

            if (!invoiceApplication.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()))
                throw new RemoteServiceException("订单已不是审核状态");


            if (shipDocumentBean.getWarehouseFlag() != null && !shipDocumentBean.getWarehouseFlag().equals(0))
                if (StringUtils.isEmpty(shipDocumentBean.getAddress()))
                    throw new RemoteServiceException("地址未填");

            integer.put(invoiceApplication.getId(),invoiceApplication.getId());

      /*      if (integer.get(invoiceApplication.getId()) != null) {
                Integer in = integer.get(invoiceApplication.getId())+1;
                if (in > 5){
                    throw new RemoteServiceException(invoiceApplication.getId()+"当前提货单预约明细超过五个，请分开提货");
                }
                integer.put(invoiceApplication.getId(),in);
            }else {
                integer.put(invoiceApplication.getId(),1);
            }*/

            if (!invoiceApplication.getCorrespondId().equals(pickManagerRequest.getCorrespondId())) {
                throw new RemoteServiceException("发货单不在此仓库下，请点击查询，查询仓库下的发货单");
            }

            if (pickManagerShipService.lambdaQuery().eq(PickManagerShip::getInvoiceOrderId,invoiceApplicationOrder.getId()).count() > 0) {
                throw new RemoteServiceException(invoiceApplicationOrder.getMaterialName()+invoiceApplicationOrder.getSpecification()+"物料发货单号已经预约");
            }

            pickManagerRequest.setCustomerId(invoiceApplication.getCustomerId());
            pickManagerRequest.setCustomerName(invoiceApplication.getCustomerName());
            pickManagerRequest.setCustomerNumber(invoiceApplication.getCustomerNumber());

            shipDocumentBean.setPickId(pickManagerRequest.getId());
            shipDocumentBean.setInvoiceOrderId(shipDocumentBean.getInvoiceOrderId());
            shipDocumentBean.setMaterialId(invoiceApplicationOrder.getMaterialId());
            shipDocumentBean.setMaterialName(invoiceApplicationOrder.getMaterialName());
            shipDocumentBean.setMaterialCode(invoiceApplicationOrder.getMaterialCode());
            shipDocumentBean.setMaterialOldNumber(invoiceApplicationOrder.getMaterialOldNumber());
            shipDocumentBean.setMainOrderId(invoiceApplicationOrder.getMainOrderId());
            shipDocumentBean.setOrderId(invoiceApplicationOrder.getOrderId());
            shipDocumentBean.setInvoiceId(invoiceApplicationOrder.getInvoiceId());
            shipDocumentBean.setApprovalNumber(invoiceApplicationOrder.getApprovalNumber());
            shipDocumentBean.setInvoiceNum(invoiceApplicationOrder.getInvoiceNum());
            shipDocumentBean.setRefundableQty(invoiceApplicationOrder.getRefundableQty());
            shipDocumentBean.setOrderType(invoiceApplicationOrder.getOrderType());
            shipDocumentBean.setSaleTypeId(invoiceApplicationOrder.getSaleTypeId());
            shipDocumentBean.setSaleTypeCode(invoiceApplicationOrder.getSaleTypeCode());
            shipDocumentBean.setSaleTypeName(invoiceApplicationOrder.getSaleTypeName());
            shipDocumentBean.setTheTime(invoiceApplicationOrder.getTheTime());
            shipDocumentBean.setSpecification(invoiceApplicationOrder.getSpecification());
            shipDocumentBean.setUnit(invoiceApplicationOrder.getUnit());
            shipDocumentBean.setPrice(invoiceApplicationOrder.getPrice());
            shipDocumentBean.setPayAmount(invoiceApplicationOrder.getPayAmount());
            shipDocumentBean.setTax(invoiceApplicationOrder.getTax());
            shipDocumentBean.setQty(invoiceApplicationOrder.getQty());
            shipDocumentBean.setAfterTaxPrice(invoiceApplicationOrder.getAfterTaxPrice());
            shipDocumentBean.setNoTotalAmount(invoiceApplicationOrder.getNoTotalAmount());
            shipDocumentBean.setPayRebateAmount(invoiceApplicationOrder.getPayRebateAmount());
            shipDocumentBean.setTotalDiscAmount(invoiceApplicationOrder.getTotalDiscAmount());
            shipDocumentBean.setK3CategoryId(invoiceApplicationOrder.getK3CategoryId());
            shipDocumentBean.setK3CategoryName(invoiceApplicationOrder.getK3CategoryName());
            shipDocumentBean.setK3CategoryNumber(invoiceApplicationOrder.getK3CategoryNumber());
            shipDocumentBean.setSalesOrderId(invoiceApplication.getSalesOrderId());
            shipDocumentBean.setRefEnginRecordNo(invoiceApplication.getRefEnginRecordNo());
            shipDocumentBean.setEnginOrderNo(invoiceApplication.getEnginOrderNo());
            shipDocumentBean.setCustomerWalletId(invoiceApplicationOrder.getCustomerWalletId());
            shipDocumentBean.setCustomerOrderId(shipDocumentBean.getCustomerOrderId());
            pickManagers.add(shipDocumentBean);
        }

/*        List<String> collect1 = pickManagers.stream().map(PickManagerShip::getMaterialId).distinct().collect(Collectors.toList());
        if (collect1.size() != pickManagers.size()) {
            throw new RemoteServiceException("一个提货单不能有相同得物料");
        }*/
        pickManagerRequest.updateById();

        pickManagerShipService.saveBatch(pickManagers);
        invoiceMapper.updatePick(pickManagerRequest.getId());
    }

    private void verificationPick(PickManagerRequest pickManagerRequest, AdminUserCom adminUser) {
        if (adminUser.getFrontPickType() == null || !adminUser.getFrontPickType())
            return;

        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(adminUser.getCustomerId());

        if (pickManagerRequest.getPickType().equals(1) && !kingDeeCustomer.getIsPick())
            throw new RemoteServiceException("该账号不允许自提，请联系管理员");

        if (pickManagerRequest.getPickType().equals(2) && !kingDeeCustomer.getIsFront())
            throw new RemoteServiceException("该账号不允许物流，请联系管理员");

        if (pickManagerRequest.getPickType().equals(1)) {

            List<KingDeeCustomerCategory> list = kingDeeCustomerCategoryService.lambdaQuery().eq(KingDeeCustomerCategory::getCustomerId, adminUser.getCustomerId())
                    .eq(KingDeeCustomerCategory::getType,1)
                    .select(KingDeeCustomerCategory::getCategoryId).list();

            for (PickManagerShip invoiceOrderId : pickManagerRequest.getInvoiceOrderIds()) {

                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(invoiceOrderId.getMaterialId());
                List<KingDeeCustomerCategory> collect = list.stream().filter(item -> item.getCategoryId().equals(kingDeeMaterial.getCategoryId())).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(collect))
                    throw new RemoteServiceException(kingDeeMaterial.getName()+"--"+kingDeeMaterial.getSpecification()+"该物料不允许自提，请联系管理员");
            }

        }

        if (pickManagerRequest.getPickType().equals(2)) {

            List<KingDeeCustomerCategory> list = kingDeeCustomerCategoryService.lambdaQuery().eq(KingDeeCustomerCategory::getCustomerId, adminUser.getCustomerId())
                    .eq(KingDeeCustomerCategory::getType,2)
                    .select(KingDeeCustomerCategory::getCategoryId).list();

            for (PickManagerShip invoiceOrderId : pickManagerRequest.getInvoiceOrderIds()) {

                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(invoiceOrderId.getMaterialId());
                List<KingDeeCustomerCategory> collect = list.stream().filter(item -> item.getCategoryId().equals(kingDeeMaterial.getCategoryId())).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(collect))
                    throw new RemoteServiceException(kingDeeMaterial.getName()+"--"+kingDeeMaterial.getSpecification()+"该物料不允许物流，请联系管理员");
            }

        }

    }


    public synchronized String generateNum(int digit, String currentStr) {

        char[] alphatableb = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
                'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
                'V', 'W', 'X', 'Y', 'Z'};
        //流水序号，默认4位
        String formatStr1 = "0000";
        int maxNum = 9999;
        StringBuffer tmpBuff = new StringBuffer();
        StringBuffer tmpBuff1 = new StringBuffer();
        for (int i = 1; i < digit; i++) {
            tmpBuff.append(0);
            tmpBuff1.append(9);
        }
        formatStr1 = tmpBuff.toString() + "0";
        maxNum = Integer.parseInt(tmpBuff1.append(9).toString());

        String initStr = "";
        if (currentStr == null) {
            initStr = maxNum + "";
        } else {
            initStr = currentStr;
        }

        //找出字符串最后一位字母
        int sign = 0;
        boolean isfind = false;
        for (int i = initStr.length() - 1; i >= 0; i--) {
            if (initStr.charAt(i) >= 'A' && initStr.charAt(i) <= 'Z') {
                sign = i;
                isfind = true;
                break;
            }
        }
        //分隔字母和数字
        String letterStr = "";
        String numStr = "";
        if (isfind) {
            letterStr = initStr.substring(0, sign + 1);
            numStr = initStr.substring(sign + 1);
        } else {
            numStr = initStr;
        }

        //如果数字部分不全为9，则直接加一，返回
        boolean isAllNine = false;
        for (int i = 0; i < numStr.length(); i++) {
            if (numStr.charAt(i) == '9') {
                isAllNine = true;
            } else {
                isAllNine = false;
                break;
            }
        }
        if (!isAllNine && !"".equals(numStr)) {
            int nextNum = Integer.parseInt(numStr) + 1;
            return letterStr + addNumPrefix(nextNum, numStr.length());
        } else {
            //数字部分全为9或者数字部分为空，需要分情况分析
            String nextNum = "";
            if ("".equals(letterStr)) {
                //字母部分为空
                String nineStr = numStr.substring(1);
                nextNum = "A" + revertNineToFirst(nineStr);
            } else {
                //字母部分不为空
                //判断字母部分的最后一位字母是否有下一位，比如A，则有下一位B，Z则没有。
                char lastLetter = letterStr.charAt(letterStr.length() - 1);
                int pos = -1;
                //顺序查找
                for (int i = 0; i < alphatableb.length; i++) {
                    if (alphatableb[i] == lastLetter) {
                        pos = i;
                        break;
                    }
                }
                if (pos == -1) {
                    System.out.println("查找字母出错");
                    return "error";
                }
                if ('Z' == alphatableb[pos]) {
                    //最后一位字母为'Z'
                    if (!"".equals(numStr)) {
                        //Z999
                        nextNum = letterStr.substring(0, letterStr.length())
                                + 'A' + revertNineToFirst(numStr.substring(1));
                    } else {
                        //ZZZZ
                        System.out.println("商户序号已达到最大值，请联系管理员");
                        return "error";
                    }
                } else {
                    //最后一位字母不为'Z'
                    if (!"".equals(numStr)) {
                        //ZA99
                        nextNum = letterStr.substring(0, letterStr.length() - 1)
                                + alphatableb[pos + 1] + revertNineToFirst(numStr);
                    } else {
                        //ZZZA
                        nextNum = letterStr.substring(0, letterStr.length() - 1)
                                + alphatableb[pos + 1];
                    }
                }
            }
            return nextNum;

        }

    }

    /**
     * 补充数字前缀
     *
     * @param nextNum
     * @param numLen
     * @return
     */
    private String addNumPrefix(int nextNum, int numLen) {
        StringBuffer tmpBuff = new StringBuffer();
        for (int i = 0; i < numLen; i++) {
            tmpBuff.append(0);
        }
        DecimalFormat format = new DecimalFormat(tmpBuff.toString());
        return format.format(nextNum);
    }

    /**
     * 转化999为001
     *
     * @param nineStr
     * @return
     */
    public String revertNineToFirst(String nineStr) {
        if ("".equals(nineStr)) return nineStr;
        String zeroStr = nineStr.replace('9', '0');
        DecimalFormat format = new DecimalFormat(zeroStr);
        int firstNum = Integer.parseInt(zeroStr) + 1;
        return format.format(firstNum);
    }


    public void sendCode(String mobile) throws Exception {
        if (!Validator.isMobile(mobile)) {
            throw new RemoteServiceException("联系电话格式不符");
        }
        // 向手机号发送验证码
        smsLogic.sendSms(Constant.RedisPrefix.VALIDA_PICK_MANAGER, mobile, SMSTypeEnum.VALIDA_PHONE_SMS.toString(), Constant.SMS_EXPIRE);

    }


    public List<TakerRecord> verifyCode(String mobile, String code) {
        Object validMessageCode = redisUtil.get(Constant.RedisPrefix.VALIDA_PICK_MANAGER + mobile);
        List<TakerRecord> list = takerRecordService.lambdaQuery().eq(TakerRecord::getPhone, mobile)
                .eq(TakerRecord::getDel,0)
                .eq(TakerRecord::getFlag,1)
                .list();
        Boolean verify = false;
        if (code.equals(validMessageCode)) {
            verify = true;

        }
        redisUtil.del(Constant.RedisPrefix.VALIDA_PICK_MANAGER + mobile);
        if (verify == true)
            return list;

        List<TakerRecord> collect = list.stream()
                .filter(item -> item.getIdentity().substring(item.getIdentity().length() - 6, item.getIdentity().length()).equals(code)).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(collect))
            throw new RemoteServiceException("验证失败");
        return collect;

    }

    @Transactional(rollbackFor = Exception.class)
    public PickManagerDetailBean detail(String id) {
        return shipMapper.detailPick(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void printAdd(List<String> ids, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        for (String id : ids) {
            PickManager pickManager = pickManagerService.getById(id);
            if (pickManager == null)
                throw new RemoteServiceException("单被商家取消预约，请刷新页面，重新选择打印");
            PickManagerLog pickManagerLog = BeanUtil.toBean(pickManager, PickManagerLog.class);
            pickManagerLog.setOperatorBy(adminUser.getNickName());
            pickManagerLog.setId(null);
            pickManagerLog.setPickId(pickManager.getId());
            pickManagerLog.insert();

            //销售出库单记录物流公司
            if (pickManager.getPickType() != null && pickManager.getPickType().equals(2)){
                for (PickManagerShip pickManagerShip : pickManagerShipService.lambdaQuery().eq(PickManagerShip::getPickId, pickManager.getId()).list()) {
                    InvoiceApplicationOrder byId = invoiceApplicationOrderService.getById(pickManagerShip.getInvoiceOrderId());
                    InvoiceApplication invoiceApplication = invoiceApplicationService.getById(byId.getInvoiceId());
                    LogisticsConfiguration logisticsConfiguration = logisticsConfigurationService.getById(pickManager.getLogisticsId());
                    salesOrderService.lambdaUpdate().eq(SalesOrder::getOrderNo,invoiceApplication.getId())
                            .eq(SalesOrder::getType,1)
                            .set(SalesOrder::getLogisticsName,logisticsConfiguration.getLogisticsCompany()).update();
                }
            }



            //嘉贤物流仓需要记录订单
            if (pickManager.getPickType() != null && pickManager.getPickType().equals(2) &&
                    logisticsConfigurationService.getById(pickManager.getLogisticsId()).getLogisticsNumber().equals(Constant.JIA_XIAN_WU_LIU)){


                for (PickManagerShip pickManagerShip : pickManagerShipService.lambdaQuery().eq(PickManagerShip::getPickId, pickManager.getId()).list()) {
                    InvoiceApplicationOrder byId = invoiceApplicationOrderService.getById(pickManagerShip.getInvoiceOrderId());
                    InvoiceApplication invoiceApplication = invoiceApplicationService.getById(byId.getInvoiceId());
                    PickManagerPush pickManagerPushUP = pickManagerPushService.lambdaQuery().eq(PickManagerPush::getInvoiceId, invoiceApplication.getId()).last("limit 1").one();



                    if (pickManagerPushUP != null) {
                    }else {
                        PickManagerPush pickManagerPush = new PickManagerPush();
                        pickManagerPush.setPickId(pickManager.getId());
                        pickManagerPush.setPickTime(pickManager.getPickTime());

                        pickManagerPush.setInvoiceId(invoiceApplication.getId());
                        pickManagerPush.setWarehouseFlag(pickManagerShip.getWarehouseFlag());
                        pickManagerPush.setReceivingName(pickManagerShip.getReceivingName());
                        pickManagerPush.setPhone(pickManagerShip.getPhone());
                        pickManagerPush.setAddress(pickManagerShip.getAddress());
                        pickManagerPush.setRemark(pickManager.getRemark());
                        pickManagerPush.setIsUp(pickManager.getIsUp());
                        pickManagerPush.setIsDischarge(pickManager.getIsDischarge());
                        pickManagerPush.setCustomerOrderId(pickManagerShip.getCustomerOrderId());
                        pickManagerPush.setSalesOrderNo(invoiceApplication.getSalesOrderId());


         /*               if (StringUtils.isNotEmpty(invoiceApplication.getEnginOrderNo())){

                            pickManagerPush.setInvoiceId(invoiceApplication.getId());
                            pickManagerPush.setWarehouseFlag(1);
                            pickManagerPush.setReceivingName(invoiceApplication.getRefLinkman());
                            pickManagerPush.setPhone(invoiceApplication.getRefPhone());
                            pickManagerPush.setAddress(invoiceApplication.getRefInstallAddress());
                        }else {
                            pickManagerPush.setInvoiceId(invoiceApplication.getId());
                            if (StringUtils.isNotEmpty(pickManagerShip.getAddress())) {
                                pickManagerPush.setWarehouseFlag(2);
                                pickManagerPush.setReceivingName(pickManagerShip.getReceivingName());
                                pickManagerPush.setPhone(pickManagerShip.getPhone());
                                pickManagerPush.setAddress(pickManagerShip.getAddress());
                            }else {
                                pickManagerPush.setWarehouseFlag(0);
                            }
                        }*/
                        pickManagerPush.insert();
                    }
                }

            }

            KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(pickManager.getCustomerId());
            //增加经销商库存
            if (pickManager.getPickType() != null && pickManager.getPickType().equals(2) &&
                    logisticsConfigurationService.getById(pickManager.getLogisticsId()).getLogisticsNumber().equals(Constant.JIA_XIAN_WU_LIU)){
                customerStockInsert(id,1);
            }

        }
        shipMapper.printAdd(ids);
        shipMapper.printAddInvoice(ids);

    }


    /*
    * id  提货id
    * i   1前置仓  2商家仓
    * */
    private void customerStockInsert(String id, int i) {

        for (PickManagerShip pickManagerShip : pickManagerShipService.lambdaQuery().eq(PickManagerShip::getPickId, id).list()) {


            InvoiceApplicationOrder invoiceApplicationOrder = invoiceApplicationOrderService.getById(pickManagerShip.getInvoiceOrderId());
            InvoiceApplication invoiceApplication = invoiceApplicationService.getById(invoiceApplicationOrder.getInvoiceId());
            if (pickManagerShip.getStatus().equals(0)){

                if (i == 1 && pickManagerShip.getWarehouseFlag().equals(0)){
                customerFrontLogic.stockAcc(true,Convert.toInt(invoiceApplicationOrder.getRefundableQty()+invoiceApplicationOrder.getRetiredQty()),invoiceApplication.getId(),
                        "打印发货单增加商家库存",i,invoiceApplicationOrder.getMaterialId(),invoiceApplication.getCustomerId(),invoiceApplication.getRemark());
                }else if((i == 1 && pickManagerShip.getWarehouseFlag().equals(2))) {
                    customerFrontLogic.stockAcc(true,Convert.toInt(invoiceApplicationOrder.getRefundableQty()+invoiceApplicationOrder.getRetiredQty()),invoiceApplication.getId(),
                            "打印发货单增加商家库存",i,invoiceApplicationOrder.getMaterialId(),invoiceApplication.getCustomerId(),invoiceApplication.getRemark());
                }

                if (CollectionUtils.isEmpty(customerStockService.lambdaQuery()
                        .eq(CustomerStock::getMaterialCode, pickManagerShip.getMaterialCode()).eq(CustomerStock::getCustomerId, invoiceApplication.getCustomerId()).list())) {
                    CustomerStock customerStock = new CustomerStock();
                    customerStock.setCustomerId(invoiceApplication.getCustomerId());
                    customerStock.setCustomerName(invoiceApplication.getCustomerName());
                    customerStock.setCustomerNumber(invoiceApplication.getCustomerNumber());
                    customerStock.setMaterialCode(invoiceApplicationOrder.getMaterialCode());
                    customerStock.setMaterialId(invoiceApplicationOrder.getMaterialId());
                    customerStock.setMaterialName(invoiceApplicationOrder.getMaterialName());
                    customerStock.setMaterialOldNumber(invoiceApplicationOrder.getMaterialOldNumber());
                    customerStock.setSpecification(invoiceApplicationOrder.getSpecification());
                    customerStock.setCategoryId(invoiceApplicationOrder.getCategoryId());
                    customerStock.setCategoryName(invoiceApplicationOrder.getCategoryName());
                    customerStock.setCategoryNumber(invoiceApplicationOrder.getCategoryNumber());
                    if (i == 1 && pickManagerShip.getWarehouseFlag().equals(0)){
                        customerStock.setFrontStockNum(Convert.toBigDecimal(invoiceApplicationOrder.getRefundableQty()+invoiceApplicationOrder.getRetiredQty()));
                    }else if((i == 1 && pickManagerShip.getWarehouseFlag().equals(2))) {
                        customerStock.setCustomerStockNum(Convert.toBigDecimal(invoiceApplicationOrder.getRefundableQty()+invoiceApplicationOrder.getRetiredQty()));
                    }
                    customerStock.insert();
                }else {
                    CustomerStock customerStockOne = customerStockService.lambdaQuery()
                            .eq(CustomerStock::getMaterialCode, pickManagerShip.getMaterialCode()).eq(CustomerStock::getCustomerId, invoiceApplication.getCustomerId()).last("limit 1").one();
                    if (i == 1  && pickManagerShip.getWarehouseFlag().equals(0)){
                        customerStockOne.setFrontStockNum(customerStockOne.getFrontStockNum().add(Convert.toBigDecimal(invoiceApplicationOrder.getRefundableQty()+invoiceApplicationOrder.getRetiredQty())));
                    }else if((i == 1 && pickManagerShip.getWarehouseFlag().equals(2))) {
                        customerStockOne.setCustomerStockNum(customerStockOne.getCustomerStockNum().add(Convert.toBigDecimal(invoiceApplicationOrder.getRefundableQty()+invoiceApplicationOrder.getRetiredQty())));
                    }
                    customerStockOne.updateById();
                }
            }



        }
    }


    public List<InvoicePickBean> listInvoice(String correspondId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        List<InvoicePickBean> invoicePickBeans = invoiceMapper.listInvoicePick(correspondId, customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds());
        return invoicePickBeans;
    }

    public void verifyShip(String shipId, String password) {

        if (shipDocumentPasswordService.lambdaQuery().eq(ShipDocumentPassword::getShipId, shipId).eq(ShipDocumentPassword::getStatus, 1).eq(ShipDocumentPassword::getPrintPassword, password).count() < 1
                && sysDictService.lambdaQuery().eq(SysDict::getDictType, "PRINT_PASSWORD").eq(SysDict::getDictValue, password).count() < 1) {
            throw new RemoteServiceException("重复打印密码错误");
        }

        shipDocumentPasswordService.lambdaUpdate()
                .eq(ShipDocumentPassword::getShipId, shipId)
                .eq(ShipDocumentPassword::getStatus, 1)
                .eq(ShipDocumentPassword::getPrintPassword, password)
                .set(ShipDocumentPassword::getStatus, 0);
    }


    @Transactional(rollbackFor = Exception.class)
    public void update(PickManagerRequest pickManagerRequest, HttpServletRequest request) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        verificationPick(pickManagerRequest,adminUser);

        for (PickManagerShip pickManagerShip : pickManagerShipService.lambdaQuery().eq(PickManagerShip::getPickId, pickManagerRequest.getId()).list()) {
            InvoiceApplicationOrder byId = invoiceApplicationOrderService.getById(pickManagerShip.getInvoiceOrderId());
            InvoiceApplication invoiceApplication = invoiceApplicationService.getById(byId.getInvoiceId());
            PickManagerPush pickManagerPush = pickManagerPushService.lambdaQuery().eq(PickManagerPush::getInvoiceId, invoiceApplication.getId()).last("limit 1").one();
            if (pickManagerPush != null) {
                pickManagerPush.setStatus("CANCEL");
                pickManagerPush.setUpdateTime(new Date());
                pickManagerPush.updateById();
            }
        }


        StockCorrespond stockCorrespond = stockCorrespondService.getById(pickManagerRequest.getCorrespondId());
        PickManager pickManager = pickManagerService.getById(pickManagerRequest.getId());
        pickManager.setCorrespondName(stockCorrespond.getName());
        pickManager.setPickStatus(pickManagerRequest.getPickStatus());
        if (!StringUtils.isEmpty(pickManagerRequest.getTakerId())) {
            TakerRecord takerRecord = takerRecordService.getById(pickManagerRequest.getTakerId());
            pickManager.setTakerPhone(takerRecord.getPhone());
        }

        if (!StringUtils.isEmpty(pickManagerRequest.getTakerCarId())) {
            TakeCarRecord takeCarRecord = takeCarRecordService.getById(pickManagerRequest.getTakerCarId());
            pickManagerRequest.setCarBrand(takeCarRecord.getCarBrand());
            pickManagerRequest.setPickCar(takeCarRecord.getCarBrand());
        }
        if (pickManagerRequest.getPickType().equals(1)){
            pickManager.setPickType(pickManagerRequest.getPickType());
            pickManager.setLogisticsId(null);
            pickManager.setPickLogistics(null);
            pickManager.setPickCar(pickManagerRequest.getPickCar());
            pickManager.setTakerName(pickManagerRequest.getTakerName());
            pickManager.setCarBrand(pickManagerRequest.getCarBrand());
            pickManager.setTakerCarId(pickManagerRequest.getTakerCarId());
            pickManager.setTakerId(pickManagerRequest.getTakerId());
            pickManager.setRemark(pickManagerRequest.getRemark());
        }
        if (pickManagerRequest.getPickType().equals(2)){
            pickManager.setPickType(pickManagerRequest.getPickType());
            pickManager.setLogisticsId(pickManagerRequest.getLogisticsId());
            pickManager.setPickLogistics(pickManagerRequest.getPickLogistics());
            pickManager.setRemark(pickManagerRequest.getRemark());
            pickManager.setPickCar(null);
            pickManager.setTakerId(null);
            pickManager.setTakerName(null);
            pickManager.setCarBrand(null);
            pickManager.setTakerCarId(null);
            pickManager.setIsDischarge(pickManagerRequest.getIsDischarge());
            pickManager.setIsUp(pickManagerRequest.getIsUp());
        }
        pickManagerRequest.deleteById();
        pickManager.insert();
        List<PickManagerShip> pickManagers = new ArrayList<>();

        for (PickManagerShip pickManagerShip : pickManagerShipService.lambdaQuery().eq(PickManagerShip::getPickId, pickManagerRequest.getId()).list()) {
            if (!pickManagerShip.getStatus().equals(0)) {
                throw new RemoteServiceException("该提货单已打单，不能修改");
            }
        }


        //新增提货预约
        pickManagerShipService.lambdaUpdate().eq(PickManagerShip::getPickId, pickManagerRequest.getId()).remove();
        for (PickManagerShip shipDocumentBean : pickManagerRequest.getInvoiceOrderIds()) {

            InvoiceApplicationOrder invoiceApplicationOrder = invoiceApplicationOrderService.getById(shipDocumentBean.getInvoiceOrderId());
            InvoiceApplication invoiceApplication = invoiceApplicationService.getById(invoiceApplicationOrder.getInvoiceId());

      /*      if (integer.get(invoiceApplication.getId()) != null) {
                Integer in = integer.get(invoiceApplication.getId())+1;
                if (in > 5){
                    throw new RemoteServiceException(invoiceApplication.getId()+"当前提货单预约明细超过五个，请分开提货");
                }
                integer.put(invoiceApplication.getId(),in);
            }else {
                integer.put(invoiceApplication.getId(),1);
            }*/

            if (!invoiceApplication.getCorrespondId().equals(pickManagerRequest.getCorrespondId())) {
                throw new RemoteServiceException("发货单不在此仓库下，请点击查询，查询仓库下的发货单");
            }

            if (pickManagerShipService.lambdaQuery().eq(PickManagerShip::getInvoiceOrderId,invoiceApplicationOrder.getId()).count() > 0) {
                throw new RemoteServiceException(invoiceApplicationOrder.getMaterialName()+invoiceApplicationOrder.getSpecification()+"物料发货单号已经预约");
            }

            pickManagerRequest.setCustomerId(invoiceApplication.getCustomerId());
            pickManagerRequest.setCustomerName(invoiceApplication.getCustomerName());
            pickManagerRequest.setCustomerNumber(invoiceApplication.getCustomerNumber());

            shipDocumentBean.setPickId(pickManagerRequest.getId());
            shipDocumentBean.setInvoiceOrderId(shipDocumentBean.getInvoiceOrderId());
            shipDocumentBean.setMaterialId(invoiceApplicationOrder.getMaterialId());
            shipDocumentBean.setMaterialName(invoiceApplicationOrder.getMaterialName());
            shipDocumentBean.setMaterialCode(invoiceApplicationOrder.getMaterialCode());
            shipDocumentBean.setMaterialOldNumber(invoiceApplicationOrder.getMaterialOldNumber());
            shipDocumentBean.setMainOrderId(invoiceApplicationOrder.getMainOrderId());
            shipDocumentBean.setOrderId(invoiceApplicationOrder.getOrderId());
            shipDocumentBean.setInvoiceId(invoiceApplicationOrder.getInvoiceId());
            shipDocumentBean.setApprovalNumber(invoiceApplicationOrder.getApprovalNumber());
            shipDocumentBean.setInvoiceNum(invoiceApplicationOrder.getInvoiceNum());
            shipDocumentBean.setRefundableQty(invoiceApplicationOrder.getRefundableQty());
            shipDocumentBean.setOrderType(invoiceApplicationOrder.getOrderType());
            shipDocumentBean.setSaleTypeId(invoiceApplicationOrder.getSaleTypeId());
            shipDocumentBean.setSaleTypeCode(invoiceApplicationOrder.getSaleTypeCode());
            shipDocumentBean.setSaleTypeName(invoiceApplicationOrder.getSaleTypeName());
            shipDocumentBean.setTheTime(invoiceApplicationOrder.getTheTime());
            shipDocumentBean.setSpecification(invoiceApplicationOrder.getSpecification());
            shipDocumentBean.setUnit(invoiceApplicationOrder.getUnit());
            shipDocumentBean.setPrice(invoiceApplicationOrder.getPrice());
            shipDocumentBean.setPayAmount(invoiceApplicationOrder.getPayAmount());
            shipDocumentBean.setTax(invoiceApplicationOrder.getTax());
            shipDocumentBean.setQty(invoiceApplicationOrder.getQty());
            shipDocumentBean.setAfterTaxPrice(invoiceApplicationOrder.getAfterTaxPrice());
            shipDocumentBean.setNoTotalAmount(invoiceApplicationOrder.getNoTotalAmount());
            shipDocumentBean.setPayRebateAmount(invoiceApplicationOrder.getPayRebateAmount());
            shipDocumentBean.setTotalDiscAmount(invoiceApplicationOrder.getTotalDiscAmount());
            shipDocumentBean.setK3CategoryId(invoiceApplicationOrder.getK3CategoryId());
            shipDocumentBean.setK3CategoryName(invoiceApplicationOrder.getK3CategoryName());
            shipDocumentBean.setK3CategoryNumber(invoiceApplicationOrder.getK3CategoryNumber());
            shipDocumentBean.setSalesOrderId(invoiceApplication.getSalesOrderId());
            shipDocumentBean.setRefEnginRecordNo(invoiceApplication.getRefEnginRecordNo());
            shipDocumentBean.setEnginOrderNo(invoiceApplication.getEnginOrderNo());
            shipDocumentBean.setPickId(pickManager.getId());
            shipDocumentBean.setCustomerWalletId(invoiceApplicationOrder.getCustomerWalletId());
            shipDocumentBean.setId(null);
            shipDocumentBean.setCustomerOrderId(shipDocumentBean.getCustomerOrderId());
            pickManagers.add(shipDocumentBean);
        }
        pickManagerShipService.saveBatch(pickManagers);

        //嘉贤物流仓需要记录订单
       /* if (pickManager.getPickType() != null && pickManager.getPickType().equals(2) &&
                logisticsConfigurationService.getById(pickManager.getLogisticsId()).getLogisticsNumber().equals(Constant.JIA_XIAN_WU_LIU)) {

            for (PickManagerShip pickManagerShip : pickManagerShipService.lambdaQuery().eq(PickManagerShip::getPickId, pickManagerRequest.getId()).list()) {
                InvoiceApplicationOrder byId = invoiceApplicationOrderService.getById(pickManagerShip.getInvoiceOrderId());
                InvoiceApplication invoiceApplication = invoiceApplicationService.getById(byId.getInvoiceId());
                PickManagerPush pickManagerPushUP = pickManagerPushService.lambdaQuery().eq(PickManagerPush::getInvoiceId, invoiceApplication.getId()).last("limit 1").one();
                if (pickManagerPushUP != null) {
                    pickManagerPushUP.setStatus("OK");
                    pickManagerPushUP.setUpdateTime(new Date());
                    pickManagerPushUP.setPickId(pickManagerRequest.getId());
                    pickManagerPushUP.setPickTime(pickManagerRequest.getPickTime());
                    if (StringUtils.isNotEmpty(invoiceApplication.getEnginOrderNo())){
                        pickManagerPushUP.setInvoiceId(invoiceApplication.getId());
                        pickManagerPushUP.setWarehouseFlag(1);
                        pickManagerPushUP.setReceivingName(invoiceApplication.getRefLinkman());
                        pickManagerPushUP.setPhone(invoiceApplication.getRefPhone());
                        pickManagerPushUP.setAddress(invoiceApplication.getRefInstallAddress());
                    }else {
                        pickManagerPushUP.setInvoiceId(invoiceApplication.getId());
                        if (StringUtils.isNotEmpty(pickManagerShip.getAddress())) {
                            pickManagerPushUP.setWarehouseFlag(2);
                            pickManagerPushUP.setReceivingName(pickManagerShip.getReceivingName());
                            pickManagerPushUP.setPhone(pickManagerShip.getPhone());
                            pickManagerPushUP.setAddress(pickManagerShip.getAddress());
                        }else {
                            pickManagerPushUP.setWarehouseFlag(0);
                        }
                    }
                    pickManagerPushUP.updateById();

                }else {
                    PickManagerPush pickManagerPush = new PickManagerPush();
                    pickManagerPush.setPickId(pickManagerRequest.getId());
                    pickManagerPush.setPickTime(pickManagerRequest.getPickTime());
                    if (StringUtils.isNotEmpty(invoiceApplication.getEnginOrderNo())){
                        pickManagerPush.setInvoiceId(invoiceApplication.getId());
                        pickManagerPush.setWarehouseFlag(1);
                        pickManagerPush.setReceivingName(invoiceApplication.getRefLinkman());
                        pickManagerPush.setPhone(invoiceApplication.getRefPhone());
                        pickManagerPush.setAddress(invoiceApplication.getRefInstallAddress());
                    }else {
                        pickManagerPush.setInvoiceId(invoiceApplication.getId());
                        if (StringUtils.isNotEmpty(pickManagerShip.getAddress())) {
                            pickManagerPush.setWarehouseFlag(2);
                            pickManagerPush.setReceivingName(pickManagerShip.getReceivingName());
                            pickManagerPush.setPhone(pickManagerShip.getPhone());
                            pickManagerPush.setAddress(pickManagerShip.getAddress());
                        }else {
                            pickManagerPush.setWarehouseFlag(0);
                        }
                    }
                    pickManagerPush.insert();
                }
            }
        }*/
    }


    /**
     * 提货列表导出
     *
     * @param pickManagerBeans
     * @return
     */
    public ExcelData export(List<PickManagerBean> pickManagerBeans) {
        String[] titles = new String[]{"状态", "预约日期","打单日期", "出库单号", "发货申请单号",
                "提货时段", "提货仓库", "提货方式", "单据创建日期", "销售订单号", "工程登录编号",
                "产品编号", "产品名称", "规格型号", "提货总数量", "申请发货单备注","经销商编码","经销商名称","预约提货人","提货人电话"};
        List<List<Object>> rows = new ArrayList<>();
        for (PickManagerBean pickManagerBean : pickManagerBeans) {
            List<Object> row = new ArrayList<>();
            row.add(CommonUtils.getPickStatusMsg(pickManagerBean.getStatus()));
            row.add(DateUtil.format(pickManagerBean.getPickTime(),"yyyy-MM-dd HH:mm:ss"));
            row.add(DateUtil.format(pickManagerBean.getPrintTime(),"yyyy-MM-dd HH:mm:ss"));
            row.add(pickManagerBean.getSalesOrderId());
            row.add(pickManagerBean.getInvoiceId());

            if (pickManagerBean.getPickStatus() != null && pickManagerBean.getPickStatus().equals("1")) {
                row.add("上午");
            } else if (pickManagerBean.getPickStatus() != null && pickManagerBean.getPickStatus().equals("2")) {
                row.add("下午");
            } else {
                row.add("");
            }
            row.add(pickManagerBean.getCorrespondName());
            if (pickManagerBean.getPickType() != null && pickManagerBean.getPickType().equals(1)) {
                row.add("自提");
            } else {
                row.add("快递物流");
            }
            row.add(DateUtil.formatDate(pickManagerBean.getCreateTime()));

            if (pickManagerBean.getOrderType().equals("HOME") || pickManagerBean.getOrderType().equals("TRADE")) {
                row.add(pickManagerBean.getEnginOrderNo());
            }else if (pickManagerBean.getOrderType().equals("PERMU_HOME") || pickManagerBean.getOrderType().equals("PERMU_TRADE")) {
                row.add(pickManagerBean.getEnginOrderNo());
            }else {
                row.add(pickManagerBean.getMainOrderId());
            }

            row.add(pickManagerBean.getRefEnginRecordNo());
            row.add(pickManagerBean.getMaterialCode());
            row.add(pickManagerBean.getMaterialName());
            row.add(pickManagerBean.getSpecification());
            //审批数量
            row.add(pickManagerBean.getRefundableQty());
            row.add(pickManagerBean.getRemark());
            row.add(pickManagerBean.getCustomerNumber());
            row.add(pickManagerBean.getCustomerName());
            row.add(pickManagerBean.getTakerName());
            row.add(pickManagerBean.getTakerPhone());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    public ExcelData storeExport(List<PickManagerBean> pickManagerBeans) {
        String[] titles = new String[]{"状态", "预约日期","打单日期", "出库单号", "发货申请单号",
                "提货时段", "提货仓库", "提货方式", "单据创建日期", "销售订单号", "工程登录编号",
                "产品编号", "产品名称", "规格型号", "提货总数量", "申请发货单备注","经销商编码","经销商名称","预约提货人","提货人电话"};
        List<List<Object>> rows = new ArrayList<>();
        for (PickManagerBean pickManagerBean : pickManagerBeans) {
            List<Object> row = new ArrayList<>();
            row.add(CommonUtils.getPickStatusMsg(pickManagerBean.getStatus()));
            row.add(DateUtil.format(pickManagerBean.getPickTime(),"yyyy-MM-dd HH:mm:ss"));
            row.add(DateUtil.format(pickManagerBean.getPrintTime(),"yyyy-MM-dd HH:mm:ss"));
            row.add(pickManagerBean.getSalesOrderId());
            row.add(pickManagerBean.getInvoiceId());

            if (pickManagerBean.getPickStatus() != null && pickManagerBean.getPickStatus().equals("1")) {
                row.add("上午");
            } else if (pickManagerBean.getPickStatus() != null && pickManagerBean.getPickStatus().equals("2")) {
                row.add("下午");
            } else {
                row.add("");
            }
            row.add(pickManagerBean.getCorrespondName());
            if (pickManagerBean.getPickType() != null && pickManagerBean.getPickType().equals("1")) {
                row.add("自提");
            } else {
                row.add("快递物流");
            }
            row.add(DateUtil.formatDate(pickManagerBean.getCreateTime()));

            if (pickManagerBean.getOrderType().equals("HOME") || pickManagerBean.getOrderType().equals("TRADE")) {
                row.add(pickManagerBean.getEnginOrderNo());
            }else if (pickManagerBean.getOrderType().equals("PERMU_HOME") || pickManagerBean.getOrderType().equals("PERMU_TRADE")) {
                row.add(pickManagerBean.getEnginOrderNo());
            }else {
                row.add(pickManagerBean.getMainOrderId());
            }

            row.add(pickManagerBean.getRefEnginRecordNo());
            row.add(pickManagerBean.getMaterialCode());
            row.add(pickManagerBean.getMaterialName());
            row.add(pickManagerBean.getSpecification());
            //审批数量
            row.add(pickManagerBean.getRefundableQty());
            row.add(pickManagerBean.getRemark());
            row.add(pickManagerBean.getCustomerNumber());
            row.add(pickManagerBean.getCustomerName());
            row.add(pickManagerBean.getTakerName());
            row.add(pickManagerBean.getTakerPhone());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    public PickSummary summary(String startTime, String endTime) {
        PickSummary pickSummary = invoiceMapper.summary(startTime, endTime);
        PickSummary two = invoiceMapper.summaryHome(startTime, endTime);
        PickSummary three = invoiceMapper.summaryTrade(startTime, endTime);
        PickSummary four = invoiceMapper.summaryLif(startTime, endTime);
        pickSummary.setShipHomeConditionerTower(two.getShipHomeConditionerTower());
        pickSummary.setShipHomeConditionerNum(two.getShipHomeConditionerNum());
        pickSummary.setShipHomeConditionerPrice(two.getShipHomeConditionerPrice());

        pickSummary.setShipTradeConditionerTower(three.getShipTradeConditionerTower());
        pickSummary.setShipTradeConditionerNum(three.getShipTradeConditionerNum());
        pickSummary.setShipTradeConditionerPrice(three.getShipTradeConditionerPrice());

        pickSummary.setPickLifeNum(four.getPickLifeNum());
        pickSummary.setPickLifeTower(four.getPickLifeTower());
        pickSummary.setPickLifePrice(four.getPickLifePrice());
        return pickSummary;
    }

    public IPage<PickManagerBean> listPrint(String takerPhone, String takerId, String invoiceId, String createBy, String correspondId, String pickStartTime, String pickEndTime, String startTime, String endTime, String customerNumber, String customerName, Integer pageNum, Integer pageSize, Integer status) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";


        IPage<PickManagerBean> pickManagerBeanIPage = shipMapper.listPrint(new Page<>(pageNum, pageSize), takerPhone, takerId, invoiceId, createBy, correspondId, pickStartTime, pickEndTime,
                null, startTime, endTime, customerNumber, customerName, customerId, adminUser.getServiceIds(), status, adminUser.getK3CategoryIds());
        return pickManagerBeanIPage;
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<PickManagerPush> list = pickManagerPushService.lambdaQuery().eq(PickManagerPush::getPickId, id).list();
        if (!CollectionUtils.isEmpty(list)) {
            for (PickManagerPush item : list) {
                InvoiceApplication invoiceApplication = invoiceApplicationService.getById(item.getInvoiceId());
                PickManagerPush pickManagerPush = pickManagerPushService.lambdaQuery().eq(PickManagerPush::getInvoiceId, invoiceApplication.getId()).last("limit 1").one();
                if (pickManagerPush != null) {
                    throw new RemoteServiceException("选择嘉贤仓发货，不能取消提货");
              /*      pickManagerPush.setStatus("CANCEL");
                    pickManagerPush.setUpdateTime(new Date());
                    pickManagerPush.updateById();*/
                }
            }
        }


        List<PickManagerShip> pickManagerShips = pickManagerShipService.lambdaQuery().eq(PickManagerShip::getPickId, id).list();
        for (PickManagerShip pickManagerShip : pickManagerShips) {
            if (pickManagerShip.getPrintNum() > 0)
                throw new RemoteServiceException("单已打印不能取消预约");
        }


        pickManagerService.removeById(id);
        pickManagerShipService.lambdaUpdate().eq(PickManagerShip::getPickId, id).remove();
    }

    public IPage<KingDeeCustomer> listCustomer(String phone, String keyword, String region, Integer pageNum, Integer pageSize) {
        return shipMapper.listCustomer(new Page<>(pageNum, pageSize), phone, keyword, region);
    }

    public PickManagerDetailBean detailPrint(String id, String invoiceId) {
        PickManagerDetailBean pickManagerDetailBean = shipMapper.detailPick(id);
        if (pickManagerDetailBean == null)
            return null;
        List<InvoicePickBean> invoicePickBeans  = new ArrayList<>();
        for (InvoicePickBean invoicePickBean : pickManagerDetailBean.getInvoicePickBeans()) {
            if (invoicePickBean.getInvoiceId().equals(invoiceId)) {
                invoicePickBeans.add(invoicePickBean);
            }
        }
        pickManagerDetailBean.setInvoicePickBeans(invoicePickBeans);
        return pickManagerDetailBean;
    }

    public IPage<PickManagerLog> listPickBy(String id, Integer pageNum, Integer pageSize) {

        IPage<PickManagerLog> list = pickManagerLogService.lambdaQuery()
                .eq(com.aliyuncs.utils.StringUtils.isNotEmpty(id), PickManagerLog::getPickId, id)

                .page(new Page<>(pageNum,pageSize));
        return list;
    }

    public PickBean listPush(String syncTime) {
        String sync = Convert.toStr(System.currentTimeMillis() / 1000);
        if (StringUtils.isEmpty(syncTime)){
            List<PickManagerPushBean> pickManagerPushBeans = invoiceMapper.listPush(null);
            PickBean pickBean = new PickBean();
            pickBean.setPickManagerPushBeans(pickManagerPushBeans);
            pickBean.setSyncTime(Convert.toStr(sync));
            return pickBean;
        }
        Date date = DateUtil.date(Convert.toLong(syncTime+"000"));
        String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
        List<PickManagerPushBean> pickManagerPushBeans = invoiceMapper.listPush(format);
        PickBean pickBean = new PickBean();
        pickBean.setPickManagerPushBeans(pickManagerPushBeans);
        pickBean.setSyncTime(Convert.toStr(sync));
        return pickBean;
    }


    public List<OrderTrack> listOrderTrack(String orderId) {
        return orderTrackService.lambdaQuery().eq(OrderTrack::getOrderId,orderId).orderByDesc(OrderTrack::getTime).list();
    }

    public Page<InvoiceApplicationPick> listInvoiceOrder(Integer pageNum, Integer pageSize, String invoiceId, String startTime, String endTime, String userName, String address, String remark) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        Date date = DateUtil.offsetDay(new Date(),-3);
        return invoiceMapper.listInvoiceOrder(new Page<>(pageNum, pageSize),date, customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds(),
                invoiceId,startTime,endTime,userName,address,remark);
    }

    public IPage<PickManagerBeanVO> listV2(ZfireParamBean zfireParamBean) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        List<String> collect = new ArrayList<>();
        if (!adminUser.getIsCustomer()) {
            collect = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, adminUser.getAdminUserId()).select(AdminUserStock::getCorrespondId).list()
                    .stream().map(AdminUserStock::getCorrespondId).distinct().collect(Collectors.toList());

        }
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        IPage<PickManagerBeanVO> invoice = shipMapper.listV2(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()),
                zfireParamBean,
                customerId, adminUser.getServiceIds(), collect, adminUser.getK3CategoryIds());

        return invoice;
    }

    public Page<InvoiceApplicationPick> listInvoiceOrderTWO(Integer pageNum, Integer pageSize, String invoiceId, String startTime, String endTime, String userName, String address, String remark) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        Date date = DateUtil.offsetSecond(new Date(),-21);
        return invoiceMapper.listInvoiceOrder(new Page<>(pageNum, pageSize),date, customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds(),
                invoiceId,startTime,endTime,userName,address,remark);

    }


    public void deleteDa(String id) {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<PickManagerPush> list = pickManagerPushService.lambdaQuery().eq(PickManagerPush::getPickId, id).list();
        if (!CollectionUtils.isEmpty(list)) {
            for (PickManagerPush item : list) {
                InvoiceApplication invoiceApplication = invoiceApplicationService.getById(item.getInvoiceId());
                PickManagerPush pickManagerPush = pickManagerPushService.lambdaQuery().eq(PickManagerPush::getInvoiceId, invoiceApplication.getId()).last("limit 1").one();
                if (pickManagerPush != null) {
                    throw new RemoteServiceException("选择嘉贤仓发货，不能取消提货");
              /*      pickManagerPush.setStatus("CANCEL");
                    pickManagerPush.setUpdateTime(new Date());
                    pickManagerPush.updateById();*/
                }
            }
        }


        pickManagerService.removeById(id);
        pickManagerShipService.lambdaUpdate().eq(PickManagerShip::getPickId, id).remove();
    }
}
