package com.steerinfo.baseinfo.meterbasetermtaredata.service.impl;

import com.steerinfo.baseinfo.combaseinfo.mapper.ComBaseInfoMapper;
import com.steerinfo.baseinfo.meterbasecar.mapper.MeterBaseCarMapper;
import com.steerinfo.baseinfo.meterbasecar.model.MeterBaseCar;
import com.steerinfo.baseinfo.meterbasehistaredata.mapper.MeterBaseHisTareDataMapper;
import com.steerinfo.baseinfo.meterbasehistaredata.model.MeterBaseHisTareData;
import com.steerinfo.baseinfo.meterbasehistaredetail.mapper.MeterBaseHisTareDetailMapper;
import com.steerinfo.baseinfo.meterbasehistaredetail.model.MeterBaseHisTareDetail;
import com.steerinfo.baseinfo.meterbaseoperationlog.mapper.MeterBaseOperationLogMapper;
import com.steerinfo.baseinfo.meterbaseoperationlog.model.MeterBaseOperationLog;
import com.steerinfo.baseinfo.meterbasespotinfo.mapper.MeterBaseSpotInfoMapper;
import com.steerinfo.baseinfo.meterbasespotinfo.model.MeterBaseSpotInfo;
import com.steerinfo.baseinfo.meterbasetermtarecar.mapper.MeterBaseTermTareCarMapper;
import com.steerinfo.baseinfo.meterbasetermtarecar.model.MeterBaseTermTareCar;
import com.steerinfo.baseinfo.meterbasetermtaretime.mapper.MeterBaseTermTareTimeMapper;
import com.steerinfo.baseinfo.meterbasetermtaretime.model.MeterBaseTermTareTime;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.baseinfo.meterbasetermtaredata.model.MeterBaseTermTareData;
import com.steerinfo.baseinfo.meterbasetermtaredata.mapper.MeterBaseTermTareDataMapper;
import com.steerinfo.baseinfo.meterbasetermtaredata.service.IMeterBaseTermTareDataService;
import com.steerinfo.framework.user.UserPayload;
import com.steerinfo.metermonitor.metermonitornote.mapper.MeterMonitorNoteMapper;
import com.steerinfo.metermonitor.metermonitornote.model.MeterMonitorNote;
import com.steerinfo.meterwork.except.MarkerMetException;
import com.steerinfo.meterwork.meterworkcaractualfirst.mapper.MeterWorkCarActualFirstMapper;
import com.steerinfo.meterwork.meterworkcaractualfirst.model.MeterWorkCarActualFirst;
import com.steerinfo.util.FieldsCollector;
import com.steerinfo.util.PublicMethod;
import com.steerinfo.util.StringUtils;
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 javax.annotation.Resource;
import javax.validation.Payload;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.lang.Math.abs;

