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

import com.steerinfo.baseinfo.constants.DbConstants;
import com.steerinfo.baseinfo.meterbaserailwayweight.mapper.MeterBaseRailwayWeightMapper;
import com.steerinfo.baseinfo.meterbaserailwayweight.model.MeterBaseRailwayWeight;
import com.steerinfo.baseinfo.meterbaserailwayweight.service.IMeterBaseRailwayWeightService;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.user.UserPayload;
import com.steerinfo.meterwork.except.MarkerMetException;
import com.steerinfo.meterwork.meterworkcaractualfirst.mapper.MeterWorkCarActualFirstMapper;
import com.steerinfo.meterwork.meterworkcaractualfirst.model.MeterWorkCarActualFirst;
import com.steerinfo.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

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

    @Resource
    private MeterBaseRailwayWeightMapper meterBaseRailwayWeightMapper;

    @Resource
    private MeterWorkCarActualFirstMapper meterWorkCarActualFirstMapper;

    @Override
    protected IBaseMapper<MeterBaseRailwayWeight, String> getMapper() {
        return meterBaseRailwayWeightMapper;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public List<MeterBaseRailwayWeight> selectTo(String railwayNo, String flag)throws MarkerMetException
    {
        List<MeterWorkCarActualFirst>  mwcafs=meterWorkCarActualFirstMapper.selectNet("1",railwayNo);
        if (mwcafs.isEmpty())
        {
            if (StringUtils.isEmpty(railwayNo)) {
                throw new MarkerMetException(500, "车号为空!!");
            }
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("railwayNo", railwayNo);
            List<MeterBaseRailwayWeight> mbrw = meterBaseRailwayWeightMapper.selectByParameters(obj);
            return mbrw;
        }
        return null;
    }

    @Override
    public List<MeterBaseRailwayWeight> noPage(Map<String, Object> param) {
        return meterBaseRailwayWeightMapper.noPage(param);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public MeterBaseRailwayWeight checkandadd(MeterBaseRailwayWeight model)
    {
        try{
            if (model == null) {
                throw  new MarkerMetException(500,"参数不能为空！！");
            }
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("railwayNo", model.getRailwayNo());
            List<MeterBaseRailwayWeight> com=meterBaseRailwayWeightMapper.selectByParameters(obj);
            if( ! com.isEmpty())
            {
                throw  new MarkerMetException(500, model.getRailwayNo()+"已存在！");
            }
            check(model);
            String no=meterBaseRailwayWeightMapper.GetNewID();
            model.setRailwayPk(new SimpleDateFormat("yyyyMMdd").format(new Date())+no);
            meterBaseRailwayWeightMapper.insertSelective(model);
            return model;
        }catch (MarkerMetException e){
            throw  e;
        }
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int checkandupdate(MeterBaseRailwayWeight model)
    {
        try{
            if (model == null)
            {
                throw  new MarkerMetException(500,"参数不能为空！！");
            }
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("railwayNo", model.getRailwayNo());
            obj.put("railwayPk", model.getRailwayPk());
            List<MeterBaseRailwayWeight> com=meterBaseRailwayWeightMapper.selectForUpdate(obj);
            if( ! com.isEmpty())
            {
                throw  new MarkerMetException(500, model.getRailwayNo()+"已存在！");
            }
            check(model);
            int num=meterBaseRailwayWeightMapper.updateByPrimaryKey(model);
            return num;
        }catch (MarkerMetException e){
            throw  e;
        }
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int abolish(List<MeterBaseRailwayWeight> models)
    {
        try{
            int num=0;
            if (models.size() <= 0 || models == null)
            {
                throw  new MarkerMetException(500,"参数不能为空！！");
            }
            for(MeterBaseRailwayWeight model:models)
            {
                if (model.getValueFlag().equals(DbConstants.INVALID))
                {
                    throw  new MarkerMetException(500,"无法再次停用！！");
                }
                model.setRailwayPk(model.getRailwayPk());
                model.setValueFlag(DbConstants.INVALID);
                meterBaseRailwayWeightMapper.updateByPrimaryKey(model);
                num++;
            }
            return num;
        }catch (MarkerMetException e){
            throw  e;
        }
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int recover(List<MeterBaseRailwayWeight> models)
    {
        try{
            int num=0;
            if (models.size() <= 0 || models == null)
            {
                throw  new MarkerMetException(500,"参数不能为空！！");
            }
            for(MeterBaseRailwayWeight model:models)
            {
                if (model.getValueFlag().equals(DbConstants.VALID))
                {
                    throw  new MarkerMetException(500,"无法再次启用！！");
                }
                model.setRailwayPk(model.getRailwayPk());
                model.setValueFlag(DbConstants.VALID);
                meterBaseRailwayWeightMapper.updateByPrimaryKey(model);
                num++;
            }
            return num;
        }catch (MarkerMetException e){
            throw  e;
        }
    }

    private void check(MeterBaseRailwayWeight model)
    {
        if(model.getRailwayNo()==null || model.getRailwayNo().equals(""))
        {
            throw  new MarkerMetException(500,"火车车厢号不能为空");
        }
        if(model.getRailwayWeight()==null || model.getRailwayWeight().equals(""))
        {
            throw  new MarkerMetException(500,"车厢重量不能为空");
        }
        if(model.getRailwayTypeNo()==null || model.getRailwayTypeNo().equals(""))
        {
            throw  new MarkerMetException(500,"轨道衡类型编号不能为空");
        }
        if(model.getRailwayTypeName()==null || model.getRailwayTypeName().equals(""))
        {
            throw  new MarkerMetException(500,"轨道衡类型名称不能为空");
        }
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();
        if(StringUtils.isEmpty(model.getRailwayPk())) {
            model.setCreateTime(new Date());
            model.setCreateManNo(userId);
            model.setCreateManName(userName);
            model.setValueFlag(DbConstants.VALID);
        }else {
            model.setUpdateTime(new Date());
            model.setUpdateManNo(userId);
            model.setUpdateManName(userName);
        }
    }

    //==================eason add 2021-04-01=====================
    @Override
    @Transactional(rollbackFor=Exception.class)
    public int doSaveWf(List<MeterBaseRailwayWeight> models) throws ParseException {
        int num=0;
        if (models.size() <= 0 || models == null){
            throw  new MarkerMetException(500,"参数不能为空！！");
        }

        Date date = new Date();
        String strYear= new SimpleDateFormat("yyyy").format(new Date());
        String strMouth = new SimpleDateFormat("MM").format(new Date());
        String strDay = new SimpleDateFormat("dd").format(new Date());

        Calendar cl = Calendar.getInstance();
        cl.setTime(date);

        Date endTime=null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        switch (strDay.substring(0,1)){
            case "0":
                endTime = simpleDateFormat.parse(strYear+"-"+strMouth+"-10 23:59:59");
                break;
            case "1":
                endTime = simpleDateFormat.parse(strYear+"-"+strMouth+"-20 23:59:59");
                break;
            case "2":
            {
                if("02".equals(strMouth)){
                    endTime = simpleDateFormat.parse(strYear+"-03-10 23:59:59");
                }else{
                    endTime = simpleDateFormat.parse(strYear+"-"+strMouth+"-30 23:59:59");
                }
            }; break;
            case "3":
            {
                cl.add(Calendar.MONTH,1);
                endTime = simpleDateFormat.parse(new SimpleDateFormat("yyyy-MM").format(new Date())+"-10 23:59:59");
            }; break;
        }



        Map<String,Object> mp=new HashMap<>();
        for(MeterBaseRailwayWeight model:models){
            //查一次是否存在相同的，存在则更新，不存在则新增
            mp.clear();
            mp.put("tareTypeNo",model.getTareTypeNo());
            mp.put("railwayTypeNo",model.getRailwayTypeNo());
            List<MeterBaseRailwayWeight> lmbrw=meterBaseRailwayWeightMapper.selectByParameters(mp);
            BigDecimal i= model.getRailwayWeight()!=null?model.getRailwayWeight():BigDecimal.valueOf(0);
            if(lmbrw.size()==0){ //新增
                String no=meterBaseRailwayWeightMapper.GetNewID();
                model.setRailwayPk(new SimpleDateFormat("yyyyMMdd").format(new Date())+no);
                model.setCreateTime(new Date());
                model.setStartTime(new Date());
                model.setEndTime(endTime);

                model.setRailwayWeight(i);
                //model.setTermValidity(0);
                model.setRailwayType("0"); //内部
                model.setValueFlag("1");

                meterBaseRailwayWeightMapper.insertSelective(model);
            }else{ //修改
                model.setRailwayWeight(i);
                model.setRailwayPk(lmbrw.get(0).getRailwayPk());
                model.setUpdateTime(new Date());
                model.setUpdateManNo(model.getCreateManNo()+"");
                model.setUpdateManName(model.getCreateManName()+"");
                model.setCreateManNo(null);
                model.setCreateManName(null);
                model.setStartTime(new Date());
                model.setEndTime(endTime);
                //model.setTermValidity(0);
                meterBaseRailwayWeightMapper.updateByPrimaryKeySelective(model);
            }
            num++;
        }
        return num;
    }
    //============================================================
}
