rk
7 天以前 832e40a8249ae15a5b2a7f01c78da4edc06cd55e
server/visits/dmvisit_service/src/main/java/com/doumee/service/business/impl/JkSketchServiceImpl.java
@@ -1,20 +1,41 @@
package com.doumee.service.business.impl;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.doumee.biz.system.SystemDictDataBiz;
import com.doumee.core.annotation.excel.ExcelImporter;
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.exception.BusinessException;
import com.doumee.core.tsp.*;
import com.doumee.core.utils.*;
import com.doumee.core.wms.model.response.WmsBaseDataResponse;
import com.doumee.core.wms.model.response.WmsBaseResponse;
import com.doumee.dao.admin.request.JkOrdersImport;
import com.doumee.dao.business.*;
import com.doumee.dao.business.model.*;
import com.doumee.service.business.third.model.LoginUserInfo;
import com.doumee.service.business.third.model.PageData;
import com.doumee.service.business.third.model.PageWrap;
import com.doumee.core.utils.Utils;
import com.doumee.dao.business.JkSketchMapper;
import com.doumee.dao.business.model.JkSketch;
import com.doumee.service.business.JkSketchService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import netscape.javascript.JSObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.math.BigDecimal;
import java.util.*;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
 * 交控-线路优化记录信息表Service实现
