package com.steerinfo.meterwork.meterworkrailwayreceived.service.impl;

import cn.hutool.db.handler.HandleHelper;
import com.github.pagehelper.util.StringUtil;
import com.steerinfo.baseinfo.meterbaseoperationlog.mapper.MeterBaseOperationLogMapper;
import com.steerinfo.baseinfo.meterbaseoperationlog.model.MeterBaseOperationLog;
import com.steerinfo.baseinfo.meterbaseoperationlog.service.IMeterBaseOperationLogService;
import com.steerinfo.baseinfo.meterbaserailwayaiweight.mapper.MeterBaseRailwayAiweightMapper;
import com.steerinfo.baseinfo.meterbaserailwayaiweight.model.MeterBaseRailwayAiweight;
import com.steerinfo.baseinfo.meterbasespotinfo.model.MeterBaseSpotInfo;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.service.pagehelper.PageHelper;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.metermonitor.metermonitornote.mapper.MeterMonitorNoteMapper;
import com.steerinfo.metermonitor.metermonitornote.model.MeterMonitorNote;
import com.steerinfo.meterwork.meterworkrailwayactfirst.mapper.MeterWorkRailwayActFirstMapper;
import com.steerinfo.meterwork.meterworkrailwayactfirst.model.MeterWorkRailwayActFirst;
import com.steerinfo.meterwork.meterworkrailwayactual.model.MeterWorkRailwayActual;
import com.steerinfo.meterwork.meterworkrailwayreceived.model.MeterWorkRailwayReceived;
import com.steerinfo.meterwork.meterworkrailwayreceived.mapper.MeterWorkRailwayReceivedMapper;
import com.steerinfo.meterwork.meterworkrailwayreceived.service.IMeterWorkRailwayReceivedService;
import com.steerinfo.meterwork.meterworkrailwayrecmain.mapper.MeterWorkRailwayRecMainMapper;
import com.steerinfo.meterwork.meterworkrailwayrecmain.model.MeterWorkRailwayRecMain;
import com.steerinfo.meterwork.meterworkstorageactual.model.MeterWorkStorageActual;
import com.steerinfo.pretrack.prerailwayscale.mapper.PreRailwayScaleMapper;
import com.steerinfo.pretrack.prerailwayscale.model.PreRailwayScale;
import com.steerinfo.util.PublicMethod;
import com.steerinfo.util.StringUtils;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * MeterWorkRailwayReceived服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2022-03-22 09:00
 * 类描述
 * 修订历史：
 * 日期：2022-03-22
 * 作者：generator
 * 参考：
 * 描述：MeterWorkRailwayReceived服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "meterWorkRailwayReceivedService")
public class MeterWorkRailwayReceivedServiceImpl extends BaseServiceImpl<MeterWorkRailwayReceived, String> implements IMeterWorkRailwayReceivedService {

    @Resource
    private MeterWorkRailwayReceivedMapper meterWorkRailwayReceivedMapper;

    @Resource
    private MeterWorkRailwayRecMainMapper meterWorkRailwayRecMainMapper;

    @Resource
    private MeterWorkRailwayActFirstMapper meterWorkRailwayActFirstMapper;

    @Resource
    private MeterBaseRailwayAiweightMapper meterBaseRailwayAiweightMapper;

    @Resource
    private MeterBaseOperationLogMapper meterBaseOperationLogMapper;

    @Resource
    private PreRailwayScaleMapper preRailwayScaleMapper;

    @Resource
    private IMeterBaseOperationLogService meterBaseOperationLogService;

    @Override
    protected IBaseMapper<MeterWorkRailwayReceived, String> getMapper() {
        return meterWorkRailwayReceivedMapper;
    }

    @Override
    public RESTfulResult checkandadd(MeterWorkRailwayReceived model) throws Exception {
        try{
            RESTfulResult rm = new RESTfulResult();
            rm.setCode("200");
            rm.setData(model.getActualFirstNo());
            if(model.getRailwayNo() == null && StringUtils.isEmpty(model.getRailwayNo())) {
                model.setRailwayNo("车号异常");
            }
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//            String afl = sdf.format(new Date());
//            String no = meterWorkRailwayReceivedMapper.getNewID(afl);
//            model.setActualFirstNo(sdf.format(new Date()) + no);
            meterWorkRailwayReceivedMapper.insertSelective(model);
            rm.setMessage("成功");
            return rm;
        }
        catch (Exception e){
            throw e;
        }
    }

