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

import com.steerinfo.baseinfo.meterbasehistaredata.model.MeterBaseHisTareData;
import com.steerinfo.baseinfo.meterbaseoperationlog.mapper.MeterBaseOperationLogMapper;
import com.steerinfo.baseinfo.meterbaseoperationlog.model.MeterBaseOperationLog;
import com.steerinfo.baseinfo.meterbaserailwayhistaredata.mapper.MeterBaseRailwayHisTareDataMapper;
import com.steerinfo.baseinfo.meterbaserailwayhistaredata.model.MeterBaseRailwayHisTareData;
import com.steerinfo.baseinfo.meterbaserailwayhistaredata.service.IMeterBaseRailwayHisTareDataService;
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.framework.user.UserPayload;
import com.steerinfo.util.PublicMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

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

    @Autowired(required = false)
    private MeterBaseRailwayHisTareDataMapper meterBaseRailwayHisTareDataMapper;

    @Resource
    private MeterBaseOperationLogMapper meterBaseOperationLogMapper;

    @Override
    protected IBaseMapper<MeterBaseRailwayHisTareData, String> getMapper() {
        return meterBaseRailwayHisTareDataMapper;
    }

    @Override
    public RESTfulResult railwayHisTare(String railwayNo, String meterWeight,String meterName, String baseSpotNo, String baseSpotName) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try {
            if (railwayNo.equals("")) {
                rm.setMessage("火车车号不能为空！！");
                return rm;
            }
            if (meterWeight.equals("")) {
                rm.setMessage("计量重量不能为空！！");
                return rm;
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("railwayNo", railwayNo);
            List<MeterBaseRailwayHisTareData> model = meterBaseRailwayHisTareDataMapper.selectByParameters(map);
            if (model.size() >= 1) {
                MeterBaseRailwayHisTareData hisTaremodel = model.get(0);
                hisTaremodel.setMeterWeight(Long.parseLong(meterWeight));
                hisTaremodel.setMeterTime(new Date());
                hisTaremodel.setMeterName(meterName);
                hisTaremodel.setValueFlag("0");
                hisTaremodel.setUpWeight(hisTaremodel.getMeterWeight());
                //新平均重量 = 当前平均重量*总次数+当前计量重量/(总次数+1)
                Long num = hisTaremodel.getMeterNum() + 1;
                Long avg = (hisTaremodel.getAvgWeight() * hisTaremodel.getMeterNum() + Long.parseLong(meterWeight)) / num;
                hisTaremodel.setAvgWeight(avg);
                hisTaremodel.setMeterNum(num);
                hisTaremodel.setBaseSpotNo(baseSpotNo);
                hisTaremodel.setBaseSpotName(baseSpotName);
                int i = meterBaseRailwayHisTareDataMapper.updateByPrimaryKeySelective(hisTaremodel);
                if (i >= 1) {
                    rm.setSucceed();
                    rm.setData(hisTaremodel);
                    rm.setMessage("操作成功！！");
                    return rm;
                }
            } else {
                MeterBaseRailwayHisTareData hisTareData = new MeterBaseRailwayHisTareData();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String no = meterBaseRailwayHisTareDataMapper.getNewID(sdf.format(new Date()));
                hisTareData.setDataNo(sdf.format(new Date()) + no);
                hisTareData.setRailwayNo(railwayNo);
                hisTareData.setMeterWeight(Long.parseLong(meterWeight));
                hisTareData.setMeterNum(new Long(1));
                hisTareData.setAvgWeight(Long.parseLong(meterWeight));
                hisTareData.setUpWeight(Long.parseLong(meterWeight));
                hisTareData.setValueFlag("0");
                hisTareData.setMeterName(meterName);
                hisTareData.setMeterTime(new Date());
                hisTareData.setCreateTime(new Date());
                UserPayload payload = UserPayload.getCurrUser();
                String userId = payload.getUserCode();
                String userName = payload.getUserName();
                hisTareData.setCreateManNo(userId);
                hisTareData.setCreateManName(userName);
                /*hisTareData.setCreateManNo("userId");
                hisTareData.setCreateManName("userName");*/
                hisTareData.setBaseSpotNo(baseSpotNo);
                hisTareData.setBaseSpotName(baseSpotName);
                int i = meterBaseRailwayHisTareDataMapper.insertSelective(hisTareData);
                if (i >= 1) {
                    rm.setSucceed();
                    rm.setData(hisTareData);
                    rm.setMessage("操作成功！！");
                    return rm;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return rm;
        }
        return rm;
    }

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

    @Override
    public String abolish(MeterBaseRailwayHisTareData 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());
            meterBaseRailwayHisTareDataMapper.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.getRailwayNo());
            logModel.setOperationBeforeFix(model.getNote());
            meterBaseOperationLogMapper.insertSelective(logModel);
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "操作异常，请联系管理员";
        }
        return "";
    }

    @Override
    public PageList<MeterBaseRailwayHisTareData> getList(HashMap params) {
        PageHelper.startPage(Integer.parseInt(params.get("pageNum").toString()), Integer.parseInt(params.get("pageSize").toString()));
        List<MeterBaseRailwayHisTareData> list = meterBaseRailwayHisTareDataMapper.getList(params);
        PageList pageInfo = new PageList(list);
        return pageInfo;
    }

}