@@ -26,6 +47,22 @@
    @Autowired
    private JkSketchMapper jkSketchMapper;
    @Autowired
    private JkSketchLineMapper jkSketchLineMapper;
    @Autowired
    private JkSketchCustomerMapper jkSketchCustomerMapper;
    @Autowired
    private JkCustomerMapper jkCustomerMapper;
    @Autowired
    private JkLineMapper jkLineMapper;
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
    @Autowired
    private JkOrdersMapper jkOrdersMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public Integer create(JkSketch jkSketch) {
@@ -51,10 +88,366 @@
        }
        jkSketchMapper.deleteBatchIds(ids);
    }
    //线路优化
    @Override
    public JkSketch updateById(JkSketch jkSketch ) {
        JkSketch model = jkSketchMapper.selectById(jkSketch.getId());
        if(model == null ||Constants.equalsInteger(model.getIsdeleted(),Constants.ONE)){
            throw  new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if( model.getDateInfo() ==  null){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"该线路日期信息不正确,不支持优化!");
        }
       if(Constants.equalsInteger(Constants.ZERO,jkSketch.getForceUpdate()) && Constants.equalsInteger(model.getStatus(),Constants.ONE)){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"该线路存在正在优化中,请耐心等待优化完成或者选择强制优化操作!");
        }
         if(  jkSketch.getLineIdList() ==null || jkSketch.getLineIdList().size()==0 ){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"请选择有效合理的线路进行优化操作!");
        }
        //当前所有线路(符合条件的线路)
        List<JkLine> lineList =  jkLineMapper.selectJoinList(JkLine.class,new MPJLambdaWrapper<JkLine>()
                .selectAll(JkLine.class)
                .eq(JkLine::getWeeks,DateUtil.getWeekZhouOfDate(model.getDateInfo()))//只能选择当前的线路
                .eq(JkLine::getIsdeleted,Constants.ZERO)
                .in(JkLine::getId,jkSketch.getLineIdList())
        );
        Integer totalCus = 0,totalNum =0;
        for(JkLine line :lineList){
            totalCus += Constants.formatIntegerNum(line.getMaxCustomer());//总客户量
            totalNum += Constants.formatIntegerNum(line.getMaxOrder());//总送货量
        }
        if( totalCus < Constants.formatIntegerNum(model.getOrderNum())  ){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"该线路订单客户数量超过了线路总客户量限制,无法进行优化!");
        }
        if( totalNum < Constants.formatBigdecimal(model.getTotalNum()).doubleValue()){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"该线路订单送货量超过了线路总送货量限制,无法进行优化!");
        }
        model.setLineList(lineList);//线路集合
        model.setCustomerList(checkJketchCustomerLocation(model));//订单集合
        model.setStatus(Constants.ONE);
        model.setPlanLineNum(lineList.size());
        model.setEditDate(new Date());
        model.setEditor(jkSketch.getLoginUserInfo().getId());
        model.setPlanLineDate(model.getEditDate());
        model.setPlanLineUserId(jkSketch.getLoginUserInfo().getId());
        model.setJobId(UUID.randomUUID().toString());
        redisTemplate.opsForValue().set(Constants.RedisKeys.JKLINE_JOB+model.getJobId(),true );//做异步处理
        jkSketchMapper.updateById(model);
        return model;
    }
    @Override
    public void updateById(JkSketch jkSketch) {
        jkSketchMapper.updateById(jkSketch);
    @Async
    public void startUpdateLineAsync(JkSketch model) {
        try {
            initCustomerDistance(model);
            List<JkSketchCustomer> customerList = model.getCustomerList();
            List<JkLine> lineList = model.getLineList();
            TspSolver.DataModel dataModel = new TspSolver.DataModel();
            int vehicleNumber1 = lineList.size();//线路数量
            long[] vehicleCapacities1=new long[lineList.size()];//每辆车的最大订单量限制
            long[] demands1 = new long[customerList.size()+1]; //各个点的订单量
            long[][] distanceMatrix1 = new long[customerList.size()+1][customerList.size()+1];
            demands1[0] =0;//原点
            double cLatitude =0;
            double cLongitude =0;
            String location = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.COMPANY_LOCATION).getCode();
            try {
                String[] ss = location.split(",");
                cLongitude = Double.parseDouble(ss[0]);
                cLatitude = Double.parseDouble(ss[1]);
            }catch (Exception e){
            }
            for (int i = 0; i < customerList.size(); i++) {
                distanceMatrix1[0][i] =  DistanceCalculator.calculateDistance(cLatitude,cLongitude,customerList.get(i).getLatitude().doubleValue(),customerList.get(i).getLongitude().doubleValue())/1000;
                distanceMatrix1[i][0] = distanceMatrix1[0][i];
                demands1[i+1] = Constants.formatBigdecimal( customerList.get(i).getTotalNum()).longValue();  //各个点的订单量
                List<Map<String,Object>> disList = customerList.get(i).getDistanceList();
                for (int j = 0; j< disList.size(); j++) {
                    if(disList.size()>j){
                        distanceMatrix1[i+1][j+1]  = (Long) disList.get(j).get("b")/1000;//构造距离矩阵
                    }else{
                        distanceMatrix1[i+1][j+1]  = 1l;
                    }
                }
            }
            for (int i = 0; i < lineList.size(); i++) {
                vehicleCapacities1[i] = lineList.get(i).getMaxOrder();//每辆车的最大订单量限制
            }
            //构造优化数据模型
            dataModel.initDataInfo(vehicleNumber1,demands1,vehicleCapacities1,distanceMatrix1);
            TspSolver.startSearch(dataModel);
            dealSearchSolution(model,dataModel);
        }catch (Exception e){
            e.printStackTrace();
            jkSketchMapper.update(null,new UpdateWrapper<JkSketch>().lambda()
                    .eq(JkSketch::getId,model.getId() )
                    .eq(JkSketch::getJobId,model.getJobId() )
                    .set(JkSketch::getPlanLineInfo,"最近一次线路优化失败!")
                    .set(JkSketch::getStatus,Constants.THREE)
                    .set(JkSketch::getPlanLineEndDate,new Date()));
        }
    }
    private void initCustomerDistance(JkSketch model) {
        String url = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.GAODE_LOCATION_GEOAPI_URL).getCode();
        List<JkCustomer> updateCustomerList = new ArrayList<>();
        List<JkSketchCustomer> customerList = model.getCustomerList();
        for(JkSketchCustomer c : customerList){
            List<DistanceMapParam> tmpList = new ArrayList<>();
            List<DistanceMapParam> distanceMapParamList  = getListFromJsonStr(c.getDistanceJson());
            for(JkSketchCustomer cm : customerList){
                boolean isNew = false;
                DistanceMapParam t = new DistanceMapParam();
                t.setId(cm.getId());
                DistanceMapParam param = getParamByCustomerIds( cm.getId(),distanceMapParamList);
                if(param!=null){//如果之前已经获取过
                    t = param;
                }else{
                    isNew = true;
                    if(Constants.equalsInteger(c.getCustomerId(),cm.getCustomerId())){
                        t.setDistance(0l);
                    }else{
                        DistanceModel dm = DistanceCalculator.calculateDistanceGaode(url,c,cm);
                        t.setDistance(dm.getDistance() );
                        if(dm.getLocations().size()>0){
                            //如果有路径信息
                        }
                    }
                }
                tmpList.add(t);
                if(isNew){//
                    JkCustomer u =new JkCustomer();
                    u.setId(c.getId());
                    u.setDistance(JSONObject.toJSONString(tmpList));
                }
            }
            c.setDistanceMapParamList(tmpList);
        }
        if(updateCustomerList.size()>0){
            for(JkCustomer c : updateCustomerList){
                jkCustomerMapper.updateById(c);//更新客户与其他点之间的距离
            }
        }
    }
    private DistanceMapParam getParamByCustomerIds(  Integer id1, List<DistanceMapParam> distanceMapParamList) {
        if(distanceMapParamList!=null){
            for(DistanceMapParam p :distanceMapParamList){
                if(Constants.equalsInteger(p.getId(),id1)){
                    return p;
                }
            }
        }
        return null;
    }
    private List<DistanceMapParam> getListFromJsonStr(String distanceJson) {
        try {
            return  JSONObject.parseObject(distanceJson, new TypeReference<List<DistanceMapParam>>(){}.getType());
        }catch (Exception e){
        }
        return new ArrayList<>();
    }
    private void dealSearchSolution(JkSketch model, TspSolver.DataModel dataModel) {
        Date date = new Date();
        List<TspSolverSolutions> solutions = dataModel.getSolutions();
        List<JkSketchLine> sketchLineList = new ArrayList<>();
        List<JkSketchCustomer> sketchCustomerList  = new ArrayList<>();
        long totalDistance = 0l;
        if(solutions!=null && solutions.size()>0){
            for(TspSolverSolutions so : solutions){
                List<Integer> routes = so.getRouteIndex();
                if(routes.size() <=2) {
                    continue;//无客户的非有效路线
                }
                totalDistance+= so.getDistance();
                JkLine  line =model.getLineList().get(so.getLineIndex());
                JkSketchLine tModel =  new JkSketchLine();
                tModel.setSketchId(model.getId());
                tModel.setCreator(model.getEditor());
                tModel.setCreateDate(date);
                tModel.setLineId(line.getId());
                tModel.setTotalNum(new BigDecimal(0));
                tModel.setOrderNum(routes.size()-2);
                tModel.setDateInfo(model.getDateInfo());
                tModel.setSortnum(sketchLineList.size()+1);
                tModel.setEditDate(tModel.getCreateDate());
                tModel.setEditor(tModel.getCreator());
                tModel.setIsdeleted(Constants.ZERO);
                tModel.setDistance(so.getDistance());//
                sketchLineList.add(tModel);
                tModel.setCustomerList( new ArrayList<>());
                //有效路径
                for (Integer cIndex : routes){
                    if(cIndex ==0 || cIndex == routes.size()-1){
                        continue; //起始点不处理
                    }
                    JkSketchCustomer customer = model.getCustomerList().get(cIndex-1);
                    tModel.setTotalNum(tModel.getTotalNum().add(Constants.formatBigdecimal(customer.getTotalNum())));//送货量
                    JkSketchCustomer cModel =  new JkSketchCustomer();
                    cModel.setCreator(tModel.getCreator());
                    cModel.setOrderId(customer.getOrderId());
                    cModel.setCreateDate(tModel.getCreateDate());
                    cModel.setTotalNum(customer.getTotalNum());
                    cModel.setDateInfo(model.getDateInfo());
                    cModel.setSortnum(tModel.getCustomerList().size()+1);
                    cModel.setEditDate(tModel.getCreateDate());
                    cModel.setEditor(tModel.getCreator());
                    cModel.setIsdeleted(Constants.ZERO);
                    cModel.setSketchId(model.getId());
                    cModel.setCustomerId(customer.getCustomerId());
                    tModel.getCustomerList().add(cModel);
                    if(cIndex ==0 || cIndex == routes.size()-1){
                        continue; //起始点不处理
                    }
                }
            }
        }
        if(sketchLineList!=null && sketchLineList.size()>0){
            jkSketchLineMapper.update(null,new UpdateWrapper<JkSketchLine>().lambda()
                    .set(JkSketchLine::getIsdeleted,Constants.ONE)
                    .eq(JkSketchLine::getIsdeleted,Constants.ZERO)
                    .eq(JkSketchLine::getDateInfo,model.getDateInfo()));
            jkSketchCustomerMapper.update(null,new UpdateWrapper<JkSketchCustomer>().lambda()
                    .set(JkSketchCustomer::getIsdeleted,Constants.ONE)
                    .eq(JkSketchCustomer::getIsdeleted,Constants.ZERO)
                    .eq(JkSketchCustomer::getDateInfo,model.getDateInfo()));
            if(sketchLineList.size()>0){
                jkSketchLineMapper.insert(sketchLineList);
            }
            for(JkSketchLine l : sketchLineList){
                if(l.getCustomerList()!=null ){
                    for(JkSketchCustomer c :l.getCustomerList()){
                        c.setSketchLineId(l.getId());
                    }
                    sketchCustomerList.addAll(l.getCustomerList());
                }
            }
            if(sketchCustomerList.size()>0){
                jkSketchCustomerMapper.insert(sketchCustomerList);
            }
            jkSketchMapper.update(null,new UpdateWrapper<JkSketch>().lambda()
                    .eq(JkSketch::getId,model.getId() )
                    .eq(JkSketch::getJobId,model.getJobId() )
                    .set(JkSketch::getLineNum,sketchLineList.size() )
                    .set(JkSketch::getDistance,totalDistance)
                    .set(JkSketch::getPlanLineInfo,"最近一次线路优化成功,优化后总距离:"+(totalDistance/1000)+"公里!")
                    .set(JkSketch::getStatus,Constants.TWO)
                    .set(JkSketch::getPlanLineEndDate,date));
        }else{
            jkSketchMapper.update(null,new UpdateWrapper<JkSketch>().lambda()
                    .eq(JkSketch::getId,model.getId() )
                    .eq(JkSketch::getJobId,model.getJobId() )
                    .set(JkSketch::getPlanLineInfo,"最近一次线路优化失败,未找到最优路线!")
                    .set(JkSketch::getStatus,Constants.THREE)
                    .set(JkSketch::getPlanLineEndDate,date));
        }
    }
    private   List<JkSketchCustomer>  checkJketchCustomerLocation(JkSketch model) {
        MPJLambdaWrapper<JkSketchCustomer> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(JkSketchCustomer.class )
                .selectAs(JkCustomer::getName,JkSketchCustomer::getName)
                .selectAs(JkCustomer::getCode,JkSketchCustomer::getCode)
                .selectAs(JkCustomer::getDistance,JkSketchCustomer::getDistanceJson)
                .selectAs(JkCustomer::getLongitude,JkSketchCustomer::getLongitude)
                .selectAs(JkCustomer::getLatitude,JkSketchCustomer::getLatitude)
                .leftJoin(JkCustomer.class,JkCustomer::getId,JkSketchCustomer::getCustomerId )
                .eq(JkSketchCustomer::getSketchId, model.getId())
                .eq(JkSketchCustomer::getIsdeleted,Constants.ZERO)
                .orderByAsc(JkSketchCustomer::getSortnum);
        List<JkSketchCustomer> customerList = jkSketchCustomerMapper.selectJoinList(JkSketchCustomer.class,queryWrapper);
        if(customerList == null ||customerList.size() ==0){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"该线路客户信息为空,不满足优化条件!");
        }
        String errorMsg ="";
        for(JkSketchCustomer c : customerList){
            if(c.getLatitude()==null || c.getLongitude() ==null){
                errorMsg += c.getName()+"-"+c.getName()+";";
            }
        }
        if(StringUtils.isNotBlank(errorMsg)){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"该线路客户:"+errorMsg+"定位信息不完整,不满足优化条件!");
        }
       /* for(JkSketchCustomer c : customerList){
            List<Map<String,Object>> tmpList = new ArrayList<>();
            for(JkSketchCustomer cm : customerList){
                Map<String,Object> t = new HashMap<>();
                t.put("a",cm.getId());
                if(Constants.equalsInteger(c.getCustomerId(),cm.getCustomerId())){
                    t.put("b",0l);
                }else{
                    t.put("b", DistanceCalculator.calculateDistance(
                            Constants.formatBigdecimal(c.getLatitude()).doubleValue(),
                            Constants.formatBigdecimal(c.getLongitude()).doubleValue(),
                            Constants.formatBigdecimal(cm.getLatitude()).doubleValue(),
                            Constants.formatBigdecimal(cm.getLongitude()).doubleValue()));
                }
                tmpList.add(t);
            }
            c.setDistanceList(tmpList);
        }
        */
        /*if(Constants.equalsInteger(Constants.ZERO,model.getStatus())){
            //如果是未优化状态,计算原始距离
            long totalDistance = 0;
            MPJLambdaWrapper<JkSketchLine> queryWrapper1 = new MPJLambdaWrapper<>();
            queryWrapper1.selectAll(JkSketchLine.class )
                    .eq(JkSketchLine::getSketchId, model.getId())
                    .eq(JkSketchLine::getIsdeleted,Constants.ZERO);
            List<JkSketchLine> lineList = jkSketchLineMapper.selectJoinList(JkSketchLine.class,queryWrapper1);//
            if(lineList!=null ||lineList.size()>0){
                double cLatitude =0;
                double cLongitude =0;
                String location = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.COMPANY_LOCATION).getCode();
                try {
                    String[] ss = location.split(",");
                    cLongitude = Double.parseDouble(ss[0]);
                    cLatitude = Double.parseDouble(ss[1]);
                }catch (Exception e){
                }
                for(JkSketchLine line : lineList){
                    boolean isFirst =true;
                    JkSketchCustomer last = null;
                    for(JkSketchCustomer c : customerList){
                        if(Constants.equalsInteger(c.getSketchLineId(),line.getId())){
                            if(isFirst){
                                totalDistance += DistanceCalculator.calculateDistance(cLatitude,cLongitude
                                        ,Constants.formatBigdecimal(c.getLatitude()).doubleValue()
                                        ,Constants.formatBigdecimal(c.getLongitude()).doubleValue());
                            }else{
                                totalDistance += DistanceCalculator.calculateDistance(
                                         Constants.formatBigdecimal(c.getLatitude()).doubleValue()
                                        ,Constants.formatBigdecimal(c.getLongitude()).doubleValue()
                                        ,Constants.formatBigdecimal(last.getLatitude()).doubleValue()
                                        ,Constants.formatBigdecimal(last.getLongitude()).doubleValue());
                            }
                            last = c;
                            isFirst=false;
                        }
                        if(last!=null){
                            totalDistance += DistanceCalculator.calculateDistance(cLatitude,cLongitude
                                    ,Constants.formatBigdecimal(last.getLatitude()).doubleValue()
                                    ,Constants.formatBigdecimal(last.getLongitude()).doubleValue());
                        }
                    }
                }
            }
            model.setOriginDistance(totalDistance);
        }*/
        return customerList;
    }
    @Override
