package com.steerinfo.meterwork.meterworkcarcheck.service.impl;

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.constants.DbConstants;
import com.steerinfo.meterwork.except.MarkerMetException;
import com.steerinfo.meterwork.meterworkcarcheck.mapper.MeterWorkCarCheckMapper;
import com.steerinfo.meterwork.meterworkcarcheck.model.MeterWorkCarCheck;
import com.steerinfo.meterwork.meterworkcarcheck.service.IMeterWorkCarCheckService;
import com.steerinfo.meterwork.meterworkprelink.mapper.MeterWorkPreLinkMapper;
import com.steerinfo.meterwork.meterworkprelink.model.MeterWorkPreLink;
import com.steerinfo.meterwork.meterworkprelink.service.IMeterWorkPreLinkService;
import com.steerinfo.util.FieldsCollector;
import com.steerinfo.util.PageSpilt;
import com.steerinfo.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

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

    private static final Logger logger = (Logger) LoggerFactory.getLogger(MeterWorkCarCheckServiceImpl.class);

    @Resource
    private MeterWorkCarCheckMapper meterWorkCarCheckMapper;

    @Resource
    private MeterWorkPreLinkMapper meterWorkPreLinkMapper;

    @Autowired
    IMeterWorkPreLinkService meterWorkPreLinkService;


    @Override
    protected IBaseMapper<MeterWorkCarCheck, String> getMapper() {
        return meterWorkCarCheckMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageList<MeterWorkCarCheck> relationIn(Map<String,Object> parmas,Integer pageNum, Integer pageSize)
    {
        parmas.put("linkCode",DbConstants.INCOME);
        parmas.put("linkName","进厂核查");
        parmas.put("valueFlag",DbConstants.INFlAG);
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkCarCheck> list = meterWorkCarCheckMapper.reSelectIn(parmas);
        PageList pageInfo = new PageList(list);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public  PageList<MeterWorkCarCheck> relationOut(Map<String, Object> parmas, Integer pageNum, Integer pageSize)
    {
        parmas.put("linkCode",DbConstants.OUTCOME);
        parmas.put("linkName","出厂核查");
        parmas.put("valueFlag",DbConstants.OUTFlAG);
        List<MeterWorkCarCheck> list1 = meterWorkCarCheckMapper.reSelectOut(parmas);

        if (list1.size() > 0) {
            for (MeterWorkCarCheck list : list1) {
                Map<String,Object> hm = new HashMap<>();
                hm.put("valueFlag","0");
                hm.put("predictionNo",list.getPredictionNo());
                hm.put("carNo",parmas.get("carNo"));
                List<MeterWorkCarCheck> list2 = meterWorkCarCheckMapper.selectByParameters(parmas);
                if (list2.size() > 0) {
                    list1.remove(list);
                    list1.add(list2.get(0));
                }
            }
        }
        PageSpilt ps = new PageSpilt(list1, pageSize);//每页显示条数
        List sublist = ps.getObjects(pageNum);//显示第几页
        PageList pageInfo = new PageList(sublist);
        pageInfo.setTotal(ps.getTotal());
        return pageInfo;
    }

    @Override
    @Transactional
    public MeterWorkCarCheck incomeAndCheck(MeterWorkCarCheck model)
    {
        if(model==null) {
            throw new MarkerMetException(500, "参数不能为空");
        }
        //检查数据完整性
        check(model);
        model.setValueFlag(DbConstants.INFlAG);
        //获取创建人
        getUse(model);
        //修改预环节的数据
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("predictionNo", model.getPredictionNo());
        obj.put("linkCode",DbConstants.INCOME);
        obj.put("linkName", "进厂核查");
        List<MeterWorkPreLink> mwpls=meterWorkPreLinkMapper.selectByParameters(obj);
        for (MeterWorkPreLink mwpl:mwpls) {
            mwpl.setValueFlag(DbConstants.Y);
            mwpl.setPreLinkNo(mwpl.getPreLinkNo());
            meterWorkPreLinkMapper.updateByPrimaryKeySelective(mwpl);
            //判断预流程是否改变
            meterWorkPreLinkService.updatePrePro(mwpl);
            //批次预报若全部用完则重新生成一套
            meterWorkPreLinkService.batchReset(mwpl.getPredictionNo());
        }
        meterWorkCarCheckMapper.insertSelective(model);
        return model;
    }

    @Override
    @Transactional
    public MeterWorkCarCheck outcomeAndCheck(MeterWorkCarCheck model)
    {
            if(model==null) {
                throw new MarkerMetException(500, "参数不能为空");
            }
            check(model);
            getUse(model);
            model.setValueFlag(DbConstants.OUTFlAG);
            MeterWorkCarCheck mwcc = meterWorkCarCheckMapper.selectByPrimaryKey(model.getPredictionNo());
            if (mwcc == null ){
                meterWorkCarCheckMapper.insertSelective(model);
            }else {
                meterWorkCarCheckMapper.updateByPrimaryKeySelective(model);
            }
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("predictionNo", model.getPredictionNo());
            obj.put("linkCode",DbConstants.OUTCOME);
            obj.put("linkName", "出厂核查");
            List<MeterWorkPreLink> mwpls=meterWorkPreLinkMapper.selectByParameters(obj);
            for (MeterWorkPreLink mwpl:mwpls) {
                mwpl.setValueFlag(DbConstants.Y);
                mwpl.setPreLinkNo(mwpl.getPreLinkNo());
                meterWorkPreLinkMapper.updateByPrimaryKeySelective(mwpl);
                //判断预流程是否改变
                meterWorkPreLinkService.updatePrePro(mwpl);
                //批次预报若全部用完则重新生成一套
                meterWorkPreLinkService.batchReset(mwpl.getPredictionNo());
            }
            return model;
    }

    @Override
    @Transactional
    public int incomeAndDelete(List<MeterWorkCarCheck> models)
    {
        if(models.size() <=0 || models==null) {
            throw new MarkerMetException(500, "参数不能为空");
        }
        int num=0;
        for (MeterWorkCarCheck model:models) {
            //判断下一环节是否已经执行
            List<MeterWorkPreLink> mwpls=meterWorkPreLinkService.getNextFlag(model.getPredictionNo(),DbConstants.INCOME);
            if(mwpls.size() > 0){
                if (mwpls.get(0).getValueFlag().equals("1")) {
                    throw new MarkerMetException(500, "下一步环节已执行，无法插销!!");
                }
            }
            //修改当前
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("predictionNo", model.getPredictionNo());
            obj.put("linkCode", DbConstants.INCOME);
            obj.put("linkName", "进厂核查");
            List<MeterWorkPreLink> list = meterWorkPreLinkMapper.selectByParameters(obj);
            for (MeterWorkPreLink  list1:list ){
                list1.setValueFlag(DbConstants.N);
                list1.setPreLinkNo(list1.getPreLinkNo());
                meterWorkPreLinkMapper.updateByPrimaryKeySelective(list1);
            }
            meterWorkCarCheckMapper.deleteByPrimaryKey(model.getPredictionNo());
            num++;
        }
        return num;
    }


    @Override
    @Transactional
    public int outcomeAndDelete(List<MeterWorkCarCheck> models)
    {
        if(models.size() <=0 || models==null) {
            throw new MarkerMetException(500, "参数不能为空");
        }
        int num=0;
        for (MeterWorkCarCheck model:models) {
            //判断下一个
            List<MeterWorkPreLink> mwpls=meterWorkPreLinkService.getNextFlag(model.getPredictionNo(),DbConstants.OUTCOME);
            if(mwpls.size() > 0){
                if (mwpls.get(0).getValueFlag().equals("1")) {
                    throw new MarkerMetException(500, "下一步环节已执行，无法插销!!");
                }
            }
            //修改当前
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("predictionNo", model.getPredictionNo());
            obj.put("linkCode", DbConstants.OUTCOME);
            obj.put("linkName", "出厂核查");
            List<MeterWorkPreLink> list = meterWorkPreLinkMapper.selectByParameters(obj);
            for (MeterWorkPreLink  list1:list ) {
                list1.setValueFlag(DbConstants.N);
                list1.setPreLinkNo(list1.getPreLinkNo());
            }
            meterWorkPreLinkMapper.batchUpdate(list);
            meterWorkCarCheckMapper.deleteByPrimaryKey(model.getPredictionNo());
            num++;
        }
        return num;
    }

    @Override
    public RESTfulResult doQueryWf(MeterWorkCarCheck oci){
        RESTfulResult rm=new RESTfulResult();
        try{
            rm.setCode("200");
            PageHelper.startPage(0, 1);
            Map<String,Object> map= FieldsCollector.beanToMap(oci);
            List<MeterWorkCarCheck> rows = meterWorkCarCheckMapper.selectByParameters(map);
            PageList pageInfo = new PageList(rows);
            rm.setData(pageInfo);
        }catch(Exception ex){
            rm.setCode("500");
            rm.setMessage("查询失败："+ex.getMessage());
        }
        return rm;
    }

//    核查记录添加
    @Override
    public String checkandadd(MeterWorkCarCheck model) {
        if (model == null ) {
            return "请传入参数!";
        }else {
            String no=meterWorkCarCheckMapper.GetNewID1();
            model.setPredictionNo(new SimpleDateFormat("yyyyMMdd").format(new Date()) +no);
//            UserPayload payload = UserPayload.getCurrUser();
//            String userId = payload.getUserCode();
//            String userName = payload.getUserName();
            check(model);
            if  (model.getValueFlag().equals(DbConstants.INFlAG)) {
                model.setEnterCheckManNo(model.getEnterCheckManNo());
                model.setEnterCheckManName(model.getEnterCheckManName());
                model.setEnterCheckTime(new Date());
                meterWorkCarCheckMapper.insertSelective(model);
                return "";
            }
            if (model.getValueFlag().equals(DbConstants.OUTFlAG)) {
                model.setLeaveCheckManNo(model.getLeaveCheckManNo());
                model.setLeaveCheckManName(model.getLeaveCheckManName());
                model.setLeaveCheckTime(new Date());
                meterWorkCarCheckMapper.insertSelective(model);
                return "";
            }
        }
        return "";
    }

//  核查记录修改
    @Override
    public String checkandupdate(String id, MeterWorkCarCheck model) {
        if (model == null ) {
            return "请传入参数!";
        }
        if (StringUtils.isEmpty(model.getCarNo())) {
            return "车号不能为空";
        }
        if (StringUtils.isEmpty(model.getDriverName())) {
            return "司机姓名不能为空";
        }
        if (StringUtils.isEmpty(model.getIdNum())) {
            return "身份证号不能为空";
        }
        if (StringUtils.isEmpty(model.getTelNum())) {
            return "电话号码不能为空";
        }
        if (model.getValueFlag().equals(DbConstants.INFlAG)){
            model.setEnterCheckManNo(model.getEnterCheckManNo());
            model.setEnterCheckManName(model.getEnterCheckManName());
            model.setEnterCheckTime(new Date());
            meterWorkCarCheckMapper.updateByPrimaryKey(model);
            return "";
        }
        if (model.getValueFlag().equals(DbConstants.OUTFlAG)){
            model.setLeaveCheckManNo(model.getLeaveCheckManNo());
            model.setLeaveCheckManName(model.getLeaveCheckManName());
            model.setLeaveCheckTime(new Date());
            meterWorkCarCheckMapper.updateByPrimaryKey(model);
            return "";
        }
        return "";

    }

    private void check(MeterWorkCarCheck model)
    {
        if (model.getPredictionNo() == null || model.getPredictionNo().equals("")) {
            throw new MarkerMetException(500, "预报编号不能为空");
        }
        if (model.getCarNo() == null || model.getCarNo().equals("")) {
            throw new MarkerMetException(500, "车号不能为空");
        }
        if (model.getDriverName() == null || model.getDriverName().equals("")) {
            throw new MarkerMetException(500, "司机姓名不能为空");
        }
        if (model.getIdNum() == null || model.getIdNum().equals("")) {
            throw new MarkerMetException(500, "身份证号不能为空");
        }
//        if (model.getTransportChemical() == null || model.getTransportChemical().equals("")) {
//            throw new MarkerMetException(500, "是否可运危化品不能为空");
//        }
        if (model.getWaterBoxIsEmpty() == null || model.getWaterBoxIsEmpty().equals("")) {
            throw new MarkerMetException(500, "水箱为空是否不能为空");
        }
        if (model.getCheckResult() == null || model.getCheckResult().equals("")) {
            throw new MarkerMetException(500, "核查结果不能为空");
        }
        if(StringUtils.isEmpty(model.getPkNo())){
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String afl = formatter.format(new Date());
            String no = meterWorkCarCheckMapper.getNewID(afl);
            model.setPkNo(afl+no);
        }
    }

    private void getUse(MeterWorkCarCheck model){
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();
        if (model.getValueFlag().equals(DbConstants.INFlAG)){
            model.setEnterCheckTime(new Date());
            model.setEnterCheckManNo(userId);
            model.setEnterCheckManName(userName);
        }
        if (model.getValueFlag().equals(DbConstants.OUTFlAG)){
            model.setLeaveCheckTime(new Date());
            model.setLeaveCheckManNo(userId);
            model.setLeaveCheckManName(userName);
        }
    }

    public static void main(String[] args) {
        List<MeterWorkCarCheck> list = new ArrayList<>();
        MeterWorkCarCheck list1 = new MeterWorkCarCheck();
        MeterWorkCarCheck list2 = new MeterWorkCarCheck();
        list1.setPkNo("001");
        list2.setPkNo("002");
        list.add(list1);
        list.add(list2);
        //system.out.println(list);
        PageSpilt ps = new PageSpilt(list, 1);//每页显示条数
        //system.out.println(ps);
        List sublist = ps.getObjects(2);//显示第几页
        //system.out.println(sublist);
    }

}