/**
 * MeterBaseTermTareData服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2020-06-24 02:18
 * 类描述
 * 修订历史：
 * 日期：2020-06-24
 * 作者：generator
 * 参考：
 * 描述：MeterBaseTermTareData服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "meterBaseTermTareDataService")
public class MeterBaseTermTareDataServiceImpl extends BaseServiceImpl<MeterBaseTermTareData, String> implements IMeterBaseTermTareDataService {

    @Resource
    private MeterBaseTermTareDataMapper meterBaseTermTareDataMapper;

    @Resource
    private ComBaseInfoMapper comBaseInfoMapper;

    @Resource
    private MeterBaseCarMapper meterBaseCarMapper;

    @Resource
    private MeterBaseSpotInfoMapper meterBaseSpotInfoMapper;

    @Resource
    private MeterBaseOperationLogMapper meterBaseOperationLogMapper;

    @Resource
    private MeterBaseTermTareCarMapper meterBaseTermTareCarMapper;

    @Resource
    private MeterWorkCarActualFirstMapper meterWorkCarActualFirstMapper;

    @Resource
    private MeterBaseTermTareTimeMapper meterBaseTermTareTimeMapper;

    @Resource
    private MeterMonitorNoteMapper meterMonitorNoteMapper;

    /**
     * 一次计量
     */
    @Resource
    private MeterBaseHisTareDataMapper meterBaseHisTareDataMapper;


    /**
     * 历史皮重明细表
     */
    @Resource
    private MeterBaseHisTareDetailMapper meterBaseHisTareDetailMapper;


    @Override
    protected IBaseMapper<MeterBaseTermTareData, String> getMapper() {
        return meterBaseTermTareDataMapper;
    }

    @Override
    public String Recovery(MeterBaseTermTareData model) {
        try {
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("valueFlag", "0");
            obj.put("carNo", model.getCarNo());
            obj.put("dataNo", model.getDataNo());
            List<MeterBaseTermTareData> list = meterBaseTermTareDataMapper.selectByParameters(obj);
            if (!list.isEmpty()) {
                return "该车号已存在有效数据，无法启用！";
            }
            model.setDataNo(model.getDataNo());
            model.setValueFlag("0");//有效
            meterBaseTermTareDataMapper.updateByPrimaryKey(model);
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "操作异常，请联系管理员";
        }
        return "";
    }

    @Override
    public String abolish(MeterBaseTermTareData model) {
        try {
            UserPayload payload = UserPayload.getCurrUser();
            String userId = payload.getUserCode();
            String userName = payload.getUserName();

            model.setId(model.getId());
            model.setValueFlag("1");
            model.setUpdateManNo(userId);
            model.setUpdateManName(userName);
            model.setUpdateTime(new Date());
            model.setNote(model.getNote());
            meterBaseTermTareDataMapper.updateByPrimaryKeySelective(model);

            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
            logModel.setId(PublicMethod.IdCreate(2));
            logModel.setCreateManNo(userId);
            logModel.setCreateManName(userName);
            logModel.setCreateTime(new Date());
            logModel.setOperationPage("web端-期限皮重数据维护");
            logModel.setOperationFunction("作废");
            logModel.setOperationId(model.getId());
            logModel.setOperationCarnNo(model.getCarNo());
            logModel.setOperationBeforeFix(model.getNote());
            meterBaseOperationLogMapper.insertSelective(logModel);
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "操作异常，请联系管理员";
        }
        return "";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<MeterBaseTermTareData> selectBy(String carNo) throws MarkerMetException {
        List<MeterBaseTermTareData> mbttds =new ArrayList<MeterBaseTermTareData>();
        try {
            List<MeterWorkCarActualFirst> mwcafs = meterWorkCarActualFirstMapper.selectNet("1", carNo);
            if (mwcafs.size() <= 0 || mwcafs == null) {
                if (carNo == null && carNo.equals("")) {
                    throw new MarkerMetException(500, "车号为空!!");
                }
                MeterBaseTermTareCar mbttc = meterBaseTermTareCarMapper.selectByPrimaryKey(carNo);
                if (!mbttc.getValueFlag().equals("0")) {
                    throw new MarkerMetException(500, "该车已被停役！");
                }
                HashMap<String, Object> obj = new HashMap<>();
                obj.put("carNo", carNo);
                mbttds = meterBaseTermTareDataMapper.selectByParameters(obj);
                return mbttds;
            }
        } catch (MarkerMetException e) {
            throw e;
        }
        return mbttds;
    }

    public List<MeterBaseTermTareData> doQueryWf(MeterBaseTermTareData oci) {
        oci.setEndTime(new Date());
        Map<String, Object> map = FieldsCollector.beanToMap(oci);
        List<MeterBaseTermTareData> list = meterBaseTermTareDataMapper.selectBy(map);
        return list;
    }

    /**
     * 能进入到这里说明已经验证过可以保存期限皮重了
     *
     * @param oci
     * @return
     */
    //@Transactional(value="tm", rollbackFor=Exception.class)
    public RESTfulResult doSaveWf(MeterBaseTermTareData oci, MeterMonitorNote note) {
        RESTfulResult rm = new RESTfulResult();
        rm.setCode("200");

        //查下是否存在皮重时间配置信息，存在则继续，不存在则提示不存在
        //METER_BASE_TERM_TARE_COUNT
        Map<String, Object> map = new HashMap<>();
        map.put("valueFlag","0");
        List<MeterBaseTermTareTime> lmbttc = meterBaseTermTareTimeMapper.selectByParameters(map);
        if (lmbttc == null || lmbttc.size() == 0) {
            rm.setCode("500");
            rm.setMessage("未找到期限皮重时间配置信息，无法保存期限皮!");
        }

        Random rd = new Random();
        int day = 0;
        try {
            switch (lmbttc.get(0).getTimeTypeNo()) {
                case "001013001": //随机间隔
                    day = rd.nextInt(Integer.parseInt(lmbttc.get(0).getRateValue() + ""));
                    break;
                case "001013002": //固定间隔
                    day = lmbttc.get(0).getFixedValue().intValue();
                    break;
                case "001013003": //前固后随
                    day = lmbttc.get(0).getFixedValue().intValue() + rd.nextInt(lmbttc.get(0).getRateValue().intValue());
                    break;
                default:
                    break;
            }

            Calendar c = new GregorianCalendar();
            c.setTime(oci.getMeterTime());
            c.add(c.DATE, day);//日期增加day天
            Date dt = c.getTime();//得到有效结束的时间

            Calendar c1 = new GregorianCalendar();
            c1.setTime(dt);
            c.add(c.HOUR, -lmbttc.get(0).getWarnValue().intValue());//日期减少小时
            Date dts = c.getTime();//得到提醒时间


            Map<String, Object> map1 = new HashMap<>();
            map1.put("valueFlag","0");
            map1.put("carNo",oci.getCarNo());
            List<MeterBaseTermTareData> lmbt = meterBaseTermTareDataMapper.selectByParameters(map1);

            if (lmbt == null || lmbt.size() == 0) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                String afl = formatter.format(oci.getCreateTime());
                String no = meterBaseTermTareDataMapper.getNewID(afl);
                //做新增操作
                oci.setDataNo(afl + no);
                oci.setStartTime(oci.getMeterTime());
                oci.setEndTime(dt);
                oci.setUpWeight(oci.getMeterWeight().longValue());
                oci.setAvgWeight(oci.getMeterWeight().longValue());
                oci.setWarnTime(dts);
                oci.setMeterNum(1l);
                oci.setValueFlag("0");
                meterBaseTermTareDataMapper.insert(oci);
            } else {
                //做修改操作
                oci.setDataNo(lmbt.get(0).getDataNo());
                oci.setStartTime(oci.getMeterTime());
                oci.setEndTime(dt);
                oci.setUpWeight(lmbt.get(0).getMeterWeight().longValue());
                oci.setWarnTime(dts);
                Long a = lmbt.get(0).getAvgWeight()*lmbt.get(0).getMeterNum()+oci.getMeterWeight().longValue();
                Long b = a/(lmbt.get(0).getMeterNum() + 1);
                oci.setAvgWeight(b);
                oci.setMeterNum(lmbt.get(0).getMeterNum()+1);
                meterBaseTermTareDataMapper.updateByPrimaryKeySelective(oci);
            }

            saveHisTareFromTerm(oci); //2021年6月14日 若历史皮重被作废，则留期限皮的时候，也留一条普通皮重；
        } catch (Exception ex) {
            rm.setCode("500");
            rm.setMessage("保存期限皮重失败：" + ex.getMessage());
        }
        //保存日志
//        saveNote(note);

        return rm;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RESTfulResult doSaveTerm(String id) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            //从一次计量表里取出：车号、计量点编号、计量点名称、计量时间、计量重量
            String actualFirstNo = id;
            MeterWorkCarActualFirst modelTemp = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualFirstNo);
            String carNo = modelTemp.getCarNo();
            String baseSpotName = modelTemp.getBaseSpotName();
            String baseSpotNo = modelTemp.getBaseSpotNo();
            Date meterTime = modelTemp.getCreateTime();
            BigDecimal meterWeight = modelTemp.getMeterWeight();
            if(StringUtils.isEmpty(carNo)){
                rm.setMessage("车号不能为空，请确认！！");
                rm.setCode("1");
                return rm;
            }
            if(StringUtils.isEmpty(baseSpotNo) && StringUtils.isEmpty(baseSpotName)){
                rm.setMessage("计量点编号或者计量点名称为空，请确认！！");
                rm.setCode("1");
                return rm;
            }
            if(meterTime == null || StringUtils.isEmpty(meterTime.toString())){
                rm.setMessage("计量时间不能为空！！");
                rm.setCode("1");
                return rm;
            }

            HashMap<String, Object> ms = new HashMap<>();
            ms.put("carNo", carNo);
            ms.put("validFlag", "0");
            ms.put("carTypeNo", "001004003");
            List<MeterBaseCar> models = meterBaseCarMapper.selectByParameters(ms);
            if(models.size() < 1 ) {
                rm.setMessage("车辆不是内部车辆不能留存期限皮！！");
                rm.setCode("1");
                return rm;
            }
            String userId = "";
            String userName = "";
            try{
                UserPayload payload = UserPayload.getCurrUser();
                userId = payload.getUserCode();
                userName = payload.getUserName();
            }catch(Exception e) {
                userId = "system";
                userName = "system";
            }
            if(StringUtils.isEmpty(modelTemp.getWeightType())
                    || !(modelTemp.getWeightType().equals("1") || modelTemp.getWeightType().equals("2"))) {
                rm.setMessage("计量类型不是皮重类型，请进行毛皮转换成皮重之后再保存期限皮！！");
                rm.setCode("1");
                return rm;
            }else {
                modelTemp.setWeightType("2");
                modelTemp.setValueFlag("0");
                modelTemp.setUpdateManName(userId);
                modelTemp.setUpdateManNo(userName);
                modelTemp.setUpdateTime(new Date());
                modelTemp.setNote("期限皮重保存");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(modelTemp);
            }

            //根据车号查询期限表的期限皮重信息
            MeterBaseSpotInfo spotInfo = meterBaseSpotInfoMapper.selectByPrimaryKey(modelTemp.getBaseSpotNo());
            HashMap<String, Object> map = new HashMap();
            map.put("carNo", carNo);
            map.put("spotAreaNo", spotInfo.getSpotAreaNo());
            map.put("spotAreaName", spotInfo.getSpotAreaName());
            MeterBaseTermTareData modelTerm = meterBaseTermTareDataMapper.selectWhereCarNo(map);
            //设置数据编号
            MeterBaseTermTareData model = new MeterBaseTermTareData();
            //设置计量点编号、名称、车号
            model.setBaseSpotName(baseSpotName);
            model.setBaseSpotNo(baseSpotNo);
            model.setSpotAreaNo(spotInfo.getSpotAreaNo());
            model.setSpotAreaName(spotInfo.getSpotAreaName());
            model.setCarNo(carNo);
            //设置皮重时间、开始时间、结束时间、提醒留皮时间
            HashMap<String, Object> tareTimemap = new HashMap();
            tareTimemap.put("valueFlag", "0");
            MeterBaseTermTareTime tareTimeModel = meterBaseTermTareTimeMapper.selectByMap(tareTimemap);
            if(tareTimeModel != null){
                Date endDate = new Date();
                Date warnDate = new Date();
                int day = tareTimeModel.getFixedValue();
                endDate.setDate(endDate.getDate()+day);
                warnDate.setDate(warnDate.getDate()+tareTimeModel.getWarnValue());
                model.setStartTime(new Date());
                model.setEndTime(new Date(endDate.getTime()));
                model.setWarnTime(new Date(warnDate.getTime()));
            }else{
                rm.setMessage("计量人编号或者计量员为空，请确认");
                rm.setCode("1");
                return rm;
            }
            model.setMeterTime(meterTime);
            //设置状态（0：有效；1：无效）、创建人编号、创建人、创建时间
            model.setValueFlag("0");
            model.setCreateManNo(userId);
            model.setCreateManName(userName);
            model.setCreateTime(new Date());
            //设置皮重次数(默认7次)、设置皮重
            model.setMeterNum(7L);
            model.setMeterWeight(meterWeight);
            //期限皮表未查到车号信息，直接插入，否则，更新车号信息
            if(modelTerm == null){
                model.setUpWeight(meterWeight.longValue());
                model.setAvgWeight(meterWeight.longValue());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                model.setDataNo(sdf.format(new Date()));
                meterBaseTermTareDataMapper.insertSelective(model);
            }else if(modelTerm.getCarNo().equals(carNo)){
                //设置上一次皮重、平均皮重
                model.setUpWeight(modelTerm.getMeterWeight().longValue());  //BigDecimal转long类型
                long avgValue = modelTerm.getAvgWeight() == null? 0: modelTerm.getAvgWeight();
                long avg =avgValue + modelTerm.getMeterWeight().longValue();
                model.setAvgWeight(avg/2);
                model.setDataNo(modelTerm.getDataNo());
                meterBaseTermTareDataMapper.updateByPrimaryKeySelective(model);
            }

            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
            logModel.setId(PublicMethod.IdCreate(2));
            logModel.setCreateManNo(userId);
            logModel.setCreateManName(userName);
            logModel.setCreateTime(new Date());
            logModel.setOperationPage("web端-汽车衡一次数据维护");
            logModel.setOperationFunction("留存期限皮");
            logModel.setOperationId(modelTemp.getActualFirstNo());
            logModel.setOperationPredictionNo(modelTemp.getPredictionNo());
            logModel.setOperationCarnNo(modelTemp.getCarNo());
            logModel.setOperationBeforeFix("重量：" + modelTemp.getMeterWeight().toString());
            meterBaseOperationLogMapper.insertSelective(logModel);

            rm.setSucceed();
            rm.setCode("200");
            rm.setMessage("操作成功");
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作失败，" + e.getMessage());
        }
        return rm;
    }

    @Override
    public RESTfulResult doSaveTermByConfig(String id) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{

            String userId = "";
            String userName = "";
            try{
                UserPayload payload = UserPayload.getCurrUser();
                userId = payload.getUserCode();
                userName = payload.getUserName();
            }catch(Exception e) {
                userId = "system";
                userName = "system";
            }

//            HashMap<String, Object> gaugerMap = new HashMap<>();
//            gaugerMap.put("pBaseCode", "001059");
//            gaugerMap.put("memo", userId);
//            List<String> gaugerModels = comBaseInfoMapper.matterNoByBaseCode(gaugerMap);
//
//            if(gaugerModels.size() < 1) {
//                rm.setMessage("该用户<" + userName + ">没有留存期限皮权限！！");
//                rm.setCode("1");
//                return rm;
//            }
            //从一次计量表里取出：车号、计量点编号、计量点名称、计量时间、计量重量
            String actualFirstNo = id;
            MeterWorkCarActualFirst modelTemp = meterWorkCarActualFirstMapper.selectByPrimaryKey(actualFirstNo);
            String carNo = modelTemp.getCarNo();
            String baseSpotName = modelTemp.getBaseSpotName();
            String baseSpotNo = modelTemp.getBaseSpotNo();
            Date meterTime = modelTemp.getCreateTime();
            BigDecimal meterWeight = modelTemp.getMeterWeight();
            if(StringUtils.isEmpty(carNo)){
                rm.setMessage("车号不能为空，请确认！！");
                rm.setCode("1");
                return rm;
            }
            if(StringUtils.isEmpty(baseSpotNo) && StringUtils.isEmpty(baseSpotName)){
                rm.setMessage("计量点编号或者计量点名称为空，请确认！！");
                rm.setCode("1");
                return rm;
            }
            if(meterTime == null || StringUtils.isEmpty(meterTime.toString())){
                rm.setMessage("计量时间不能为空！！");
                rm.setCode("1");
                return rm;
            }

            HashMap<String, Object> ms = new HashMap<>();
            ms.put("carNo", carNo);
            ms.put("validFlag", "0");
            ms.put("carTypeNo", "001004003");
            List<MeterBaseCar> models = meterBaseCarMapper.selectByParameters(ms);
            if(models.size() < 1 ) {
                rm.setMessage("车辆不是内部车辆不能留存期限皮！！");
                rm.setCode("1");
                return rm;
            }
            if(StringUtils.isEmpty(modelTemp.getWeightType())
                    || !(modelTemp.getWeightType().equals("1") || modelTemp.getWeightType().equals("2"))) {
                rm.setMessage("计量类型不是皮重类型，请进行毛皮转换成皮重之后再保存期限皮！！");
                rm.setCode("1");
                return rm;
            }else {
                modelTemp.setWeightType("2");
                modelTemp.setValueFlag("0");
                modelTemp.setUpdateManName(userId);
                modelTemp.setUpdateManNo(userName);
                modelTemp.setUpdateTime(new Date());
                modelTemp.setNote("期限皮重保存");
                meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(modelTemp);
            }

            //根据车号查询期限表的期限皮重信息
            MeterBaseSpotInfo spotInfo = meterBaseSpotInfoMapper.selectByPrimaryKey(modelTemp.getBaseSpotNo());
            HashMap<String, Object> map = new HashMap();
            map.put("carNo", carNo);
            map.put("spotAreaNo", spotInfo.getSpotAreaNo());
            map.put("spotAreaName", spotInfo.getSpotAreaName());
            MeterBaseTermTareData modelTerm = meterBaseTermTareDataMapper.selectWhereCarNo(map);
            //设置数据编号
            MeterBaseTermTareData model = new MeterBaseTermTareData();
            //设置计量点编号、名称、车号
            model.setBaseSpotName(baseSpotName);
            model.setBaseSpotNo(baseSpotNo);
            model.setSpotAreaNo(spotInfo.getSpotAreaNo());
            model.setSpotAreaName(spotInfo.getSpotAreaName());
            model.setCarNo(carNo);
            //设置皮重时间、开始时间、结束时间、提醒留皮时间
            HashMap<String, Object> tareTimemap = new HashMap();
            tareTimemap.put("valueFlag", "0");
            MeterBaseTermTareTime tareTimeModel = meterBaseTermTareTimeMapper.selectByMap(tareTimemap);
            if(tareTimeModel != null){
                Date endDate = new Date();
                Date warnDate = new Date();
                int day = tareTimeModel.getFixedValue();
                endDate.setDate(endDate.getDate()+day);
                warnDate.setDate(warnDate.getDate()+tareTimeModel.getWarnValue());
                model.setStartTime(new Date());
                model.setEndTime(new Date(endDate.getTime()));
                model.setWarnTime(new Date(warnDate.getTime()));
            }else{
                rm.setMessage("计量人编号或者计量员为空，请确认");
                rm.setCode("1");
                return rm;
            }
            model.setMeterTime(meterTime);
            //设置状态（0：有效；1：无效）、创建人编号、创建人、创建时间
            model.setValueFlag("0");
            model.setCreateManNo(userId);
            model.setCreateManName(userName);
            model.setCreateTime(new Date());
            //设置皮重次数(默认7次)、设置皮重
            model.setMeterNum(7L);
            model.setMeterWeight(meterWeight);
            //期限皮表未查到车号信息，直接插入，否则，更新车号信息
            if(modelTerm == null){
                model.setUpWeight(meterWeight.longValue());
                model.setAvgWeight(meterWeight.longValue());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                model.setDataNo(sdf.format(new Date()));
                meterBaseTermTareDataMapper.insertSelective(model);
            }else if(modelTerm.getCarNo().equals(carNo)){
                //设置上一次皮重、平均皮重
                model.setUpWeight(modelTerm.getMeterWeight().longValue());  //BigDecimal转long类型
                long avgValue = modelTerm.getAvgWeight() == null? 0: modelTerm.getAvgWeight();
                long avg =avgValue + modelTerm.getMeterWeight().longValue();
                model.setAvgWeight(avg/2);
                model.setDataNo(modelTerm.getDataNo());
                meterBaseTermTareDataMapper.updateByPrimaryKeySelective(model);
            }

            MeterBaseOperationLog logModel = new MeterBaseOperationLog();
            logModel.setId(PublicMethod.IdCreate(2));
            logModel.setCreateManNo(userId);
            logModel.setCreateManName(userName);
            logModel.setCreateTime(new Date());
            logModel.setOperationPage("web端-汽车衡一次数据维护");
            logModel.setOperationFunction("留存期限皮");
            logModel.setOperationId(modelTemp.getActualFirstNo());
            logModel.setOperationPredictionNo(modelTemp.getPredictionNo());
            logModel.setOperationCarnNo(modelTemp.getCarNo());
            logModel.setOperationBeforeFix("重量：" + modelTemp.getMeterWeight().toString());
            meterBaseOperationLogMapper.insertSelective(logModel);

            rm.setSucceed();
            rm.setCode("200");
            rm.setMessage("操作成功");
        }catch(Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setMessage("操作失败，" + e.getMessage());
        }
        return rm;
    }

    @Override
    public RESTfulResult listBycarNo(HashMap<String, Object> parmas) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            List<MeterBaseTermTareData> models = meterBaseTermTareDataMapper.listBycarNo(parmas);
            if(models.size() >= 1) {
                rm.setSucceed();
                rm.setMessage("操作成功！！");
                rm.setData(models.get(0));
                rm.setCode("200");
            }else {
                rm.setSucceed();
                rm.setMessage("未找到相应期限皮重信息");
                rm.setData("");
                rm.setCode("200");
            }
        }catch (Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常，请确认！！" + e.getMessage());
        }
        return rm;
    }

    @Override
    public RESTfulResult ApplistBycarNo(HashMap<String, Object> parmas) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            parmas.put("valueFlag", "0");
            List<MeterBaseTermTareData> models = meterBaseTermTareDataMapper.selectByParameters(parmas);
            if(models.size() >= 1) {
                //MeterBaseTermTareData model = models.get(0);
                List<HashMap> maps = new ArrayList<>();
                for(MeterBaseTermTareData model: models) {
                    //判断期限皮过期时间
                    HashMap<String, Object> map = new HashMap<>();
                    Date startTime = sdf.parse(sdf.format(model.getEndTime()));
                    Date endTime = sdf.parse(sdf.format(new Date()));
                    long from = startTime.getTime();
                    long to = endTime.getTime();
                    int day = (int)(from - to)/(60*60*24*1000);
                    int hour = (int)(from - to)/(60*60*1000);
                    int minutes = (int)(from - to)/(60*1000) - (hour*60);
                    if(startTime.compareTo(endTime) > 0) {
                        map.put("flag", "1");
                    }else {
                        map.put("flag", "0");
                    }
                    map.put("model", model);
                    map.put("day", abs(day));
                    map.put("hour", abs(hour));
                    map.put("minutes", abs(minutes));
                    maps.add(map);
                }
                rm.setData(maps);
                rm.setSucceed();
                rm.setMessage("操作成功");
                rm.setCode("200");
            }else {
                rm.setMessage("未找到相应有效期限皮重信息");
                rm.setCode("500");
            }
        }catch (Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常，请确认！！" + e.getMessage());
        }
        return rm;
    }

    private String saveNote(MeterMonitorNote note){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String afl = formatter.format(new Date());
        String no = meterMonitorNoteMapper.getNewID(afl);
        note.setNoteNo(PublicMethod.IdCreate(3));
        meterMonitorNoteMapper.insert(note);
        return note.getNoteNo();
    }

    /**
     * 通过期限皮重，更新历史皮重
     * @param oci
     */
    private void saveHisTareFromTerm(MeterBaseTermTareData oci){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String afl = formatter.format(oci.getCreateTime());

        MeterBaseHisTareData mbtd = new MeterBaseHisTareData();
        mbtd.setCarNo(oci.getCarNo());
        mbtd.setValueFlag("0");
        Map<String, Object> map = FieldsCollector.beanToMap(mbtd);
        List<MeterBaseHisTareData> lmOne = meterBaseHisTareDataMapper.selectByParameters(map);
        if (lmOne != null && lmOne.size() > 0) {
            //说明存在历史皮重，则执行修改操作
            mbtd.setDataNo(lmOne.get(0).getDataNo());
            mbtd.setBaseSpotNo(oci.getBaseSpotNo());
            mbtd.setBaseSpotName(oci.getBaseSpotName());
            mbtd.setMeterWeight(Math.round(oci.getMeterWeight().doubleValue()));
            mbtd.setUpWeight(oci.getMeterWeight().longValue()); //上次皮重
            //  (之前的重量*次数)/(次数+1)
            double db = (lmOne.get(0).getAvgWeight() * lmOne.get(0).getMeterNum() + lmOne.get(0).getMeterWeight()) / (lmOne.get(0).getMeterNum() + 1);
            mbtd.setAvgWeight(Math.round(db));//平均皮重
            mbtd.setMeterNum(lmOne.get(0).getMeterNum() + 1);
            mbtd.setCreateTime(new Date());
            mbtd.setCreateManNo("system");
            mbtd.setCreateManName("期限皮重更新");
            meterBaseHisTareDataMapper.updateByPrimaryKeySelective(mbtd);
        } else {
            //新增操作
            String no = meterBaseHisTareDataMapper.getNewID(afl);
            mbtd.setDataNo(afl + no);
            mbtd.setBaseSpotNo(oci.getBaseSpotNo());
            mbtd.setBaseSpotName(oci.getBaseSpotName());
            mbtd.setMeterWeight(Math.round(oci.getMeterWeight().doubleValue()));
            mbtd.setUpWeight(oci.getMeterWeight().longValue()); //上次皮重
            mbtd.setAvgWeight(Math.round(oci.getMeterWeight().doubleValue()));//平均皮重
            mbtd.setMeterNum(1l);
            mbtd.setMeterTime(oci.getCreateTime());
            mbtd.setCreateTime(oci.getCreateTime());
            mbtd.setCreateManNo("system");
            mbtd.setCreateManName("期限皮重新增");
            meterBaseHisTareDataMapper.insert(mbtd);
        }
        MeterBaseHisTareDetail mbhtd = new MeterBaseHisTareDetail();
        String no = meterBaseHisTareDetailMapper.getNewID(afl);
        mbhtd.setDetailNo(PublicMethod.IdCreate(3));
        mbhtd.setActualFirstNo(oci.getDataNo()); //期限皮重主键
        mbhtd.setBaseSpotNo(oci.getBaseSpotNo());
        mbhtd.setBaseSpotName(oci.getBaseSpotName());
        mbhtd.setCarNo(oci.getCarNo());
        mbhtd.setMeterOrder("1");
        mbhtd.setMeterTime(oci.getCreateTime());
        mbhtd.setMeterWeight(oci.getMeterWeight().longValue());
        meterBaseHisTareDetailMapper.insert(mbhtd);
    }
}
