package com.mvc.service.biz;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.constant.BaseConstant;
import com.mvc.dao.TMaintenanceRecordsMapper;
import com.mvc.entity.TMaintenanceRecords;
import com.mvc.entity.TMaintenanceRecordsExample;
import com.mvc.entity.TaskRemoteCfg;
import com.mvc.model.*;
import com.mvc.model.biz.TMaintenanceRecordsModel;
import com.mvc.service.copy.TAireadService;
import com.mvc.service.setup.TSetupService;
import com.mvc.service.taizhang.StationAccService;
import com.mvc.service.taizhang.TaskRemoteCfgService;
import com.mvc.utils.DateUtil;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class TMaintenanceRecordsService {
    private static Logger log = LoggerFactory.getLogger(TMaintenanceRecordsService.class);

    @Resource
    private TMaintenanceRecordsMapper tMaintenanceRecordsMapper;

    @Resource
    private StationAccService stationAccService;

    @Resource
    private TaskRemoteCfgService taskRemoteCfgService;

    @Resource
    private TSetupService tSetupService;

    @Resource
    private TAireadService tAireadService;

    /**
     * 根据条件查询所有记录
     *
     * @param queryModel
     * @return
     */
    public ResPageModel findAllTMaintenanceRecords(TMaintenanceRecordsModel queryModel) {
        TMaintenanceRecordsExample example = new TMaintenanceRecordsExample();
        TMaintenanceRecordsExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(queryModel.getStationCode())) {//遥测站编码
            criteria.andStationCodeEqualTo(queryModel.getStationCode());
        }
        if (StringUtils.isNotEmpty(queryModel.getDeviceSn())) {//设备SN
            criteria.andDeviceSnEqualTo(queryModel.getDeviceSn());
        }
        if (StringUtils.isNotEmpty(queryModel.getMaintenanceType())) {//维护类型
            criteria.andMaintenanceTypeEqualTo(queryModel.getMaintenanceType());
        }
        if (StringUtils.isNotEmpty(queryModel.getProductVersion())) {//产品版本
            criteria.andProductVersionEqualTo(queryModel.getProductVersion());
        }
        if (StringUtils.isNotEmpty(queryModel.getSealant())) {//灌封胶
            criteria.andSealantLike("%" + queryModel.getSealant() + "%");
        }
        if (StringUtils.isNotEmpty(queryModel.getFixationMethod())) {//固定方式
            criteria.andFixationMethodLike("%" + queryModel.getFixationMethod() + "%");
        }
        if (StringUtils.isNotEmpty(queryModel.getGlueType())) {//胶水类型
            criteria.andGlueTypeLike("%" + queryModel.getGlueType() + "%");
        }
        if (StringUtils.isNotEmpty(queryModel.getGlassType())) {//下玻璃类型
            criteria.andGlassTypeLike("%" + queryModel.getGlassType() + "%");
        }
        if (StringUtils.isNotEmpty(queryModel.getMaintenanceReason())) {//维护原因
            criteria.andMaintenanceReasonLike("%" + queryModel.getMaintenanceReason() + "%");
        }
        if (StringUtils.isNotEmpty(queryModel.getRemarks())) {//备注
            criteria.andRemarksLike("%" + queryModel.getRemarks() + "%");
        }
        if (StringUtils.isNotEmpty(queryModel.getRegistrant())) {//登记人
            criteria.andRegistrantLike("%" + queryModel.getRegistrant() + "%");
        }
        if (StringUtils.isNotEmpty(queryModel.getInstallEnvironment())) {//安装环境
            criteria.andInstallEnvironmentLike("%" + queryModel.getInstallEnvironment() + "%");
        }
        if (StringUtils.isNotEmpty(queryModel.getHasLagging())) {//保温膜
            criteria.andHasLaggingEqualTo(queryModel.getHasLagging());
        }
        if (StringUtils.isNotEmpty(queryModel.getHasBreatheValve())) {//透气阀
            criteria.andHasBreatheValveEqualTo(queryModel.getHasBreatheValve());
        }
        if (StringUtils.isNotEmpty(queryModel.getHasDesiccant())) {//干燥剂
            criteria.andHasDesiccantEqualTo(queryModel.getHasDesiccant());
        }
        if(StringUtils.isNotEmpty(queryModel.getTopSealMethod())){//上盖密封方式
            criteria.andTopSealMethodLike(StringUtil.getLikeFormat(queryModel.getTopSealMethod()));
        }

        example.setOrderByClause("CONFIG_TIME DESC");
        Page<Object> pageObject = PageHelper.startPage(queryModel.getPageNum(), queryModel.getPageSize());
        List<TMaintenanceRecordsModel> resList = selectByExample(example);
        ResPageModel pageModel = new ResPageModel(resList, pageObject);
        return pageModel;
    }

    /**
     * 根据TMaintenanceRecordsExample查询数据列表
     *
     * @param example
     * @return
     */
    private List<TMaintenanceRecordsModel> selectByExample(TMaintenanceRecordsExample example) {
        List<TMaintenanceRecords> TMaintenanceRecordss = tMaintenanceRecordsMapper.selectByExample(example);
        List<TMaintenanceRecordsModel> resList = new ArrayList<>();
        for (TMaintenanceRecords TMaintenanceRecords : TMaintenanceRecordss) {
            TMaintenanceRecordsModel model = new TMaintenanceRecordsModel();
            BeanUtils.copyProperties(TMaintenanceRecords, model);
            setRemoteCfgModel(model);
            setSetupModel(model);
            resList.add(model);
        }
        return resList;
    }

    /**
     * 赋值配置记录对象
     *
     * @param model
     */
    private void setRemoteCfgModel(TMaintenanceRecordsModel model) {
        if (model.getConfigId() != null) {
            TaskRemoteCfgModel cfgModel = taskRemoteCfgService.findTaskRemoteCfgById(model.getConfigId());
            model.setRemoteCfgModel(cfgModel);
        } else {
            model.setRemoteCfgModel(new TaskRemoteCfgModel());
        }
    }

    /**
     * 赋值安装记录对象
     *
     * @param model
     */
    private void setSetupModel(TMaintenanceRecordsModel model) {
        if (model.getSetupId() != null) {
            TSetupModel setupModel = tSetupService.findTSetupById(model.getSetupId());
            model.setSetupModel(setupModel);
        } else {
            model.setSetupModel(new TSetupModel());
        }
    }

    /**
     * 保存维护记录
     *
     * @param model
     * @return
     */
    public TMaintenanceRecordsModel saveTMaintenanceRecords(TMaintenanceRecordsModel model) {
        TMaintenanceRecords TMaintenanceRecords = new TMaintenanceRecords();
        model.setCreateTime(new Date());
        model.setAutoFlag(StringUtils.isNotEmpty(model.getAutoFlag()) ? model.getAutoFlag() : "0");
        StationAccModel accModel = stationAccService.findStationAccByStationCode(model.getStationCode());
        if (accModel != null) {
            model.setStationName(accModel.getStationName());
        }
        /*else {//通过读数自动生成的情况下,没有站点不生成   //批量生成时才需要
            if(model.getAutoFlag().equals("1")&&model.getConfigId()==null) return null;
        }*/

        BeanUtils.copyProperties(model, TMaintenanceRecords);
        tMaintenanceRecordsMapper.insert(TMaintenanceRecords);
        model.setId(TMaintenanceRecords.getId());
        log.info("-----生成维护记录[" + model.getStationCode() + "]-----");
        return model;
    }

    /**
     * 更新维护记录
     *
     * @param model
     * @return
     */
    public TMaintenanceRecordsModel updateTMaintenanceRecords(TMaintenanceRecordsModel model) {
        TMaintenanceRecords tMaintenanceRecords = tMaintenanceRecordsMapper.selectByPrimaryKey(model.getId());
        model.setRegistrationTime(new Date());
        if (!tMaintenanceRecords.getStationCode().equals(model.getStationCode())) {//站码变化,重新查询名称
            StationAccModel accModel = stationAccService.findStationAccByStationCode(model.getStationCode());
            if (accModel != null) {
                model.setStationName(accModel.getStationName());
            }
        }

        BeanUtils.copyProperties(model, tMaintenanceRecords);
        int i = tMaintenanceRecordsMapper.updateByPrimaryKey(tMaintenanceRecords);
        return model;
    }

    /**
     * 删除维护记录
     *
     * @param id
     * @return
     */
    public int deleteTMaintenanceRecords(int id) {
        int i = tMaintenanceRecordsMapper.deleteByPrimaryKey(id);
        return i;
    }

    /**
     * 根据配置任务生成维护记录
     *
     * @param remoteCfg
     */
    public void generateRecordByTaskRemoteCfg(TaskRemoteCfg remoteCfg) {
        try {
            //排除未生效的计划
            if (!remoteCfg.getFinishedFlag().equals("1")) return;

            //排除未配置站点,或配置站点与SN尾数相同
            if (StringUtils.isEmpty(remoteCfg.getStationCode()) || remoteCfg.getDeviceSn().contains(remoteCfg.getStationCode())
                    || remoteCfg.getStationCode().equals("0000000000"))
                return;

            //未配置间隔或间隔是9898
            if (remoteCfg.getSampleInterval() == null && remoteCfg.getSampleInterval() == BaseConstant.MAX_SAMPLE_INTERVAL) return;

            //总结:当远程计划配置的ID号和间隔,ID与SN后10位不相同,并且间隔不是9898,计划配置成功后,判定为维护性质
            //考虑:1.是否需要联合判断其它配置项(口径、数字、尾数、读数等);2.当ID或间隔不是在同一任务进行时(暂时先简章处理,少数情况)？
            TMaintenanceRecordsModel model = new TMaintenanceRecordsModel();
            model.setStationCode(remoteCfg.getStationCode());
            model.setDeviceSn(remoteCfg.getDeviceSn());
            model.setConfigId(remoteCfg.getId());
            model.setConfigTime(remoteCfg.getFinishedTime());//完成时间
            model.setMaintenanceType("0");//维护类型默认为0 (未知,需要人工判断)
            model.setAutoFlag("1");

            TSetupModel setupModel = getSetupModel(remoteCfg.getStationCode(), remoteCfg.getCreateTime());
            if (setupModel != null) {
                model.setSetupId(setupModel.getId());
            }
            log.info("-----生成维护记录[" + model.getStationCode() + "]-----");
            saveTMaintenanceRecords(model);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }

    /**
     * 匹配安装记录
     *
     * @param stationCode
     * @param cfgTime
     * @return
     */
    private TSetupModel getSetupModel(String stationCode, Date cfgTime) {
        TSetupModel setupModel = new TSetupModel();
        setupModel.setStationCode(stationCode);
        Date temp = DateUtil.getOtherDateByHour(cfgTime, -1);//配置时间的前一个小时
        setupModel.setSetupTime(temp);
        setupModel.setPage(1);
        setupModel.setRows(1);
        Map<String, Object> map = tSetupService.findAllTSetup(setupModel);
        Object obj = map.get("list");
        if (obj != null) {
            List<TSetupModel> setupModels = (List<TSetupModel>) obj;
            Date finalTemp = DateUtil.getOtherDateByCurrentDate(cfgTime, 1);//配置时间加1天
            List<TSetupModel> list = setupModels.stream().filter(s -> s.getSetupTime().compareTo(finalTemp) < 0).collect(Collectors.toList());
            if (list != null && list.size() > 0) {
                return setupModel;
            }
        }
        return null;
    }

    /**
     * 根据读数列表生成维护记录
     */
    public Integer generateRecordByTAiReads(){
        int num=0;
        List<TAireadModel> tAireadModels = tAireadService.findMaintenanceAireadList();
        TAireadModel temp =null;
        for(TAireadModel model:tAireadModels){
            LocalDateTime localDateTime = model.getSampleTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            if(localDateTime.getMinute()==0){//过滤整分
                continue;
            }
            if(localDateTime.getHour()<5||localDateTime.getHour()>22){//非正常安装时间
                continue;
            }

            if(temp!=null){
                if(temp.getStationCode().equals(model.getStationCode()) &&
                        DateUtil.formateDate(temp.getSampleTime(),"yyyyMMdd").equals(DateUtil.formateDate(model.getSampleTime(),"yyyyMMdd"))){
                    continue;//同一个SN同一天,只处理一条
                }
            }
            if(StringUtils.isNotEmpty(model.getDeviceType())&&!model.getDeviceType().equals("1")){//非水表
                continue;
            }

            saveTMaintenanceByTAiRead(model);
            temp=model;
            num++;
        }
        return num;
    }

    /**
     * 根据读数对象保存维护记录
     * @param aireadModel
     */
    public void saveTMaintenanceByTAiRead(TAireadModel aireadModel){
        try {
            TMaintenanceRecordsModel model = new TMaintenanceRecordsModel();
            model.setStationCode(aireadModel.getStationCode());
            if(aireadModel.getDeviceSn()!=null){//有SN为空的情况 2024-06-15 guozhao
                model.setDeviceSn(aireadModel.getDeviceSn());
            }
            //model.setConfigId(remoteCfg.getId());
            model.setConfigTime(aireadModel.getSampleTime());
            model.setMaintenanceType("0");//维护类型默认为0 (未知,需要人工判断)
            model.setAutoFlag("1");

            TSetupModel setupModel = getSetupModel(aireadModel.getStationCode(), aireadModel.getSampleTime());
            if (setupModel != null) {
                model.setSetupId(setupModel.getId());
            }

            saveTMaintenanceRecords(model);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }

    /**
     * 根据读数生成维护记录
     * @param aireadModel
     */
    public void generateRecordByTAiRead(TAireadModel aireadModel){
        try {
            if(aireadModel.getStationCode().equals("0000000000")){//拆下来的设备
                return;
            }
            if(aireadModel.getDeviceSn()==null){
                return;
            }
            if(aireadModel.getDeviceSn().contains(aireadModel.getStationCode())){//SN与ID相同
                return;
            }

            LocalDateTime localDateTime = aireadModel.getSampleTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            if(localDateTime.getMinute()==0){//过滤整分
                return;
            }
            if(localDateTime.getHour()<5||localDateTime.getHour()>22){//非正常安装时间
                return;
            }

            //近8小时只内处理一条
            TMaintenanceRecordsExample example=new TMaintenanceRecordsExample();
            TMaintenanceRecordsExample.Criteria criteria=example.createCriteria();
            criteria.andStationCodeEqualTo(aireadModel.getStationCode());
            criteria.andCreateTimeGreaterThan(DateUtil.getOtherDateByHour(aireadModel.getSampleTime(),-8));

            List<TMaintenanceRecordsModel> models = selectByExample(example);
            if(models!=null&&models.size()>0){//已经生成过了
                return;
            }

            TMaintenanceRecordsModel model = new TMaintenanceRecordsModel();
            model.setStationCode(aireadModel.getStationCode());
            model.setDeviceSn(aireadModel.getDeviceSn());
            model.setConfigTime(aireadModel.getSampleTime());
            model.setMaintenanceType("0");//维护类型默认为0 (未知,需要人工判断)
            model.setAutoFlag("1");

            TSetupModel setupModel = getSetupModel(aireadModel.getStationCode(), aireadModel.getSampleTime());
            if (setupModel != null) {
                model.setSetupId(setupModel.getId());
            }

            saveTMaintenanceRecords(model);
        } catch (Exception ex) {
            log.error("",ex);
        }
    }
}
