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

import com.steerinfo.baseinfo.appphonehelp.model.AppPhoneHelp;
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.meterwork.except.MarkerMetException;
import com.steerinfo.meterwork.meterworkscheduledhelp.mapper.MeterWorkScheduledHelpMapper;
import com.steerinfo.meterwork.meterworkscheduledhelp.model.MeterWorkScheduledHelp;
import com.steerinfo.meterwork.meterworkscheduledhelp.service.IMeterWorkScheduledHelpService;
import com.steerinfo.util.PublicMethod;
import com.steerinfo.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailParseException;
import org.springframework.stereotype.Service;

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

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

    @Resource
    private MeterWorkScheduledHelpMapper meterWorkScheduledHelpMapper;

    @Override
    protected IBaseMapper<MeterWorkScheduledHelp, String> getMapper() {
        return meterWorkScheduledHelpMapper;
    }

    @Override
    public RESTfulResult scheduledHelp(String carNo, String baseSpotNo, String baseSpotName, String helpContent) {
        RESTfulResult rm = new RESTfulResult();
        //新建AppPhoneHelp类存储远程救助信息
        MeterWorkScheduledHelp helpModel = new MeterWorkScheduledHelp();
        //根据车号、电话、司机姓名获取远程求助信息
        HashMap<String, Object> map = new HashMap<>();
        map.put("carNo", carNo);
        map.put("baseSpotNo", baseSpotNo);
        map.put("baseSpotName", baseSpotName);
        List<MeterWorkScheduledHelp> model = meterWorkScheduledHelpMapper.selectByParameters(map);
        //若是远程求助信息里面没有求助信息，重新生成Id直接插入
        if(model.size() < 1){
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//            helpModel.setHelpId(sdf.format(new Date()));
            String no =  PublicMethod.IdCreate(3);
            helpModel.setHelpId(no);
            helpModel.setCarNo(carNo);
            helpModel.setBaseSpotNo(baseSpotNo);
            helpModel.setBaseSpotName(baseSpotName);
            helpModel.setHelpContent(helpContent);
            helpModel.setCreateTime(new Date());
            helpModel.setValueFlag("0");
            int i = meterWorkScheduledHelpMapper.insertSelective(helpModel);
            if( i > 0){
                rm.setSucceed();
                rm.setMessage("数据正在处理，请等待！！");
                rm.setCode("200");
                rm.setData(helpModel);
            }else{
                rm.setMessage("操作失败");
                rm.setCode("500");
                rm.setFailed();
            }
        }else{  //若有求助信息，更新远程求助表
            model.get(0).setHelpContent(helpContent);
            model.get(0).setCreateTime(new Date());
            model.get(0).setValueFlag("0");
            int i = meterWorkScheduledHelpMapper.updateByPrimaryKeySelective(model.get(0));
            if( i > 0){
                rm.setSucceed();
                rm.setMessage("数据正在处理，请等待！！");
                rm.setCode("200");
                rm.setData(model);
            }else{
                rm.setMessage("操作失败");
                rm.setCode("500");
                rm.setFailed();
            }
        }
        return rm;
    }

    @Override
    public RESTfulResult scheduledHelpConfirm(String id, String createNo, String createName, String result) {
        RESTfulResult rm = new RESTfulResult();
        MeterWorkScheduledHelp model = meterWorkScheduledHelpMapper.selectByPrimaryKey(id);
        if(model == null){
            rm.setMessage("根据远程求助信息ID未找到相应远程求助信息，请确认！！");
            rm.setData(null);
            rm.setFailed();
        }else{
            model.setCreateNo(createNo);
            model.setCreateName(createName);
            model.setEndTime(new Date());
            model.setValueFlag("1");
            model.setResult(result);
            int i = meterWorkScheduledHelpMapper.updateByPrimaryKeySelective(model);
            if( i > 0){
                rm.setMessage("操作成功");
                rm.setSucceed();
            }else{
                rm.setMessage("操作失败");
                rm.setFailed();
            }
        }
        return rm;
    }

    @Override
    public RESTfulResult checkAdd(MeterWorkScheduledHelp model) {
        try{
            RESTfulResult rm = new RESTfulResult();
            rm.setCode("200");
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//            String afl = sdf.format(new Date());
//            String no = meterWorkScheduledHelpMapper.getNewID(afl);
//            model.setHelpId(sdf.format(new Date()) + no);

            String no =  PublicMethod.IdCreate(3);
            model.setHelpId(no);
            model.setCreateTime(new Date());
            model.setValueFlag("0");
            meterWorkScheduledHelpMapper.insertSelective(model);
            rm.setData(model.getHelpId());
            rm.setMessage("成功");
            return rm;
        }
        catch (MarkerMetException e){
            RESTfulResult rm = new RESTfulResult();
            rm.setCode("500");
            rm.setFailed();
            rm.setMessage(e.getMessage());
            return rm;
        }
    }

    @Override
    public PageList<MeterWorkScheduledHelp> likeByDesc(Map<String, Object> parameters, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        if(parameters.get("baseSpotNoStr") != null) {
            String spotNoStr[] = parameters.get("baseSpotNoStr").toString().split(",");
            parameters.put("spotNoStr", spotNoStr);
        }
        if(parameters.get("createManNoStr") != null) {
            String manNoStr[] = parameters.get("createManNoStr").toString().split(",");
            parameters.put("manNoStr", manNoStr);
        }
        List<MeterWorkScheduledHelp> rows = meterWorkScheduledHelpMapper.likeByDesc(parameters);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

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

    @Override
    public PageList<MeterWorkScheduledHelp> allStateView(Map<String, Object> params, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkScheduledHelp> rows = meterWorkScheduledHelpMapper.allStateView(params);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public List<HashMap> helpContentSummary(HashMap<String, Object> params) {
        if(params.get("baseSpotNoStr") != null && !params.get("baseSpotNoStr").equals("")) {
            String[] spotStr = params.get("baseSpotNoStr").toString().split(",");
            params.put("spotStr", spotStr);
        }
        //统计报警信息秤点信息
        List<MeterWorkScheduledHelp> spotModels = meterWorkScheduledHelpMapper.helpContentSummarySpot(params);
        //根据秤点信息查询报警信息
        List<MeterWorkScheduledHelp> scheduledHelps = meterWorkScheduledHelpMapper.helpContentSummary(params);
        List<HashMap> mapList = new ArrayList<>();
        if(spotModels.size() >= 1) {
            for(MeterWorkScheduledHelp spotModel: spotModels){
                //疑似跟车
                long countFollowCar = 0L;
                //车号未识别
                long countNotIdentify = 0L;
                //车号识别不一致
//                long countIdentifyError = 0L;
                //重置委托状态
                long countResetScaleFlag = 0L;
                //扫码计量
                long countScanCode = 0L;
                //无委托结净数
                long countNotMatchScaleClean = 0L;
                //匹配最新委托结净数
                long countMatchScaleClean = 0L;
                //存在未结净毛重（一次毛重）
                long countFirstGross = 0L;
                //连续保存皮重（一次皮重）
                long countFirstTare = 0L;
                //无仪表盘抓拍图片
                long countInstrument = 0L;
                //期限皮过期，请留存期限皮
                long countTermDataNo = 0L;
                //留存期限皮成功
                long countTermDataYes = 0L;
                //联系大厅
                long countContactLobby = 0L;
                //已处理
                long countProcessed = 0L;
                //未处理
                long countUnprocessed = 0L;
                if(scheduledHelps.size() >= 1) {
                    countFollowCar = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && item.getHelpContent().contains("疑似跟车")).count();
                    countNotIdentify = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && ( item.getHelpContent().contains("双摄像头只有一个识别，请核查车号"))).count();
//                    countIdentifyError = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
//                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())).count();
                    countScanCode = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && item.getHelpContent().contains("扫码过秤")).count();
                    countResetScaleFlag = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && item.getHelpContent().contains("正使用委托没有匹配一次记录，自动修改为未使用状态")).count();
                    countNotMatchScaleClean = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && (    (item.getHelpContent().contains("存在") && item.getHelpContent().contains("个委托"))
                                    || item.getHelpContent().contains("无委托结净")  )).count();
                    countMatchScaleClean = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && item.getHelpContent().contains("多个完全相同委托自动匹配最新委托")).count();
                    countFirstGross = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && item.getHelpContent().contains("毛重")).count();
                    countFirstTare = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && item.getHelpContent().contains("连续保存皮重")).count();
                    countInstrument = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && item.getHelpContent().contains("仪表抓图失败，请重启该秤点智能终端")).count();
                    countTermDataNo = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && item.getHelpContent().contains("期限皮过期")).count();
                    countTermDataYes = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && item.getHelpContent().contains("留存期限皮成功")).count();
                    countContactLobby = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && item.getHelpContent().contains("大厅")).count();
                    countProcessed = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && item.getValueFlag().equals("1")).count();
                    countUnprocessed = scheduledHelps.stream().filter(item -> item.getBaseSpotNo().equals(spotModel.getBaseSpotNo())
                            && item.getBaseSpotName().equals(spotModel.getBaseSpotName())
                            && item.getValueFlag().equals("0")).count();
                }
                HashMap map = new HashMap<>();
                map.put("baseSpotNo", spotModel.getBaseSpotNo());
                map.put("baseSpotName", spotModel.getBaseSpotName());
                map.put("countFollowCar", countFollowCar);
                map.put("countNotIdentify", countNotIdentify);
//                map.put("countIdentifyError", countIdentifyError);
                map.put("countResetScaleFlag", countResetScaleFlag);
                map.put("countScanCode", countScanCode);
                map.put("countNotMatchScaleClean", countNotMatchScaleClean);
                map.put("countMatchScaleClean", countMatchScaleClean);
                map.put("countFirstGross", countFirstGross);
                map.put("countFirstTare", countFirstTare);
                map.put("countInstrument", countInstrument);
                map.put("countTermDataNo", countTermDataNo);
                map.put("countTermDataYes", countTermDataYes);
                map.put("countContactLobby", countContactLobby);
                map.put("countProcessed", countProcessed);
                map.put("countUnprocessed", countUnprocessed);
                mapList.add(map);
            }
        }
        return mapList;
    }

    @Override
    public PageList<MeterWorkScheduledHelp> helpContentDetail(HashMap<String, Object> params, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkScheduledHelp> rows = meterWorkScheduledHelpMapper.helpContentSummary(params);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }
}