    @Override
    public List<MeterWorkRailwayReceived> noPage(HashMap<String, Object> parmas) {
        List<MeterWorkRailwayReceived> rows = meterWorkRailwayReceivedMapper.noPage(parmas);
        return rows;
    }

    @Override
    @Transactional
    public RESTfulResult updateList(List<MeterWorkRailwayReceived> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            int count = 0;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            for (MeterWorkRailwayReceived model: models) {
                if(model.getMemo() != null && StringUtils.isNotEmpty(model.getMemo())) {
                    MeterWorkRailwayReceived received = meterWorkRailwayReceivedMapper.selectByPrimaryKey(model.getActualFirstNo());
                    MeterBaseOperationLog note = new MeterBaseOperationLog();
                    String no = PublicMethod.IdCreate(3);
                    note.setId(no);
                    note.setOperationId(model.getActualFirstNo());
                    note.setCreateManNo(model.getUpdateManNo());
                    note.setCreateManName(model.getUpdateManName());
                    note.setCreateTime(new Date());
                    note.setOperationPage("终端-轨道衡从表数据维护");
                    if(StringUtils.isEmpty(received.getRailwayNo()) || !received.getRailwayNo().equals(model.getRailwayWorkNo())) {
                        note.setOperationFunction("车号修改");
                    }else {
                        if(received.getMeterWeight() == null || !(received.getMeterWeight().compareTo(model.getMeterWeight()) == 0)) {
                            note.setOperationFunction("Ai标识皮修改");
                        }
                    }

                    note.setOperationBeforeFix(received.toString());
                    note.setOperationAfterFix(model.toString());
                    note.setOperationCarnNo(model.getRailwayNo());
                    meterBaseOperationLogMapper.insertSelective(note);
                    model.setMemo("");
                }

                if(model.getAiWeight() != null && StringUtils.isNotEmpty(model.getAiWeight())) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("railwayNo", model.getRailwayNo());
                        List<MeterBaseRailwayAiweight> AiModels = meterBaseRailwayAiweightMapper.selectByParameters(map);
                    MeterBaseRailwayAiweight AiModel = new MeterBaseRailwayAiweight();
                    if(AiModels.size() >= 1) {
                        AiModel = AiModels.get(0);
                        AiModel.setMeterWeight(new BigDecimal(model.getAiWeight()));
                        AiModel.setRailwayType(model.getRailwayModelName());
                        AiModel.setRailwaySpeed(model.getRailwaySpeed());
                        AiModel.setUpdateManNo(model.getUpdateManNo());
                        AiModel.setUpdateManName(model.getUpdateManName());
                        AiModel.setUpdateTime(new Date());
                        AiModel.setValueFlag("0");
                        meterBaseRailwayAiweightMapper.updateByPrimaryKeySelective(AiModel);
                    }else {
                        MeterBaseRailwayAiweight aiModel = meterBaseRailwayAiweightMapper.selectByPrimaryKey(model.getActualFirstNo());
                        if(aiModel != null) {
                            AiModel = aiModel;
                            AiModel.setRailwayNo(model.getRailwayNo());
                            AiModel.setMeterWeight(new BigDecimal(model.getAiWeight()));
                            AiModel.setRailwayType(model.getRailwayModelName());
                            AiModel.setRailwaySpeed(model.getRailwaySpeed());
                            AiModel.setUpdateManNo(model.getUpdateManNo());
                            AiModel.setUpdateManName(model.getUpdateManName());
                            AiModel.setUpdateTime(new Date());
                            AiModel.setValueFlag("0");
                            meterBaseRailwayAiweightMapper.updateByPrimaryKeySelective(AiModel);
                        }else {
                            AiModel.setActualFirstNo(model.getActualFirstNo());
                            AiModel.setRailwayNo(model.getRailwayNo());
                            AiModel.setMeterWeight(new BigDecimal(model.getAiWeight()));
                            AiModel.setRailwayType(model.getRailwayModelName());
                            AiModel.setRailwayTypeNo("001019002");
                            AiModel.setRailwayTypeName("动态轨道衡");
                            AiModel.setValueFlag("0");
                            AiModel.setCreateManNo(model.getUpdateManNo());
                            AiModel.setCreateManName(model.getUpdateManName());
                            AiModel.setCreateTime(new Date());
                            AiModel.setRailwaySpeed(model.getRailwaySpeed());
                            meterBaseRailwayAiweightMapper.insertSelective(AiModel);
                        }
                    }
                }
                meterWorkRailwayReceivedMapper.updateByPrimaryKeySelective(model);
                count ++;
            }
            //修改主表是否已处理完
            if(models.size() >= 1) {
                MeterWorkRailwayReceived receivedModel = meterWorkRailwayReceivedMapper.selectByPrimaryKey(models.get(0).getActualFirstNo());
                if(receivedModel != null){
                    HashMap<String, Object> obj = new HashMap<>();
                    obj.put("railwayWorkNo", receivedModel.getRailwayWorkNo());
                    HashMap<String, Object> countMap = meterWorkRailwayReceivedMapper.getCount(obj);
                    int countNum = Integer.parseInt(countMap.get("COUNTNUM").toString());
                    if(countNum < 1) {
                        HashMap<String, Object> mainMap = new HashMap<>();
                        mainMap.put("soundName", receivedModel.getRailwayWorkNo());
                        List<MeterWorkRailwayRecMain> mainModel = meterWorkRailwayRecMainMapper.selectByParameters(mainMap);
                        if(mainModel.size() >= 1) {
                            mainModel.get(0).setIsDispose("1");
                            meterWorkRailwayRecMainMapper.updateByPrimaryKeySelective(mainModel.get(0));
                        }
                    }
                }
            }

