package com.steerinfo.pretrack.pretrackscale.service.impl;

import com.steerinfo.appservice.apppretrackscale.service.impl.AppPreTrackScaleServiceImpl;
import com.steerinfo.baseinfo.meterbasecarblacelist.mapper.MeterBaseCarBlacelistMapper;
import com.steerinfo.baseinfo.meterbasecarblacelist.model.MeterBaseCarBlacelist;
import com.steerinfo.baseinfo.meterbasecarrierunitcar.mapper.MeterBaseCarrierUnitCarMapper;
import com.steerinfo.baseinfo.meterbasecarrierunitcar.model.MeterBaseCarrierUnitCar;
import com.steerinfo.baseinfo.meterbasecussupcar.mapper.MeterBaseCusSupCarMapper;
import com.steerinfo.baseinfo.meterbasecussupcar.model.MeterBaseCusSupCar;
import com.steerinfo.baseinfo.meterbaselimitchemical.mapper.MeterBaseLimitChemicalMapper;
import com.steerinfo.baseinfo.meterbaselimitchemical.model.MeterBaseLimitChemical;
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.meterwork.except.MarkerMetException;
import com.steerinfo.meterwork.meterworkcarcheck.mapper.MeterWorkCarCheckMapper;
import com.steerinfo.meterwork.meterworkcarcheck.model.MeterWorkCarCheck;
import com.steerinfo.meterwork.meterworkprelink.mapper.MeterWorkPreLinkMapper;
import com.steerinfo.meterwork.meterworkprelink.model.MeterWorkPreLink;
import com.steerinfo.meterwork.meterworkprelink.service.impl.MeterWorkPreLinkServiceImpl;
import com.steerinfo.meterwork.meterworkpreprocess.mapper.MeterWorkPreProcessMapper;
import com.steerinfo.meterwork.meterworkpreprocess.model.MeterWorkPreProcess;
import com.steerinfo.pretrack.constants.DbConstants;
import com.steerinfo.pretrack.pretracknotice.mapper.PreTrackNoticeMapper;
import com.steerinfo.pretrack.pretracknotice.model.PreTrackNotice;
import com.steerinfo.pretrack.pretrackscale.mapper.PreTrackScaleMapper;
import com.steerinfo.pretrack.pretrackscale.model.PreTrackScale;
import com.steerinfo.pretrack.pretrackscale.service.IPreTrackScaleService;
import com.steerinfo.util.DoChinFilters;
import com.steerinfo.util.FieldsCollector;
import com.steerinfo.util.StringUtils;
import oracle.jdbc.proxy.annotation.Pre;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

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

    /**
     * 合同接口
     */
    @Resource
    private PreTrackNoticeMapper preTrackNoticeMapper;

    /**
     * 门岗核查
     */
    @Resource
    private MeterWorkCarCheckMapper meterWorkCarCheckMapper;

    /**
     * 危化品配置信息
     */
    @Resource
    private MeterBaseLimitChemicalMapper meterBaseLimitChemicalMapper;

    @Resource
    private PreTrackScaleMapper preTrackScaleMapper;

    @Resource
    private MeterWorkPreLinkMapper meterWorkPreLinkMapper;

    @Resource
    private MeterBaseCusSupCarMapper meterBaseCusSupCarMapper;

    @Resource
    private MeterBaseCarrierUnitCarMapper meterBaseCarrierUnitCarMapper;

    @Resource
    private MeterWorkPreProcessMapper meterWorkPreProcessMapper;

    @Autowired
    public MeterWorkPreLinkServiceImpl meterWorkPreLinkServiceImpl;

    @Autowired
    public AppPreTrackScaleServiceImpl appPreTrackScaleServiceImpl;

    @Resource
    private MeterBaseCarBlacelistMapper meterBaseCarBlacelistMapper;


    @Override
    protected IBaseMapper<PreTrackScale, String> getMapper() {
        return preTrackScaleMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<PreTrackScale> selectlist(String carNo) throws MarkerMetException {
        try {
            if (StringUtils.isEmpty(carNo)) {
                throw new MarkerMetException(500, "车号为空!!");
            }
            List<PreTrackScale> list = preTrackScaleMapper.selectlist(carNo);
            return list;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    public PageList<PreTrackScale> likeByDesc(Map<String, Object> parameters, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PreTrackScale> rows = preTrackScaleMapper.likeByDesc(parameters);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public PageList<PreTrackScale> likeByList(Map<String, Object> parameters, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PreTrackScale> rows = preTrackScaleMapper.likeByList(parameters);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public PageList<PreTrackScale> webLikeByDesc(Map<String, Object> parameters, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PreTrackScale> rows = preTrackScaleMapper.webLikeByDesc(parameters);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public List<PreTrackScale> noPageDesc(Map<String, Object> params) {
        List<PreTrackScale> rows = preTrackScaleMapper.noPageDesc(params);
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<PreTrackScale> selectView(HashMap param) {
        return preTrackScaleMapper.selectView(param);
    }

    /**
     * 新增非计量的数据
     *
     * @param scale
     * @return
     */
    @Override
    @Transactional
    public PreTrackScale checkandaddNotMetter(PreTrackScale scale) {
        checkNotWeight(scale);
        scale.setCarNo(scale.getCarNo().toUpperCase(Locale.ROOT).trim());
        scale.setCarAllocationTime(new Date());
        scale.setValueFlag(DbConstants.NOT);
        scale.setCreateTime(new Date());

        if (StringUtils.isEmpty(scale.getCreateManNo())) {
            UserPayload payload = UserPayload.getCurrUser();
            String userId = payload.getUserCode();
            String userName = payload.getUserName();
            scale.setCreateTime(new Date());
            scale.setCreateManNo(userId);
            scale.setCreateManName(userName);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String no = preTrackScaleMapper.getNewID(sdf.format(new Date()));
        scale.setPredictionNo(sdf.format(new Date()) + no);
        preTrackScaleMapper.insertSelective(scale);

        return scale;
    }

    @Override
    @Transactional
    public PreTrackScale checkandadd(PreTrackScale model) {
        check(model);
        if (StringUtils.isEmpty(model.getCarNo())) {
            model.setValueFlag(DbConstants.NOCAR);
        } else {
            //2021年3月15日 杨秀东注释，网页端新增预报时，不存在的车号也可以进行新增；
            //checkCarNo(model.getCarNo(), model.getCustomerSupplierNo(), model.getCarrierUnitNo());
            model.setCarNo(model.getCarNo().toUpperCase(Locale.ROOT).trim());
            model.setCarAllocationTime(new Date());
            model.setValueFlag(DbConstants.NOT);
        }
        //2021年3月15日 验证合同号是否存在系统中；PRE_TRACK_NOTICE
        if (StringUtils.isNotEmpty(model.getContractNo())
                && (!"001006006".equals(model.getMeterTypeNo()) && !"001006003".equals(model.getMeterTypeNo()))) {
            Map<String, Object> map = new HashMap<>();
            map.put("contractNo", model.getContractNo());
            List<PreTrackNotice> noticeList = preTrackNoticeMapper.selectByParameters(map);
            if (noticeList == null || noticeList.size() == 0) {
                throw new MarkerMetException(500, "未查询到合同号[" + model.getContractNo() + "]的信息，不允许进行预报新增!!");
            }
        }
        //预报条数验证
        if (StringUtils.isNotEmpty(model.getCarNo())) {
            PreTrackScale chek = new PreTrackScale();
            chek.setValueFlag("1");
            chek.setCarNo(model.getCarNo());
            Map<String, Object> map = FieldsCollector.beanToMap(chek);
            List<PreTrackScale> scaleList = preTrackScaleMapper.selectByParameters(map);
            if (scaleList != null && scaleList.size() > 0) {
                throw new MarkerMetException(500, "车号[" + model.getCarNo() + "]存在[" + scaleList.size() + "]条有效的" + DbConstants.typePurchase + "预报数据，" +
                        "不允许继续新增，请先在小程序作废不使用的预报!!");
            }
        }
        if (StringUtils.isEmpty(model.getPredictionNo())) {
            UserPayload payload = UserPayload.getCurrUser();
            String userId = payload.getUserCode();
            String userName = payload.getUserName();
            model.setCreateTime(new Date());
            model.setCreateManNo(userId);
            model.setCreateManName(userName);
        } else {
            model.setUpdateTime(new Date());
        }
        if (StringUtils.isNotEmpty(model.getCarNo())) {
            checkCarNoBlackList(model.getCarNo());
        }
        if (model.getUsedType().equals(DbConstants.NUM)) {
            model.setMeterNum(0);
        }
        if (model.getUsedType().equals(DbConstants.COUNT)) {
            model.setMeterWeight(new BigDecimal(0));
        }
        if (StringUtils.isEmpty(model.getPredictionNo())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String no = preTrackScaleMapper.getNewID(sdf.format(new Date()));
            model.setPredictionNo(sdf.format(new Date()) + no);
        }
        preTrackScaleMapper.insertSelective(model);
        //对预流程、预环节进行相应操作,配车的相应操作
        allocation(model);
        //2021年5月3日对门岗核查信息及危化品进行处理  2022.1.21注释创建预报新增车辆核查信息的语句
        if (StringUtils.isNotEmpty(model.getCarNo())) {
//            addCarCheckInfo(model);
        }
        return model;
    }


    @Transactional
    public PreTrackScale checkandaddApp(PreTrackScale model) {
        if (model == null) {
            throw new MarkerMetException(500, "参数为空!!");
        }
        check(model);
        if (StringUtils.isEmpty(model.getCarNo())) {
            model.setValueFlag(DbConstants.NOCAR);
        } else {
            model.setCarNo(model.getCarNo().toUpperCase(Locale.ROOT).trim());
            model.setCarAllocationTime(new Date());
            model.setValueFlag(DbConstants.NOT);
            checkCarNoBlackList(model.getCarNo());
        }
        if (model.getUsedType().equals(DbConstants.NUM)) {
            model.setMeterNum(0);
        }
        if (model.getUsedType().equals(DbConstants.COUNT)) {
            model.setMeterWeight(new BigDecimal(0));
        }
        if (StringUtils.isEmpty(model.getPredictionNo())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String no = preTrackScaleMapper.getNewID(sdf.format(new Date()));
            model.setPredictionNo(sdf.format(new Date()) + no);
        }
        //2021年5月3日对门岗核查信息及危化品进行处理  2022.1.21注释创建预报新增车辆核查信息的语句
        if (StringUtils.isNotEmpty(model.getCarNo())) {
//            addCarCheckInfo(model);
        }

        preTrackScaleMapper.insertSelective(model);
        //对预流程、预环节进行相应操作,配车的相应操作
        if (StringUtils.isNotEmpty(model.getCarNo())) {
            allocation(model);
        }
        return model;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PreTrackScale checkandupdate(PreTrackScale model) {
        if (model == null) {
            throw new MarkerMetException(500, "参数为空!!");
        }
        if (model.getValueFlag().equals("2") || model.getValueFlag().equals("3") || model.getValueFlag().equals("4")) {
            throw new MarkerMetException(500, "该状态不允许修改!!");
        }
        PreTrackScale pts = preTrackScaleMapper.selectByPrimaryKey(model.getPredictionNo());
        if (StringUtils.isNotEmpty(pts.getCarNo())) {
            List<MeterWorkPreLink> meterWorkPreLink = meterWorkPreLinkServiceImpl.getNextFlag(pts.getPredictionNo(), DbConstants.APPOINTMENT);
            if (meterWorkPreLink.size() > 0) {
                if (meterWorkPreLink.get(0).getValueFlag().equals("1")) {
                    throw new MarkerMetException(500, "下一步环节已执行，无法修改!!");
                }
            }
            //对预流程、预环节进行删除
            canceleAllocation(pts);
        }
        preTrackScaleMapper.deleteByPrimaryKey(pts.getPredictionNo());
        checkandadd(model);
        return model;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int setPreIndex(PreTrackScale scale) {
        try {
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("predictionNo", scale.getPredictionNo());
            obj.put("carNo", scale.getCarNo());
//            List<PreTrackScale> com = preTrackScaleMapper.selectValueFlag(obj);
//            if(com.size()>0){
//                return -1;
//            }
            // 将该车已选为当次的委托重置为未选中
            List <PreTrackScale> preList = preTrackScaleMapper.selectuselist(scale.getCarNo());
            if (preList.size() > 0) {
                for (PreTrackScale pres : preList) {
                    pres.setLineDesc("0");
                    preTrackScaleMapper.updateByPrimaryKeySelective(pres);
                }
            }

            // 设置选中
            scale.setLineDesc("1");
            int num = preTrackScaleMapper.updateByPrimaryKeySelective(scale);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<PreTrackScale> selectInUseAndNoUse(HashMap<String, Object> model) {
        String carNo = model.get("carNo") == null ? "": model.get("carNo").toString();
        if (StringUtils.isEmpty(carNo)) {
            throw new MarkerMetException(500, "车号为空!!");
        }
        List<PreTrackScale> scales = preTrackScaleMapper.selectInUseAndNoUse(model);
        return scales;
    }

    @Override
    public PageList<PreTrackScale> findCarScale(HashMap param) {
        String predictionNo = param.get("predictionNo") == null ? "": param.get("predictionNo").toString();
        if(StringUtils.isEmpty(predictionNo)) {
            return null;
        }
        List<PreTrackScale> list = preTrackScaleMapper.selectByParameters(param);
        PageList pageInfo = new PageList(list);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int abolish(List<PreTrackScale> models) {
        try {
            int num = 0;
            if (models.size() <= 0 || models.isEmpty()) {
                throw new MarkerMetException(500, "参数为空!!");
            }
            for (PreTrackScale model : models) {
                if (model == null) {
                    throw new MarkerMetException(500, "参数为空!!");
                }
                if (StringUtils.isEmpty(model.getPredictionNo())) {
                    throw new MarkerMetException(500, "预报编号不允许为空!!");
                }
                if (StringUtils.isEmpty(model.getPredictionType())) {
                    throw new MarkerMetException(500, "预报类型(0：批次预报；1：单次预报；2：联运预报)不允许为空!!");
                }
                if ("2".equals(model.getPredictionType()) && StringUtils.isNotEmpty(model.getPredictionCombination())) {
                    throw new MarkerMetException(500, "预报类型为2：联运预报时，预报组合号不允许为空!!");
                }
            }
            for (PreTrackScale model : models) {
                PreTrackScale preTrackScale = preTrackScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                if (preTrackScale.getValueFlag().equals(DbConstants.USE) || preTrackScale.getValueFlag().equals(DbConstants.IN)) {
                    throw new MarkerMetException(500, "已使用或正使用的预报无法删除!!");
                }
                //联运预报清除掉已作废的组合数据
                if (model.getPredictionType().equals(DbConstants.COM_PRE) && StringUtils.isNotEmpty(model.getPredictionCombination())) {
                    HashMap<String, Object> obj = new HashMap<>();
                    obj.put("predictionCombination", preTrackScale.getPredictionCombination());
                    List<PreTrackScale> ptss = preTrackScaleMapper.selectByParameters(obj);
                    if (ptss.size() > 0) {
                        String[] str = preTrackScale.getPredictionCombination().split(",");
                        String no = DoChinFilters.doChinFilters(str, preTrackScale.getPredictionNo());
                        for (PreTrackScale pts : ptss) {
                            pts.setPredictionCombination(no);
                        }
                        preTrackScaleMapper.batchUpdateSelective(ptss);
                    }
                    model.setPredictionType("1");
                }
                model.setPredictionCombination("");
                model.setpValueFlag(model.getValueFlag());
                model.setValueFlag(DbConstants.DROP);
                model.setUpdateTime(new Date());
                model.setUploadFlag("1");
                num++;
            }
            preTrackScaleMapper.batchUpdateSelective(models);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int recover(List<PreTrackScale> models) {
        try {
            int num = 0;
            if (models.isEmpty()) {
                throw new MarkerMetException(500, "参数为空!!");
            }
            for (PreTrackScale model : models) {
                if (StringUtils.isNotEmpty(model.getpValueFlag())) {
                    model.setValueFlag(model.getpValueFlag());
                } else {
                    model.setValueFlag("1");
                }
                model.setUploadFlag("1");
                num++;
            }
            preTrackScaleMapper.batchUpdateSelective(models);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int combined(List<PreTrackScale> models) {
        try {
            int num = 0;
            if (models.isEmpty()) {
                throw new MarkerMetException(500, "参数为空!!");
            }
            //取得第一个车号
            String carno = models.get(0).getCarNo();
            String meterTypeNo = models.get(0).getMeterTypeNo();
            //将所有的预报编号结合
            String str = "";
            for (PreTrackScale model : models) {
                if (!model.getPredictionType().equals(DbConstants.SINGLE)) {
                    throw new MarkerMetException(500, "存在非单次预报的数据，无法混装，请确认!!");
                }
                if (!model.getValueFlag().equals(DbConstants.NOT)) {
                    throw new MarkerMetException(500, "未使用的数据才可混装，请确认!!");
                }
                if (!model.getCarNo().equals(carno)) {
                    throw new MarkerMetException(500, "存在车号不同的数据，请确认!!");
                }
                if (!model.getMeterTypeNo().equals(meterTypeNo)) {
                    throw new MarkerMetException(500, "存在业务类型不同的数据，请确认!!");
                }
                if (num == 0) {
                    str = str + model.getPredictionNo();
                } else {
                    str = str + "," + model.getPredictionNo();
                }
                num++;
            }
            for (PreTrackScale model : models) {
                model.setPredictionType(DbConstants.COM_PRE);
                model.setPredictionCombination(str);
            }
            preTrackScaleMapper.batchUpdateSelective(models);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    @Transactional
    public int remove(List<PreTrackScale> models) {
        try {
            int num = 0;
            if (models.isEmpty()) {
                throw new MarkerMetException(500, "参数为空!!");
            }
            for (PreTrackScale model : models) {
                if (!(DbConstants.COM_PRE).equals(model.getPredictionType())) {
                    throw new MarkerMetException(500, "存在非联运预报的信息，无法解除!!");
                }
                //查询出同样的联运
                PreTrackScale preTrackScale = preTrackScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                HashMap<String, Object> obj = new HashMap<>();
                obj.put("predictionCombination", preTrackScale.getPredictionCombination());
                List<PreTrackScale> ptss = preTrackScaleMapper.selectByParameters(obj);
                if (ptss.size() > 0) {
                    String[] str = preTrackScale.getPredictionCombination().split(",");
                    String no = DoChinFilters.doChinFilters(str, preTrackScale.getPredictionNo());
                    for (PreTrackScale pts : ptss) {
                        pts.setPredictionCombination(no);
                    }
                    preTrackScaleMapper.batchUpdateSelective(ptss);
                }
                num++;
            }
            for (PreTrackScale model : models) {
                model.setPredictionCombination("");
                model.setPredictionType(DbConstants.SINGLE);
            }
            preTrackScaleMapper.batchUpdateSelective(models);
            return num;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    public RESTfulResult doQueryWf(HashMap parmas) {
        RESTfulResult rm = new RESTfulResult();
        try {
            rm.setCode("200");
            rm.setData(preTrackScaleMapper.selectBy(parmas));
        } catch (Exception ex) {
            rm.setCode("500");
            rm.setMessage("查询失败：" + ex.getMessage());
        }
        return rm;
    }

    /**
     * 检查数据是否符合要求
     *
     * @param model
     * @throws MarkerMetException
     */
    private void check(PreTrackScale model) throws MarkerMetException {
        checkNotWeight(model);
        if (model.getMatterName() == null || model.getMatterName().equals("")) {
            throw new MarkerMetException(500, "物料名称为空!!");
        }
        if ("连铸坯".equals(model.getMatterName()) && model.getReceivingUintName().equals(model.getForwardingUnitName())){
            throw new MarkerMetException(500, "物资名称为【连铸坯】，收货单位与发货单位相同，不允许做预报!!");
        }
    }

    /**
     * 检查数据是否符合要求
     *
     * @param model
     * @throws MarkerMetException
     */
    private void checkNotWeight(PreTrackScale model) throws MarkerMetException {
        if (model == null) {
            throw new MarkerMetException(500, "参数不允许为空!!");
        }
        if (StringUtils.isEmpty(model.getCarNo())) {
            throw new MarkerMetException(500, "车号不允许为空!!");
        }

        if (model.getMeterTypeNo() == null || model.getMeterTypeNo().equals("")) {
            throw new MarkerMetException(500, "业务类型编号为空!!");
        }
        if (model.getMeterTypeName() == null || model.getMeterTypeName().equals("")) {
            throw new MarkerMetException(500, "业务类型名称为空!!");
        }
        if (model.getCustomerSupplierNo() == null || model.getCustomerSupplierNo().equals("")) {
            throw new MarkerMetException(500, "供应商/客户编码为空!!");
        }
        if (StringUtils.isEmpty(model.getUsedType())) {
            throw new MarkerMetException(500, "预报使用类型不允许为空!!");
        }
    }

    //预报配车
    public void allocation(PreTrackScale model) throws MarkerMetException {
        if (model == null) {
            throw new MarkerMetException(500, "参数为空!!");
        }
        MeterWorkPreProcess mwpp = meterWorkPreProcessMapper.selectByType(model.getMeterTypeNo(), model.getMeterTypeName(), model.getPredictionNo());
        if (mwpp == null) {
            throw new MarkerMetException(500, "该业务类型未配流程");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String no = meterWorkPreProcessMapper.getNewID();
        mwpp.setPreProcessNo(sdf.format(new Date()) + no);
        mwpp.setValueFlag("1");//正使用
        //获取当前登录人以及时间
        mwpp.setCreateTime(new Date());
        mwpp.setCreateManNo(model.getCreateManNo());
        mwpp.setCreateManName(model.getCreateManName());
        //插入预流程表
        meterWorkPreProcessMapper.insertSelective(mwpp);
        //获取该流程下的所有环节
        List<MeterWorkPreLink> mwpls = meterWorkPreLinkMapper.selectByType(mwpp.getProcessNo(), mwpp.getPreProcessNo());
        if (mwpls.size() <= 0) {
            throw new MarkerMetException(500, "该业务类型未配环节");
        }
        for (MeterWorkPreLink mwpl : mwpls) {
            String no1 = meterWorkPreLinkMapper.getNewID(sdf.format(new Date()));
            mwpl.setPreLinkNo(sdf.format(new Date()) + no1);
            mwpl.setCreateTime(new Date());
            mwpl.setCreateManNo(model.getCreateManNo());
            mwpl.setCreateManName(model.getCreateManName());
            if (mwpl.getSeqNo() == 1 && mwpl.getLinkCode().equals(DbConstants.APPOINTMENT)) {
                mwpl.setValueFlag("1");//已使用
            } else {
                mwpl.setValueFlag("0");//待使用
            }
            meterWorkPreLinkMapper.insertSelective(mwpl);
        }
    }

    //删除预报配车
    public void canceleAllocation(PreTrackScale model) {
        if (model == null) {
            throw new MarkerMetException(500, "参数为空!!");
        }
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("predictionNo", model.getPredictionNo());
        obj.put("carNo", model.getCarNo());
        obj.put("meterTypeNo", model.getMeterTypeNo());
        List<MeterWorkPreProcess> mwpp = meterWorkPreProcessMapper.selectByParameters(obj);
        if (mwpp.size() > 0) {
            HashMap<String, Object> obj1 = new HashMap<>();
            obj1.put("predictionNo", mwpp.get(0).getPredictionNo());
            obj1.put("processNo", mwpp.get(0).getProcessNo());
            obj1.put("preProcessNo", mwpp.get(0).getPreProcessNo());
            List<MeterWorkPreLink> mwpls = meterWorkPreLinkMapper.selectByParameters(obj1);
            if (mwpls.size() > 0) {
                ArrayList<String> ids = new ArrayList<>();
                for (MeterWorkPreLink mwpl : mwpls) {
                    ids.add(mwpl.getPreLinkNo());
                }
                meterWorkPreLinkMapper.batchDelete(ids);
            }
            meterWorkPreProcessMapper.deleteByPrimaryKey(mwpp.get(0).getPreProcessNo());
        }
    }

    //判断车号是否为黑名单
    private void checkCarNoBlackList(String carNo) {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("carNo", carNo);
        obj.put("valueFlag", "0");
        List<MeterBaseCarBlacelist> list = meterBaseCarBlacelistMapper.selectByParameters(obj);
        if (list.size() >= 1) {
            throw new MarkerMetException(500, "该车在黑名单中，不允许新增!!");
        }
    }

    //检查车号是否在供应商或者承运单位的车辆中
    private void checkCarNo(String carNo, String customerSupplierNo, String carrierUnitNo) throws MarkerMetException {
        if (StringUtils.isEmpty(customerSupplierNo)) {
            throw new MarkerMetException(500, "供应商为空!!");
        }
        //是否在供应商车辆中
        HashMap<String, Object> obj1 = new HashMap<>();
        obj1.put("cusSupCarNo", carNo);
        obj1.put("customerSupplierNo", customerSupplierNo);
        List<MeterBaseCusSupCar> mbcscs = meterBaseCusSupCarMapper.selectByParameters(obj1);
        //是否在承运单位车辆中
        List<MeterBaseCarrierUnitCar> mbcucs = new ArrayList<>();
        if (StringUtils.isNotEmpty(carrierUnitNo)) {
            HashMap<String, Object> obj2 = new HashMap<>();
            obj2.put("cusSupCarNo", carNo);
            obj2.put("carrierUnitNo", carrierUnitNo);
            mbcucs = meterBaseCarrierUnitCarMapper.selectByParameters(obj2);
        }
        //均不存在则不允许
        if (mbcscs.isEmpty() && mbcucs.isEmpty()) {
            throw new MarkerMetException(500, "承运单位和供应商均不存在该车号，请填入正确的车号!!");
        }
    }


    @Override
    @Transactional
    public int addList(List<PreTrackScale> models) throws Exception {
        if (models == null) {
            throw new MarkerMetException(500, "参数为空！！");
        }
        int num = 0;
        for (PreTrackScale model : models) {
            checkandadd(model);
            num++;
        }
        return num;
    }



    /**
     * 新增门岗检查信息，同时也用作危化品处理的数据
     *
     * @param model
     * @throws MarkerMetException
     */
    public void addCarCheckInfo(PreTrackScale model) throws MarkerMetException {
        if (model == null || StringUtils.isEmpty(model.getPredictionNo())) {
            throw new MarkerMetException(500, "预报编号为空，新增门岗核查信息失败!!");
        }
        //核验是否为危化品车辆及危化品物资
        List<MeterBaseLimitChemical> limitChemicalList = new ArrayList<>();
        if (StringUtils.isNotEmpty(model.getMatterNo())) {
            MeterBaseLimitChemical chemical = new MeterBaseLimitChemical();
            chemical.setMatterNo(model.getMatterNo());
            limitChemicalList = meterBaseLimitChemicalMapper.selectLikeByParameters(FieldsCollector.beanToMap(chemical));
        }
        MeterWorkCarCheck meterWorkCarCheck = meterWorkCarCheckMapper.selectByPrimaryKey(model.getPredictionNo());
        if (meterWorkCarCheck == null) {
            meterWorkCarCheck = new MeterWorkCarCheck();
        }
        meterWorkCarCheck.setCarNo(model.getCarNo());
        meterWorkCarCheck.setMnemonicCode(model.getTrailerNo());
        meterWorkCarCheck.setCustomerSupplierNo(model.getCustomerSupplierNo());
        meterWorkCarCheck.setCustomerSupplierName(model.getCustomerSupplierName());
        if (limitChemicalList != null && limitChemicalList.size() > 0) {
            meterWorkCarCheck.setTransportChemical("0"); //是否可运危化品（0=是；1=否）
            meterWorkCarCheck.setLimitWeight(limitChemicalList.get(0).getLimitWeight()); //限载重量
        }
        if (meterWorkCarCheck != null && StringUtils.isNotEmpty(meterWorkCarCheck.getPredictionNo())) {
            meterWorkCarCheckMapper.updateByPrimaryKeySelective(meterWorkCarCheck);
        } else {
            meterWorkCarCheck.setPredictionNo(model.getPredictionNo());
            if (StringUtils.isEmpty(meterWorkCarCheck.getPkNo())) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                String afl = formatter.format(new Date());
                String no = meterWorkCarCheckMapper.getNewID(afl);
                meterWorkCarCheck.setPkNo(afl + no);
            }
            meterWorkCarCheckMapper.insertSelective(meterWorkCarCheck);
        }
    }

    //定时作废到期的预报；预报作废
//    @Scheduled(cron = " 0 */60 * * * ?") //定时任务(每天凌晨一点执行一次)/作废预报；定时服务打包时启用
    @Transactional
    public void updateValueFlagForTime() {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("predictionType", "0");//批次预报
        obj.put("usedType", "1");//时间
        List<PreTrackScale> ptss = preTrackScaleMapper.selectByParameters(obj);
        for (PreTrackScale pts : ptss) {
            if (pts.getEffectiveEndTime().before(new Date())) {
                pts.setValueFlag("2");
            }
            pts.setUploadFlag("1");
            preTrackScaleMapper.updateByPrimaryKeySelective(pts);
        }
    }


    //定时作废到期的预报；预报作废
//    @Scheduled(cron = " 0 */60 * * * ?") //定时任务(每天凌晨一点执行一次)/作废预报；定时服务打包时启用 @Scheduled(cron = "0/1 * * * * ?")
    @Transactional
    public void updateValueFlagByMatter() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<PreTrackScale> ptss = preTrackScaleMapper.selectScaleValidPeriod();
        //system.out.println("updateValueFlagByMatter接口自动作废在" + sdf.format(new Date()) + "已经执行");
        for (PreTrackScale pts : ptss) {
            PreTrackScale scale = new PreTrackScale();
            scale.setPredictionNo(pts.getPredictionNo());
            scale.setValueFlag("3");
            scale.setUploadFlag("1");
            scale.setUpdateManNo("admin");
            scale.setUpdateManName("updateValueFlagByMatter接口自动作废");
            scale.setUpdateTime(new Date());
            //system.out.println("updateValueFlagByMatter接口自动作废" + scale.getPredictionNo());
            preTrackScaleMapper.updateByPrimaryKeySelective(scale);
            pts.setValueFlag("3");
        }
        //system.out.println("updateValueFlagByMatter接口自动作废在" + sdf.format(new Date()) + "执行完成");
    }

    @Override
    public List<PreTrackScale> selectByCarNo(String carNo, String valueFlag) {
        try {
            if (StringUtils.isEmpty(carNo)) {
                throw new MarkerMetException(500, "车号为空!!");
            }
            List<PreTrackScale> list = preTrackScaleMapper.selectByCarNo(carNo, valueFlag);
            return list;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    public List<PreTrackScale> selectByCar(String carNo) {
        try {
            if (StringUtils.isEmpty(carNo)) {
                throw new MarkerMetException(500, "车号为空!!");
            }
            List<PreTrackScale> list = preTrackScaleMapper.selectByCar(carNo);
            return list;
        } catch (MarkerMetException e) {
            throw e;
        }
    }
}