@@ -87,61 +480,62 @@
    @Override
    public PageData<JkSketch> findPage(PageWrap<JkSketch> pageWrap) {
        IPage<JkSketch> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        QueryWrapper<JkSketch> queryWrapper = new QueryWrapper<>();
        MPJLambdaWrapper<JkSketch> queryWrapper = new MPJLambdaWrapper<>();
        Utils.MP.blankToNull(pageWrap.getModel());
        pageWrap.getModel().setIsdeleted(Constants.ZERO);
        queryWrapper.selectAll(JkSketch.class )
                .selectAs(Category::getId,JkSketch::getCategoryId)
                .selectAs(Category::getName,JkSketch::getCategoryName)
                .leftJoin(Category.class,Category::getId,JkSketch::getCategoryId );
        queryWrapper.eq( pageWrap.getModel().getCategoryId()!=null,JkLine::getCategoryId, pageWrap.getModel().getCategoryId());
        if (pageWrap.getModel().getId() != null) {
            queryWrapper.lambda().eq(JkSketch::getId, pageWrap.getModel().getId());
            queryWrapper.eq(JkSketch::getId, pageWrap.getModel().getId());
        }
        if (pageWrap.getModel().getCreator() != null) {
            queryWrapper.lambda().eq(JkSketch::getCreator, pageWrap.getModel().getCreator());
            queryWrapper.eq(JkSketch::getCreator, pageWrap.getModel().getCreator());
        }
        if (pageWrap.getModel().getCreateDate() != null) {
            queryWrapper.lambda().ge(JkSketch::getCreateDate, Utils.Date.getStart(pageWrap.getModel().getCreateDate()));
            queryWrapper.lambda().le(JkSketch::getCreateDate, Utils.Date.getEnd(pageWrap.getModel().getCreateDate()));
            queryWrapper.ge(JkSketch::getCreateDate, Utils.Date.getStart(pageWrap.getModel().getCreateDate()));
            queryWrapper.le(JkSketch::getCreateDate, Utils.Date.getEnd(pageWrap.getModel().getCreateDate()));
        }
        if (pageWrap.getModel().getEditor() != null) {
            queryWrapper.lambda().eq(JkSketch::getEditor, pageWrap.getModel().getEditor());
            queryWrapper.eq(JkSketch::getEditor, pageWrap.getModel().getEditor());
        }
        if (pageWrap.getModel().getEditDate() != null) {
            queryWrapper.lambda().ge(JkSketch::getEditDate, Utils.Date.getStart(pageWrap.getModel().getEditDate()));
            queryWrapper.lambda().le(JkSketch::getEditDate, Utils.Date.getEnd(pageWrap.getModel().getEditDate()));
            queryWrapper.ge(JkSketch::getEditDate, Utils.Date.getStart(pageWrap.getModel().getEditDate()));
            queryWrapper.le(JkSketch::getEditDate, Utils.Date.getEnd(pageWrap.getModel().getEditDate()));
        }
        if (pageWrap.getModel().getIsdeleted() != null) {
            queryWrapper.lambda().eq(JkSketch::getIsdeleted, pageWrap.getModel().getIsdeleted());
            queryWrapper.eq(JkSketch::getIsdeleted, pageWrap.getModel().getIsdeleted());
        }
        if (pageWrap.getModel().getInfo() != null) {
            queryWrapper.lambda().eq(JkSketch::getInfo, pageWrap.getModel().getInfo());
            queryWrapper.eq(JkSketch::getInfo, pageWrap.getModel().getInfo());
        }
        if (pageWrap.getModel().getCategoryId() != null) {
            queryWrapper.lambda().eq(JkSketch::getCategoryId, pageWrap.getModel().getCategoryId());
            queryWrapper.eq(JkSketch::getCategoryId, pageWrap.getModel().getCategoryId());
        }
        if (pageWrap.getModel().getTotalNum() != null) {
            queryWrapper.lambda().eq(JkSketch::getTotalNum, pageWrap.getModel().getTotalNum());
            queryWrapper.eq(JkSketch::getTotalNum, pageWrap.getModel().getTotalNum());
        }
        if (pageWrap.getModel().getOrderNum() != null) {
            queryWrapper.lambda().eq(JkSketch::getOrderNum, pageWrap.getModel().getOrderNum());
            queryWrapper.eq(JkSketch::getOrderNum, pageWrap.getModel().getOrderNum());
        }
        if (pageWrap.getModel().getStatus() != null) {
            queryWrapper.lambda().eq(JkSketch::getStatus, pageWrap.getModel().getStatus());
            queryWrapper.eq(JkSketch::getStatus, pageWrap.getModel().getStatus());
        }
        if (pageWrap.getModel().getSortnum() != null) {
            queryWrapper.lambda().eq(JkSketch::getSortnum, pageWrap.getModel().getSortnum());
            queryWrapper.eq(JkSketch::getSortnum, pageWrap.getModel().getSortnum());
        }
        if (pageWrap.getModel().getDateInfo() != null) {
            queryWrapper.lambda().ge(JkSketch::getDateInfo, Utils.Date.getStart(pageWrap.getModel().getDateInfo()));
            queryWrapper.lambda().le(JkSketch::getDateInfo, Utils.Date.getEnd(pageWrap.getModel().getDateInfo()));
            queryWrapper.eq(JkSketch::getDateInfo,  pageWrap.getModel().getDateInfo());
        }
        if (pageWrap.getModel().getJobId() != null) {
            queryWrapper.lambda().eq(JkSketch::getJobId, pageWrap.getModel().getJobId());
            queryWrapper.eq(JkSketch::getJobId, pageWrap.getModel().getJobId());
        }
        for(PageWrap.SortData sortData: pageWrap.getSorts()) {
            if (sortData.getDirection().equalsIgnoreCase(PageWrap.DESC)) {
                queryWrapper.orderByDesc(sortData.getProperty());
            } else {
                queryWrapper.orderByAsc(sortData.getProperty());
            }
        }
        return PageData.from(jkSketchMapper.selectPage(page, queryWrapper));
        queryWrapper.orderByDesc(JkSketch::getDateInfo);
        IPage<JkSketch> result = jkSketchMapper.selectJoinPage(page, JkSketch.class,queryWrapper);
        return PageData.from(result);
    }
    @Override