            rm.setSucceed();
            rm.setMessage("操作成功，共有" + count + "条数据更新成功");
            rm.setCode("200");
            rm.setData(count);
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常");
        }
        return rm;
    }

    @Override
    public RESTfulResult updateListStart(List<MeterWorkRailwayReceived> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            int count = 0;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            for (MeterWorkRailwayReceived model: models) {
//                if(model.getMemo() != null && StringUtils.isNotEmpty(model.getMemo())) {
//                    MeterBaseOperationLog note = new MeterBaseOperationLog();
//                    String no = PublicMethod.IdCreate(3);
//                    note.setId(no);
//                    note.setCreateManNo(model.getCreateManNo());
//                    note.setCreateManName(model.getCreateManName());
//                    note.setCreateTime(new Date());
//                    note.setOperationPage("终端-轨道衡从表数据维护");
//                    note.setOperationFunction("修改");
//                    note.setOperationCarnNo(model.getRailwayNo());
//                    meterBaseOperationLogMapper.insertSelective(note);
//                    model.setMemo("");
//                }

//                if(model.getAiWeight() != null && StringUtils.isNotEmpty(model.getAiWeight())) {
//                    HashMap<String, Object> map = new HashMap<>();
//                    map.put("railwayNo", model.getRailwayNo());
//                    List<MeterBaseRailwayAiweight> AiModels = meterBaseRailwayAiweightMapper.selectByParameters(map);
//                    MeterBaseRailwayAiweight AiModel = new MeterBaseRailwayAiweight();
//                    if(AiModels.size() >= 1) {
//                        AiModel = AiModels.get(0);
//                        AiModel.setMeterWeight(new BigDecimal(model.getAiWeight()));
//                        AiModel.setRailwayType(model.getRailwayModelName());
//                        AiModel.setRailwaySpeed(model.getRailwaySpeed());
//                        AiModel.setUpdateManNo("systemAdd");
//                        AiModel.setUpdateManName("systemAdd");
//                        AiModel.setUpdateTime(new Date());
//                        AiModel.setValueFlag("1");
//                        meterBaseRailwayAiweightMapper.updateByPrimaryKeySelective(AiModel);
//                    }else {
//                        AiModel.setActualFirstNo(model.getActualFirstNo());
//                        AiModel.setRailwayNo(model.getRailwayNo());
//                        AiModel.setMeterWeight(new BigDecimal(model.getAiWeight()));
//                        AiModel.setRailwayType(model.getRailwayModelName());
//                        AiModel.setRailwayTypeNo("001019002");
//                        AiModel.setRailwayTypeName("动态轨道衡");
//                        AiModel.setValueFlag("1");
//                        AiModel.setCreateManNo("systemAdd");
//                        AiModel.setCreateManName("systemAdd");
//                        AiModel.setCreateTime(new Date());
//                        AiModel.setRailwaySpeed(model.getRailwaySpeed());
//                        meterBaseRailwayAiweightMapper.insertSelective(AiModel);
//                    }
//                }
//                meterWorkRailwayReceivedMapper.deleteByPrimaryKey(model.getActualFirstNo());
//                rm.setData(model.getActualFirstNo());
//                if(model.getRailwayNo() == null && StringUtils.isEmpty(model.getRailwayNo())) {
//                    model.setRailwayNo("车号异常");
//                }
////            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
////            String afl = sdf.format(new Date());
////            String no = meterWorkRailwayReceivedMapper.getNewID(afl);
////            model.setActualFirstNo(sdf.format(new Date()) + no);
//                meterWorkRailwayReceivedMapper.insertSelective(model);
                model.setValueFlag("1");
                meterWorkRailwayReceivedMapper.updateByPrimaryKeySelective(model);
                count ++;
            }

            //修改主表是否已处理完
            if(models.size() >= 1) {
                MeterWorkRailwayReceived receivedModel = meterWorkRailwayReceivedMapper.selectByPrimaryKey(models.get(0).getActualFirstNo());
                if(receivedModel != null){
                    HashMap<String, Object> mainMap = new HashMap<>();
                    mainMap.put("soundName", receivedModel.getRailwayWorkNo());
                    List<MeterWorkRailwayRecMain> mainModel = meterWorkRailwayRecMainMapper.selectByParameters(mainMap);
                    if(mainModel.size() >= 1) {
                        mainModel.get(0).setIsDispose("0");
                        meterWorkRailwayRecMainMapper.updateByPrimaryKeySelective(mainModel.get(0));
                    }
                }
            }
            rm.setMessage("操作成功，共有" + count + "条数据更新成功");
            rm.setCode("200");
            rm.setData(count);
            rm.setSucceed(true);
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常");
        }
        return rm;
    }

    @Override
    public RESTfulResult addList(List<MeterWorkRailwayReceived> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            Assert.isTrue(models.size() >= 1, "未勾选数据新增");
            int count = 0;
            List<String> spotList = models
                    .stream()
                    .map(MeterWorkRailwayReceived::getBaseSpotNo)
                    .distinct()
                    .collect(Collectors.toList());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            List<HashMap> map = new ArrayList<>();
            for(String spot: spotList) {
                Long spotCount = models.stream().filter(item -> StringUtils.isNotEmpty(item.getBaseSpotNo()) && item.getBaseSpotNo().equals(spot)).count();
                String afl = sdf.format(new Date());
                String lcNo = meterWorkRailwayRecMainMapper.getLcNo(afl, spot);
                List<MeterWorkRailwayReceived> spotModel = models.stream().filter(item ->  StringUtils.isNotEmpty(item.getBaseSpotNo()) && item.getBaseSpotNo().equals(spot)).collect(Collectors.toList());
                HashMap<String, Object> obj = new HashMap<>();
                obj.put("spotNo", spot);
                obj.put("spotName", spotModel.get(0).getBaseSpotName());
                obj.put("size", spotCount);
                obj.put("lcNo", "-" + afl + lcNo + "(" + spotCount + ")");
                map.add(obj);
            }

            if (spotList.size() >= 1) {
                List<MeterWorkRailwayReceived> receiveds = new ArrayList<>();
                for(MeterWorkRailwayReceived receivedTemp: models){
                    if(receivedTemp.getRailwayWorkNo() != null && StringUtils.isNotEmpty(receivedTemp.getRailwayWorkNo())) {
                        HashMap<String, Object> objMap = new HashMap();
                        objMap.put("soundName", receivedTemp.getRailwayWorkNo());
                        List<MeterWorkRailwayRecMain> recMainTemp = meterWorkRailwayRecMainMapper.selectByParameters(objMap);
                        if(recMainTemp.size() < 1) {
                            rm.setMessage("未找到" + receivedTemp.getRailwayWorkNo()  + "列次号信息");
                            return rm;
                        }
                        recMainTemp.get(0).setIsDispose("0");
                        recMainTemp.get(0).setCarriageNum((short)(receiveds.size() + 1));
                        meterWorkRailwayRecMainMapper.updateByPrimaryKeySelective(recMainTemp.get(0));

//                        if(receivedTemp.getMemo() != null && StringUtils.isNotEmpty(receivedTemp.getMemo())) {
                            MeterBaseOperationLog note = new MeterBaseOperationLog();
                            note.setId(PublicMethod.IdCreate(3));
                            note.setCreateManNo(receivedTemp.getCreateManNo());
                            note.setCreateManName(receivedTemp.getCreateManName());
                            note.setCreateTime(new Date());
                            note.setOperationPage("终端-轨道衡从表数据维护");
                            note.setOperationFunction("新增");
                            note.setOperationId(receivedTemp.getActualFirstNo());
                            note.setOperationCarnNo(receivedTemp.getRailwayNo());
                            meterBaseOperationLogMapper.insertSelective(note);
//                        }
                        receivedTemp.setRailwayWorkNo(recMainTemp.get(0).getActualNo());
                        receivedTemp.setActualFirstNo(PublicMethod.IdCreate(3));
                        receivedTemp.setValueFlag("1");
                        receivedTemp.setRailwayTypeNo(receivedTemp.getRailwayModelNo());
                        receivedTemp.setRailwayTypeName(receivedTemp.getRailwayModelName());
                        meterWorkRailwayReceivedMapper.insertSelective(receivedTemp);
                        count ++;
                    }else {
//                        if(spotNo.equals(receivedTemp.getBaseSpotNo())){
                            for(HashMap temp: map) {
                                if(temp.get("spotNo").equals(receivedTemp.getBaseSpotNo())) {
                                    receivedTemp.setRailwayWorkNo(receivedTemp.getBaseSpotName().replaceAll("#", "")
                                            .replaceAll("轨道衡", "")
                                            .replaceAll("动轨", "")
                                            .replaceAll("动态", "") + temp.get("lcNo").toString());
                                }
                            }
                            MeterBaseOperationLog note = new MeterBaseOperationLog();
                            note.setId(PublicMethod.IdCreate(3));
                            note.setCreateManNo(receivedTemp.getCreateManNo());
                            note.setCreateManName(receivedTemp.getCreateManName());
                            note.setCreateTime(new Date());
                            note.setOperationPage("终端-轨道衡从表数据维护");
                            note.setOperationFunction("新增");
                            note.setOperationId(receivedTemp.getActualFirstNo());
                            note.setOperationCarnNo(receivedTemp.getRailwayNo());
                            meterBaseOperationLogMapper.insertSelective(note);
                            receivedTemp.setActualFirstNo(PublicMethod.IdCreate(3));
                            receivedTemp.setValueFlag("1");
                            receivedTemp.setRailwayTypeNo(receivedTemp.getRailwayModelNo());
                            receivedTemp.setRailwayTypeName(receivedTemp.getRailwayModelName());
                            meterWorkRailwayReceivedMapper.insertSelective(receivedTemp);
//                            receiveds.add(receivedTemp);
                            count ++;
                    }
                }
            }

            if(models.size()>=1) {
                if (map.size() >= 1) {
                    for(HashMap temp: map) {
                        //插入主表数据
                        MeterWorkRailwayRecMain recMain = new MeterWorkRailwayRecMain();
//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//                    String afl = sdf.format(new Date());
//                    String lcNo = meterWorkRailwayRecMainMapper.getLcNo(afl, receiveds.get(0).getBaseSpotNo());
//                    recMain.setActualNo(receiveds.get(0).getBaseSpotName().replaceAll("#", "")
//                            .replaceAll("轨道衡", "")
//                            .replaceAll("动轨", "")
//                            .replaceAll("动态", "") + "-" + afl + lcNo + "(" + receiveds.size() + ")");
                        recMain.setActualNo(temp.get("spotName").toString().replaceAll("#", "")
                                .replaceAll("轨道衡", "")
                                .replaceAll("动轨", "")
                                .replaceAll("动态", "") + temp.get("lcNo").toString());
//                            recMain.setActualNo(new SimpleDateFormat("yyyyMMddHHmm").format(new Date()) + PublicMethod.RandomCreate(2));
                        recMain.setIsDispose("0");
                        recMain.setSoundName(recMain.getActualNo());
                        recMain.setCarriageNum(Short.valueOf(temp.get("size").toString()));
                        recMain.setBaseSpotNo(temp.get("spotNo").toString());
                        recMain.setBaseSpotName(temp.get("spotName").toString());
                        recMain.setCreateTime(new Date());
                        meterWorkRailwayRecMainMapper.insertSelective(recMain);
                    }
                }


//                    for(MeterWorkRailwayReceived received: receiveds){
////                        if(received.getMemo() != null && StringUtils.isNotEmpty(received.getMemo())) {
//                            MeterBaseOperationLog note = new MeterBaseOperationLog();
//                            note.setId(PublicMethod.IdCreate(3));
//                            note.setCreateManNo(received.getCreateManNo());
//                            note.setCreateManName(received.getCreateManName());
//                            note.setCreateTime(new Date());
//                            note.setOperationPage("终端-轨道衡从表数据维护");
//                            note.setOperationFunction("新增");
//                            note.setOperationCarnNo(received.getRailwayNo());
//                            meterBaseOperationLogMapper.insertSelective(note);
////                        }
//                        received.setRailwayWorkNo(recMain.getActualNo());
//                        received.setActualFirstNo(PublicMethod.IdCreate(3));
//                        received.setValueFlag("1");
//                        received.setRailwayTypeNo("001019002");
//                        received.setRailwayTypeName("动态轨道衡");
//                        meterWorkRailwayReceivedMapper.insertSelective(received);
//                        count ++;
//                    }
            }

            rm.setSucceed();
            rm.setMessage("操作成功，共有" + count + "条数据更新成功");
            rm.setCode("200");
            rm.setData(count);
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常");
        }
        return rm;
    }

    @Override
    public PageList<MeterWorkRailwayReceived> likeByDesc(HashMap<String, Object> params, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        if(params.get("railwayTypeNoStr") != null) {
            String[] typeNoStr = params.get("railwayTypeNoStr").toString().split(",");
            params.put("typeNoStr", typeNoStr);
        }
        List<MeterWorkRailwayReceived> rows = meterWorkRailwayReceivedMapper.likeByDesc(params);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public RESTfulResult RemovePre(List<MeterWorkRailwayReceived> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            int count = 0;
            String userId = models.get(0).getUpdateManNo();
            String userName = models.get(0).getUpdateManName();
            for(MeterWorkRailwayReceived model: models){
                MeterWorkRailwayReceived modelTemp =  meterWorkRailwayReceivedMapper.selectByPrimaryKey(model.getActualFirstNo());
                if(modelTemp.getPredictionNo() != null && StringUtils.isNotEmpty(modelTemp.getPredictionNo())){
                    PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(modelTemp.getPredictionNo());
                    scale.setValueFlag("1");
                    scale.setUploadFlag("1");
                    scale.setUpdateManNo(userId);
                    scale.setUpdateManName(userName);
                    scale.setUpdateTime(new Date());
                    preRailwayScaleMapper.updateByPrimaryKeySelective(scale);
                }
                modelTemp = meterWorkRailwayReceivedMapper.selectAndRemove(modelTemp.getActualFirstNo());
                modelTemp.setIsAutoOperation("1");
                modelTemp.setUpdateManNo(userId);
                modelTemp.setUpdateManName(userName);
                modelTemp.setUpdateTime(new Date());
                meterWorkRailwayReceivedMapper.updateByPrimaryKey(modelTemp);
                count++;
            }
            rm.setSucceed(true);
            rm.setMessage("操作成功，共有" + count + "条数据更新成功");
            rm.setCode("200");
            rm.setData(count);
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常");
        }
        return rm;
    }

    @Override
    public RESTfulResult removeList(List<MeterWorkRailwayReceived> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            String userId = models.get(0).getUpdateManNo();
            String userName = models.get(0).getUpdateManName();
            int count = 0;
            for(MeterWorkRailwayReceived model: models){

                //获取修改前数据
                MeterWorkRailwayReceived upBefore = meterWorkRailwayReceivedMapper.selectByPrimaryKey(model.getActualFirstNo());
                //修改操作原因memo
                String memo = model.getMemo();
                String substring = "";
                try {
                    substring = memo.substring(memo.indexOf("作废原因：")+5, memo.indexOf("，数据信息："));
                }catch (Exception e){
                    e.printStackTrace();
                }
                model.setMemo(substring);

                model.setValueFlag("0");
                model.setIsAutoOperation("1");
                model.setUpdateManNo(userId);
                model.setUpdateManName(userName);
                model.setUpdateTime(new Date());
                meterWorkRailwayReceivedMapper.updateByPrimaryKeySelective(model);


                //添加日志记录
                MeterBaseOperationLog operationLog = new MeterBaseOperationLog();
                operationLog.setOperationPage("C#端-动轨数据维护");
                operationLog.setOperationFunction("作废");
                insertOperateLog(upBefore, operationLog);


                if(model.getPredictionNo() != null &&  StringUtils.isNotEmpty(model.getPredictionNo())){
                    PreRailwayScale preRailwayScale = new PreRailwayScale();
                    preRailwayScale.setValueFlag("1");
                    preRailwayScale.setUploadFlag("1");
                    preRailwayScale.setUpdateManNo(userId);
                    preRailwayScale.setUpdateManName(userName);
                    preRailwayScale.setPredictionNo(model.getPredictionNo());
                    preRailwayScaleMapper.updateByPrimaryKeySelective(preRailwayScale);
                }
                count++;
            }

            //修改主表是否已处理完
            if(models.size() >= 1) {
                MeterWorkRailwayReceived receivedModel = meterWorkRailwayReceivedMapper.selectByPrimaryKey(models.get(0).getActualFirstNo());
                if(receivedModel != null){
                    HashMap<String, Object> obj = new HashMap<>();
                    obj.put("railwayWorkNo", receivedModel.getRailwayWorkNo());
                    HashMap<String, Object> countMap = meterWorkRailwayReceivedMapper.getCount(obj);
                    int countNum = Integer.parseInt(countMap.get("COUNTNUM").toString());
                    if(countNum < 1) {
                        HashMap<String, Object> mainMap = new HashMap<>();
                        mainMap.put("soundName", receivedModel.getRailwayWorkNo());
                        List<MeterWorkRailwayRecMain> mainModel = meterWorkRailwayRecMainMapper.selectByParameters(mainMap);
                        if(mainModel.size() >= 1) {
                            mainModel.get(0).setIsDispose("1");
                            meterWorkRailwayRecMainMapper.updateByPrimaryKeySelective(mainModel.get(0));
                        }
                    }
                }
            }
            rm.setSucceed(true);
            rm.setMessage("操作成功，共有" + count + "条数据更新成功");
            rm.setCode("200");
            rm.setData(count);
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常");
        }
        return rm;
    }

    @Override
    public RESTfulResult matchPre(MeterWorkRailwayReceived model) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            if(StringUtils.isEmpty(model.getPredictionNo())) {
                rm.setMessage("请选择一条委托！！");
                return rm;
            }
            //修改前数据
            MeterWorkRailwayReceived modelTemp = meterWorkRailwayReceivedMapper.selectByPrimaryKey(model.getActualFirstNo());

            MeterBaseOperationLog note = new MeterBaseOperationLog();
            note.setId(PublicMethod.IdCreate(3));
            note.setCreateManNo(model.getUpdateManNo());
            note.setCreateManName(model.getUpdateManName());
            note.setCreateTime(new Date());
            note.setOperationPage("终端-轨道衡从表数据维护");
            note.setOperationFunction("匹配委托");
            note.setOperationId(model.getActualFirstNo());
            note.setOperationPredictionNo(model.getPredictionNo());
            note.setOperationCarnNo(model.getRailwayNo());
            note.setOperationBeforeFix(modelTemp.toString());

            PreRailwayScale preRailwayScale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
            preRailwayScale.setValueFlag("4");
            preRailwayScale.setUploadFlag("1");
            preRailwayScaleMapper.updateByPrimaryKeySelective(preRailwayScale);

            if(StringUtils.isNotEmpty(model.getPredictionNo())) {
                MeterWorkRailwayReceived firstRec1 = meterWorkRailwayReceivedMapper.selectAndMatch(model.getActualFirstNo(), preRailwayScale.getPredictionNo());
                BeanUtils.copyProperties(firstRec1,model);
                model.setPredictionType("1");
                meterWorkRailwayReceivedMapper.updateByPrimaryKeySelective(model);
            }
            model.setRailwayNo(preRailwayScale.getRailwayNo());
            meterWorkRailwayReceivedMapper.updateByPrimaryKeySelective(model);

            note.setOperationAfterFix(model.toString());
            meterBaseOperationLogMapper.insertSelective(note);

            rm.setSucceed();
            rm.setMessage("操作成功");
            rm.setCode("200");
            rm.setData(null);
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常");
        }
        return rm;
    }

    @Override
    @Transactional
    public RESTfulResult batchMatchPre(List<MeterWorkRailwayReceived> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            int count = 0;
            for(MeterWorkRailwayReceived model: models) {
                //修改前数据
                MeterWorkRailwayReceived modelTemp = meterWorkRailwayReceivedMapper.selectByPrimaryKey(model.getActualFirstNo());

                MeterBaseOperationLog note = new MeterBaseOperationLog();
                note.setId(PublicMethod.IdCreate(3));
                note.setCreateManNo(model.getUpdateManNo());
                note.setCreateManName(model.getUpdateManName());
                note.setCreateTime(new Date());
                note.setOperationPage("终端-轨道衡从表数据维护");
                note.setOperationFunction("匹配委托");
                note.setOperationId(model.getActualFirstNo());
                note.setOperationPredictionNo(model.getPredictionNo());
                note.setOperationCarnNo(model.getRailwayNo());
                note.setOperationBeforeFix(modelTemp.toString());

                PreRailwayScale scale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                scale.setValueFlag("4");
                scale.setUploadFlag("1");
                scale.setMeasureStation(modelTemp.getBaseSpotNo());
                scale.setMeasureStationName(modelTemp.getBaseSpotName());
                preRailwayScaleMapper.updateByPrimaryKeySelective(scale);

                if(StringUtils.isNotEmpty(model.getPredictionNo())) {
                    MeterWorkRailwayReceived firstRec1 = meterWorkRailwayReceivedMapper.selectAndMatch(model.getActualFirstNo(), scale.getPredictionNo());
                    BeanUtils.copyProperties(firstRec1,model);
                    model.setPredictionType("1");
                    meterWorkRailwayReceivedMapper.updateByPrimaryKey(model);
                }
                model.setRailwayNo(scale.getRailwayNo());
                model.setMatterNo(scale.getMatterNo());
                model.setMatterName(scale.getMatterName());
                model.setReceivingUintNo(scale.getReceivingUintNo());
                model.setReceivingUintName(scale.getReceivingUintName());
                model.setForwardingUnitNo(scale.getForwardingUnitNo());
                model.setForwardingUnitName(scale.getForwardingUnitName());
                meterWorkRailwayReceivedMapper.updateByPrimaryKeySelective(model);
                count ++;

                note.setOperationAfterFix(model.toString());
                meterBaseOperationLogMapper.insertSelective(note);
            }
            rm.setSucceed();
            rm.setMessage("操作成功,共有" + count + "条数据匹配委托成功");
            rm.setCode("200");
            rm.setData(null);
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作异常");
        }
        return rm;
    }

    /**
     * @param upBefore     修改前的数据
     * @param operationLog 操作日志实体：此处传界面及
     */
    public void insertOperateLog(MeterWorkRailwayReceived upBefore, MeterBaseOperationLog operationLog) {

        //修改后的数据
        MeterWorkRailwayReceived upAfter = meterWorkRailwayReceivedMapper.selectByPrimaryKey(upBefore.getActualFirstNo());
        //记录日志数据
        operationLog.setCreateManNo(upAfter.getUpdateManNo());
        operationLog.setCreateManName(upAfter.getUpdateManName());
        operationLog.setOperationId(upBefore.getActualFirstNo());
        operationLog.setOperationPredictionNo(upBefore.getPredictionNo());
        operationLog.setOperationCarnNo(upBefore.getRailwayNo());
        meterBaseOperationLogService.addComparePropertiesLog(upBefore, upAfter, operationLog);
    }
}
