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

import com.steerinfo.baseinfo.combaseinfo.mapper.ComBaseInfoMapper;
import com.steerinfo.baseinfo.combaseinfo.model.ComBaseInfo;
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.pretrack.constants.DbConstants;
import com.steerinfo.pretrack.dto.PreRailwayScaleDto;
import com.steerinfo.pretrack.prerailwayscale.mapper.PreRailwayScaleMapper;
import com.steerinfo.pretrack.prerailwayscale.model.PreRailwayScale;
import com.steerinfo.pretrack.prerailwayscale.service.IPreRailwayScaleService;
import com.steerinfo.pretrack.pretrackscale.model.PreTrackScale;
import com.steerinfo.util.DoChinFilters;
import com.steerinfo.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.text.SimpleDateFormat;
import java.util.*;

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

    @Resource
    private PreRailwayScaleMapper preRailwayScaleMapper;

    @Resource
    private ComBaseInfoMapper comBaseInfoMapper;

    @Override
    protected IBaseMapper<PreRailwayScale, String> getMapper() {
        return preRailwayScaleMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageList<PreRailwayScale> selectlist(String railwayNo, Integer pageNum, Integer pageSize) {
        if (railwayNo == null && "".equals(railwayNo)) {
            throw new MarkerMetException(500, "车号为空!!");
        }
        PageHelper.startPage(pageNum, pageSize);
        List<PreRailwayScale> list = preRailwayScaleMapper.selectlist(railwayNo);
        PageList pageInfo = new PageList(list);
        return pageInfo;
    }

    @Override
    @Transactional
    public PageList<PreRailwayScale> selectView(HashMap param, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PreRailwayScale> rows = preRailwayScaleMapper.selectView(param);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    @Transactional
    public String checkandadd(PreRailwayScale model) {
        if (model == null) {
            throw new MarkerMetException(500, "参数为空!!");
        }
        check(model);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String afl = sdf.format(model.getCreateTime());
        String no = preRailwayScaleMapper.getNewID(afl);
        model.setPredictionNo("T" + afl + no);
        preRailwayScaleMapper.insertSelective(model);
        return model.getPredictionNo();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PreRailwayScale checkandupdate(PreRailwayScale model) throws MarkerMetException {
        try {
            if (model == null) {
                throw new MarkerMetException(500, "参数为空!!");
            }
            if (model.getValueFlag().equals("2") || model.getValueFlag().equals("3") || model.getValueFlag().equals("4")) {
                throw new MarkerMetException(500, "该状态不允许修改!!");
            }
            check(model);
            preRailwayScaleMapper.updateByPrimaryKey(model);
            return model;
        } catch (MarkerMetException e) {
            throw e;
        }
    }

    @Override
    @Transactional
    public int abolish(List<PreRailwayScale> models) {
        int num = 0;
        String userId = "";
        String userName = "";
        if (models.size() <= 0 || models.isEmpty()) {
            throw new MarkerMetException(500, "参数为空!!");
        }
        //更新人信息
        /*if (UserPayload.getCurrUser() != null) {
            UserPayload payload = UserPayload.getCurrUser();
            userId = payload.getUserCode();
            userName = payload.getUserName();
        }*/

        for (PreRailwayScale model : models) {
            if (model.getValueFlag().equals(DbConstants.USE)) {
                throw new MarkerMetException(500, "已使用状态无法删除!!");
            }
            if (model.getPredictionType().equals(DbConstants.COM_PRE)) {
                PreRailwayScale preTrackScale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
                HashMap<String, Object> obj = new HashMap<>();
                obj.put("predictionCombination", preTrackScale.getPredictionCombination());
                List<PreRailwayScale> ptss = preRailwayScaleMapper.selectByParameters(obj);
                String[] str = preTrackScale.getPredictionCombination().split(",");
                String no = DoChinFilters.doChinFilters(str, preTrackScale.getPredictionNo());
                if (ptss.size() > 0) {
                    for (PreRailwayScale pts : ptss) {
                        pts.setPredictionCombination(no);
                    }
                    preRailwayScaleMapper.batchUpdateSelective(ptss);
                }
                model.setPredictionCombination("");
            }
            model.setpValueFlag(model.getValueFlag());
            model.setValueFlag(DbConstants.DROP);
            model.setUploadFlag("1");
            /*model.setUpdateManNo(userId);
            model.setUpdateManName(userName);*/
            model.setUpdateTime(new Date());
            num++;
        }
        preRailwayScaleMapper.batchUpdateSelective(models);
        return num;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int recover(List<PreRailwayScale> models) {
        int num = 0;
        if (models.size() <= 0 || models.isEmpty()) {
            throw new MarkerMetException(500, "参数为空!!");
        }
        for (PreRailwayScale model : models) {
            model.setValueFlag("1"); //直接恢复到未使用状态
            model.setUploadFlag("1");
            model.setUpdateTime(new Date());
            num++;
        }
        preRailwayScaleMapper.batchUpdateSelective(models);
        return num;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int combined(List<PreRailwayScale> models) {
        int num = 0;
        if (models.size() <= 0 || models.isEmpty()) {
            throw new MarkerMetException(500, "参数为空!!");
        }
        //取得第一个车号
        String carno = models.get(0).getRailwayNo();
        //需要修改的主键
        List<String> ids = new ArrayList<>();
        //将所有的预报编号结合
        String str = "";
        for (PreRailwayScale model : models) {
            if (!model.getPredictionType().equals(DbConstants.SINGLE)) {
                throw new MarkerMetException(500, "存在非单次预报的数据，无法联运，请确认!!");
            }
            if (!model.getValueFlag().equals(DbConstants.NOT)) {
                throw new MarkerMetException(500, "未使用的数据才可联运，请确认!!");
            }
            if (!model.getRailwayNo().equals(carno)) {
                throw new MarkerMetException(500, "存在车号不同的数据，请确认!!");
            }
            if (StringUtils.isNotEmpty(model.getPredictionCombination())) {
                String[] strs = model.getPredictionCombination().split(",");
                ids.addAll(Arrays.asList(strs));
            }
            num++;
            ids.add(model.getPredictionNo());
        }
        //编号去重
        HashSet h = new HashSet(ids);
        ids.clear();
        ids.addAll(h);
        //拼接字符串
        StringBuilder strb = new StringBuilder();
        for (int i = 0; i < ids.size(); i++) {
            if (i == 0)
                strb.append(ids.get(i));
            else
                strb.append("," + ids.get(i));
        }
        for (String id : ids) {
            PreRailwayScale preRailwayScale = new PreRailwayScale();
            preRailwayScale.setPredictionCombination(strb.toString());
            preRailwayScale.setPredictionNo(id);
            preRailwayScaleMapper.updateByPrimaryKeySelective(preRailwayScale);
        }
        return ids.size();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int remove(List<PreRailwayScale> models) {
        int num = 0;
        if (models.size() <= 0 || models.isEmpty()) {
            throw new MarkerMetException(500, "参数为空!!");
        }
        for (PreRailwayScale model : models) {
            PreRailwayScale preTrackScale = preRailwayScaleMapper.selectByPrimaryKey(model.getPredictionNo());
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("predictionCombination", preTrackScale.getPredictionCombination());
            List<PreRailwayScale> ptss = preRailwayScaleMapper.selectByParameters(obj);
            String[] str = preTrackScale.getPredictionCombination().split(",");
            String no = DoChinFilters.doChinFilters(str, preTrackScale.getPredictionNo());
            if (ptss.size() > 0) {
                for (PreRailwayScale pts : ptss) {
                    pts.setPredictionCombination(no);
                }
                preRailwayScaleMapper.batchUpdateSelective(ptss);
            }
            model.setPredictionCombination("");
            num++;
        }
        preRailwayScaleMapper.batchUpdateSelective(models);
        return num;
    }

    //检查数据是否符合要求
    private void check(PreRailwayScale model) throws MarkerMetException {
        if (model.getRailwayNo() == null || model.getRailwayNo().equals("")) {
            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.getRailwayTypeNo() == null || model.getRailwayTypeNo().equals("")) {
            throw new MarkerMetException(500, "轨道衡类型编号为空!!");
        }
        if (model.getRailwayTypeName() == null || model.getRailwayTypeName().equals("")) {
            throw new MarkerMetException(500, "轨道衡类型名称为空!!");
        }
        if (model.getPredictionNo() == null || model.getPredictionNo().equals("")){
            model.setValueFlag("1");//未使用
            model.setUploadFlag("1");
        }
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();
        if (model.getPredictionNo() == null || model.getPredictionNo().equals("")) {
            model.setCreateTime(new Date());
            model.setCreateManNo(userId);
            model.setCreateManName(userName);
        }
    }

    @Override
    public PageList<PreRailwayScale> doQueryWf(HashMap param, Integer pageNum, Integer pageSize) {
        param.put("startTime", param.get("startTime"));
        param.put("endTime", param.get("endTime"));
        PageHelper.startPage(pageNum, pageSize);
        List<PreRailwayScale> list = preRailwayScaleMapper.selectByPraAndTime(param);
        PageList pageInfo = new PageList(list);
        return pageInfo;
    }

    @Override
    public List<PreRailwayScale> doQueryByCar(HashMap param) {
        List<PreRailwayScale> list = preRailwayScaleMapper.doQueryByCar(param);
        return list;
    }

    @Override
    public List<PreRailwayScale> doQueryJLByCar(HashMap param) {
        List<PreRailwayScale> list = preRailwayScaleMapper.doQueryJLByCar(param);
        if (list == null || list.size() == 0) {
            list = preRailwayScaleMapper.doQueryJLByCarUsed(param);
        }
        return list;
    }

    @Override
    public PageList<PreRailwayScale> likeByDesc(HashMap param, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("pBaseCode", "001036");
        List<String> matterList = comBaseInfoMapper.matterNoByBaseCode(obj);
        param.put("list", matterList);
        List<PreRailwayScale> rows = preRailwayScaleMapper.likeByDesc(param);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public PageList<PreRailwayScale> likeDesc(HashMap param, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PreRailwayScale> rows = preRailwayScaleMapper.likeDesc(param);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public PageList<PreRailwayScale> likeByList(HashMap param, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PreRailwayScale> rows = preRailwayScaleMapper.likeByList(param);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public List<PreRailwayScale> noPage(HashMap param) {
        List<PreRailwayScale> rows = preRailwayScaleMapper.noPage(param);
        return rows;
    }

    @Override
    public List<PreRailwayScale> noPageDesc(HashMap param) {
        List<PreRailwayScale> rows = preRailwayScaleMapper.noPageDesc(param);
        return rows;
    }

    @Override
    public List<PreRailwayScale> hookScaleByDesc(HashMap param) {
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("pBaseCode", "001036");
        List<String> matterList = comBaseInfoMapper.matterNoByBaseCode(obj);
        param.put("list", matterList);
        List<PreRailwayScale> rows = preRailwayScaleMapper.hookScaleByDesc(param);
        return rows;
    }


    @Autowired
    DataSource dataSource;

    //定时任务通过notice和jk委托生成静态轨道衡预报
    @Override
//    @Scheduled(cron = "0/1800 * * * * ?") //定时任务 ；静态轨道衡预报新增；2021年5月28日（已废弃）
//    @Scheduled(cron = "*/5 * * * * ?")
    public void InsertRailScale() {
        HashMap<String, Object> obj = new HashMap<>();

        //查询出需要新增的数据
        List<PreRailwayScaleDto> prsds = preRailwayScaleMapper.selectForInsertRailScale(obj);
        if (prsds.size() > 0) {
            List<String> entrIds = new ArrayList<>();
            for (PreRailwayScaleDto prsd : prsds) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String afl = sdf.format(new Date());
                String no = preRailwayScaleMapper.getNewID(afl);
                prsd.setPredictionNo("T" + afl + no);
                entrIds.add(prsd.getEntrId());
                prsd.setValueFlag("1");//未使用
                prsd.setCreateManNo("system");
                prsd.setCreateManName("InsertRailScale接口");
                prsd.setCreateTime(new Date());
                prsd.setPredictionType("1");//单次预报
                prsd.setMeterTypeNo("001006001");
                prsd.setMeterTypeName("采购进厂");
                prsd.setRailwayTypeNo("001019001");
                prsd.setRailwayTypeName("静态轨道衡");
                prsd.setShipmentNetWeight(prsd.getShipmentNetWeight()); //发运净重
                prsd.setShipmentNum(prsd.getShipmentNum()); //发运数量
                prsd.setLoadPointName(prsd.getLoadPointName()); //卸货地点名称
                prsd.setSourceArea(prsd.getSourceArea()); //原产地
                //新增轨道衡预报
                preRailwayScaleMapper.insertSelective(prsd);
            }
            //system.out.println("DATASOURCE = " + dataSource);
        }
    }


}