@@ -149,4 +543,342 @@
        QueryWrapper<JkSketch> wrapper = new QueryWrapper<>(jkSketch);
        return jkSketchMapper.selectCount(wrapper);
    }
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public List<JkSketch> importBatch(MultipartFile file, String dateInfoStr, LoginUserInfo loginUser){
        if(StringUtils.isBlank(dateInfoStr)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请选择送货日期!");
        }
        Date dateInfo = DateUtil.getDateFromShortString(dateInfoStr);
        if(dateInfo == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请选择正确的送货日期!");
        }
        Boolean importing = (Boolean) redisTemplate.opsForValue().get(Constants.RedisKeys.IMPORTING_JKORDERS);
        if(importing!=null && importing){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,已存在导入任务正在执行中,请稍后再试!");
        }
        redisTemplate.opsForValue().set(Constants.RedisKeys.IMPORTING_JKORDERS,true,30, TimeUnit.MINUTES);
        try {
            ExcelImporter ie = null;
            List<JkOrdersImport> dataList =null;
            try {
                ie = new ExcelImporter(file,1,0);
                dataList = ie.getDataList(JkOrdersImport.class,null);
            }  catch (Exception e) {
                e.printStackTrace();
            }
            if(dataList == null || dataList.size() ==0){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,录入数据为空!");
            }
            List<JkCustomer> customerList =  jkCustomerMapper.selectJoinList(JkCustomer.class,new MPJLambdaWrapper<JkCustomer>()
                    .selectAll(JkCustomer.class)
                    .eq(JkCustomer::getIsdeleted,Constants.ZERO)
            );
            String week =  DateUtil.getWeekZhouOfDate(dateInfo);
            //当前所有线路
            List<JkLine> lineList =  jkLineMapper.selectJoinList(JkLine.class,new MPJLambdaWrapper<JkLine>()
                    .selectAll(JkLine.class)
                    .eq(JkLine::getWeeks,week)//只能选择当前的线路
                    .eq(JkLine::getIsdeleted,Constants.ZERO)
            );
            List<JkOrders> newOrderList = new ArrayList<>();
            for(int i=0;i<dataList.size();i++){
                JkOrdersImport model = dataList.get(i);
                if(StringUtils.isBlank(model.getName())
                        &&StringUtils.isBlank(model.getCode())
                        &&StringUtils.isBlank(model.getNum())
                        &&StringUtils.isBlank(model.getSortnum())
                        &&StringUtils.isBlank(model.getDateInfo())
                        &&StringUtils.isBlank(model.getLineName()) ){
                    continue;
                }
                checkModelParam(model, newOrderList, i,dateInfo,loginUser,customerList,lineList );
            }
            if( newOrderList.size()==0){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,录入有效数据为空!");
            }
            List<JkSketch> newList = initNewSketchList(newOrderList);//按照主线路分组
            if(  newList.size() ==0 ){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,录入有效数据为空!");
            }
            jkSketchMapper.update(null,new UpdateWrapper<JkSketch>().lambda()
                    .set(JkSketch::getIsdeleted,Constants.ONE)
                    .eq(JkSketch::getIsdeleted,Constants.ZERO)
                    .eq(JkSketch::getDateInfo,dateInfo));
            jkOrdersMapper.update(null,new UpdateWrapper<JkOrders>().lambda()
                    .set(JkOrders::getIsdeleted,Constants.ONE)
                    .eq(JkOrders::getIsdeleted,Constants.ZERO)
                    .eq(JkOrders::getDateInfo,dateInfo));
            if(newList.size()>0){
                jkSketchMapper.insert(newList);
            }
            if(newOrderList.size()>0){
                jkOrdersMapper.insert(newOrderList);
            }
            List<JkSketchLine> sketchLineList = initNewSketchLineList(newList,newOrderList,lineList);
            jkSketchLineMapper.update(null,new UpdateWrapper<JkSketchLine>().lambda()
                    .set(JkSketchLine::getIsdeleted,Constants.ONE)
                    .eq(JkSketchLine::getIsdeleted,Constants.ZERO)
                    .eq(JkSketchLine::getDateInfo,dateInfo));
            if(sketchLineList.size()>0){
                jkSketchLineMapper.insert(sketchLineList);
            }
            List<JkSketchCustomer> sketchCuustomerList = initNewSketchCustomerList(sketchLineList,newOrderList);//按照主线路分组
            jkSketchCustomerMapper.update(null,new UpdateWrapper<JkSketchCustomer>().lambda()
                    .set(JkSketchCustomer::getIsdeleted,Constants.ONE)
                    .eq(JkSketchCustomer::getIsdeleted,Constants.ZERO)
                    .eq(JkSketchCustomer::getDateInfo,dateInfo));
            if(sketchCuustomerList.size()>0){
                jkSketchCustomerMapper.insert(sketchCuustomerList);
            }
            return newList;
        }catch (BusinessException e){
            throw e;
        }catch (Exception e){
            e.printStackTrace();
            throw  new BusinessException(ResponseStatus.SERVER_ERROR.getCode(),"信息导入失败,请稍后重试");
        }finally {
            redisTemplate.delete(Constants.RedisKeys.IMPORTING_JKORDERS);
        }
    }
    private List<JkSketchCustomer> initNewSketchCustomerList(List<JkSketchLine> sketchLineList, List<JkOrders> newOrderList) {
        List<JkSketchCustomer> list =new ArrayList<>();
        for(JkOrders orders : newOrderList){
            JkSketchLine line = findModelFromListByLineId(orders.getLineId(),sketchLineList);
            if( line!=null){
                JkSketchCustomer tModel =  new JkSketchCustomer();
                tModel.setCreator(orders.getCreator());
                tModel.setOrderId(orders.getId());
                tModel.setCreateDate(orders.getCreateDate());
                tModel.setTotalNum(orders.getNum());
                tModel.setDateInfo(orders.getDateInfo());
                tModel.setSortnum(list.size()+1);
                tModel.setEditDate(tModel.getCreateDate());
                tModel.setEditor(tModel.getCreator());
                tModel.setIsdeleted(Constants.ZERO);
                tModel.setSketchId(line.getSketchId());
                tModel.setCustomerId(orders.getCustomerId());
                tModel.setSketchLineId(line.getId());
                list.add(tModel);
            }
        }
        return list;
    }
    private List<JkSketchLine> initNewSketchLineList(List<JkSketch> newList, List<JkOrders> newOrderList,List<JkLine> lineList) {
        List<JkSketchLine> list =new ArrayList<>();
        for (JkLine line : lineList){
            JkSketchLine tModel =  new JkSketchLine();
            tModel.setSketchId(getSKetchIdByyCategoryId(line.getCategoryId(),newList));
            tModel.setCreator(newList.get(0).getCreator());
            tModel.setCreateDate(newList.get(0).getCreateDate());
            tModel.setLineId(line.getId());
            initOrderAndTotalNum(tModel,line.getId(),newOrderList);
            tModel.setDateInfo(newList.get(0).getDateInfo());
            tModel.setSortnum(list.size()+1);
            tModel.setEditDate(tModel.getCreateDate());
            tModel.setEditor(tModel.getCreator());
            tModel.setIsdeleted(Constants.ZERO);
            if(tModel.getSketchId()!=null && Constants.formatIntegerNum(tModel.getOrderNum()) >0){
                list.add(tModel);
            }
        }
        /*for(JkOrders orders : newOrderList){
            JkSketchLine tModel = findModelFromListByLineId(orders.getLineId(),list);
            if(tModel!=null){
                tModel.setTotalNum(  tModel.getTotalNum().add(orders.getNum()));//订单量累计
                tModel.setOrderNum(tModel.getOrderNum()+1);//客户数加1
            }else{
                tModel = new JkSketchLine();
                tModel.setSketchId(getSKetchIdByyCategoryId(orders.getCategoryId(),newList));
                tModel.setCreator(orders.getCreator());
                tModel.setCreateDate(orders.getCreateDate());
                tModel.setLineId(orders.getLineId());
                tModel.setTotalNum(orders.getNum());
                tModel.setOrderNum(1);
                tModel.setDateInfo(orders.getDateInfo());
                tModel.setSortnum(list.size()+1);
                tModel.setEditDate(tModel.getCreateDate());
                tModel.setEditor(tModel.getCreator());
                tModel.setIsdeleted(Constants.ZERO);
                if(tModel.getSketchId()!=null){
                    list.add(tModel);
                }
            }
        }*/
        return list;
    }
    private void initOrderAndTotalNum(JkSketchLine tModel, Integer id, List<JkOrders> newOrderList) {
        for(JkOrders orders : newOrderList){
            if(Constants.equalsInteger(orders.getLineId(),id)){
                tModel.setOrderNum(Constants.formatIntegerNum(tModel.getOrderNum())+1);
                tModel.setTotalNum(Constants.formatBigdecimal(tModel.getTotalNum()).add(Constants.formatBigdecimal(orders.getNum())));
            }
        }
    }
    private Integer getSKetchIdByyCategoryId(Integer categoryId, List<JkSketch> newList) {
        for(JkSketch model:newList){
            if(Constants.equalsInteger(model.getCategoryId(),categoryId)){
                return model.getId();
            }
        }
        return null;
    }
    private JkSketchLine findModelFromListByLineId(Integer lineId, List<JkSketchLine> list) {
        if(list !=null){
            for(JkSketchLine model : list){
                if(Constants.equalsInteger(lineId,model.getLineId())){
                    return  model;
                }
            }
        }
        return null;
    }
    private   List<JkSketch>  initNewSketchList(List<JkOrders> newOrderList) {
        List<JkSketch> list =new ArrayList<>();
        for(JkOrders orders : newOrderList){
            JkSketch tModel = findModelFromListByCateId(orders.getCategoryId(),list);
            if(tModel!=null){
                tModel.setTotalNum(  tModel.getTotalNum().add(orders.getNum()));//订单量累计
                tModel.setOrderNum(tModel.getOrderNum()+1);//客户数加1
            }else{
                tModel = new JkSketch();
                tModel.setLineNum(getLineNumByOrders(orders.getCategoryId(),newOrderList));
                tModel.setPlanLineNum(tModel.getLineNum());
                tModel.setCreator(orders.getCreator());
                tModel.setCreateDate(orders.getCreateDate());
                tModel.setCategoryId(orders.getCategoryId());
                tModel.setTotalNum(orders.getNum());
                tModel.setOrderNum(1);
                tModel.setDateInfo(orders.getDateInfo());
                tModel.setSortnum(list.size()+1);
                tModel.setEditDate(tModel.getCreateDate());
                tModel.setEditor(tModel.getCreator());
                tModel.setStatus(Constants.ZERO);
                tModel.setIsdeleted(Constants.ZERO);
                list.add(tModel);
            }
        }
        return list;
    }
    private Integer getLineNumByOrders(Integer cateId, List<JkOrders> newOrderList) {
        List<JkSketchLine> list =new ArrayList<>();
        for(JkOrders orders : newOrderList){
            if(!Constants.equalsInteger(orders.getCategoryId(),cateId)){
                continue;
            }
            JkSketchLine tModel = findModelFromListByLineId(orders.getLineId(),list);
            if(tModel ==null){
                tModel = new JkSketchLine();
                tModel.setLineId(orders.getLineId());
                list.add(tModel);
            }
        }
        return list.size();
    }
    private JkOrders checkModelParam(JkOrdersImport model
            , List<JkOrders> newOrderList
            ,int index
            ,Date dateInfo
            ,LoginUserInfo loginUserInfo
            ,List<JkCustomer> allList
            ,List<JkLine> lineList ) {
        if(StringUtils.isBlank(model.getName())
                ||StringUtils.isBlank(model.getCode())
                ||StringUtils.isBlank(model.getName())
                ||StringUtils.isBlank(model.getLineName()) ){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第"+(index+3)+"行客户信息不完整,请检查表格内容!");
        }
        for(JkOrders param: newOrderList){
            if(StringUtils.isNotBlank(model.getCode())&&StringUtils.isNotBlank(param.getCode())) {
                if (StringUtils.equals(model.getCode(), param.getCode())) {
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,第" + (index + 3) + "行客户简码【" + model.getName() + "】重复出现,请检查表格内容!");
                }
            }
        }
        JkCustomer customer = findModelFromList(model.getCode(),allList);
        if(customer == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,第" + (index + 3) + "行客户编码【" + model.getCode() + "】不存在,请检查表格内容!");
        }
        if(!StringUtils.equals(customer.getName(),model.getName())){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,第" + (index + 3) + "行客户名称【" + model.getName() + "】和编码不匹配,请检查表格内容!");
        }
        JkLine line = findLineFromListByName(model.getLineName(),lineList);
        if(line == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,第" + (index + 3) + "行线路【" + model.getLineName() + "】不存在或者配送周期不符合,请检查表格内容!");
        }
        JkOrders tModel =   new JkOrders();
        tModel.setCreator(loginUserInfo.getId());
        tModel.setCreateDate(new Date());
        tModel.setName(model.getName());
        tModel.setCode(model.getCode());
        tModel.setNum(getDecimalByVal(model.getNum()));
        tModel.setCustomerId(customer.getId());
        tModel.setDateInfo(dateInfo);
        tModel.setLatitude(customer.getLatitude());
        tModel.setLongitude(customer.getLongitude());
        tModel.setSortnum(model.getSortnum());
        tModel.setLineId(line.getId());
        tModel.setCategoryId(line.getCategoryId());
        tModel.setEditDate(new Date());
        tModel.setEditor(loginUserInfo.getId());
        tModel.setIsdeleted(Constants.ZERO);
        newOrderList.add(tModel);
        return tModel;
    }
    private BigDecimal getDecimalByVal(String val) {
        try {
            return new BigDecimal(val);
        }catch (Exception e){
        }
        return null;
    }
    private JkCustomer findModelFromList(String code, List<JkCustomer> list) {
        if(list !=null){
            for(JkCustomer model : list){
                if(StringUtils.equals(code,model.getCode())){
                    return  model;
                }
            }
        }
        return null;
    }
    private JkSketch findModelFromListByCateId(Integer cateId, List<JkSketch> list) {
        if(list !=null){
            for(JkSketch model : list){
                if(Constants.equalsInteger(cateId,model.getCategoryId())){
                    return  model;
                }
            }
        }
        return null;
    }
    private JkLine findLineFromListByName(String name, List<JkLine> list) {
        if(list !=null){
            for(JkLine model : list){
                if(StringUtils.equals(name,model.getName())){
                    return model;
                }
            }
        }
        return null;
    }
}