package com.mvc.service.taizhang;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.constant.BaseConstant;
import com.mvc.constant.TaskStatus;
import com.mvc.dao.TTaskDownMapper;
import com.mvc.dao.TaskRemoteCfgMapper;
import com.mvc.entity.*;
import com.mvc.model.*;
import com.mvc.netty.SimpleResponse;
import com.mvc.service.biz.TMaintenanceRecordsService;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Transactional
public class TTaskDownService {

    @Resource
    private TTaskDownMapper tTaskDownMapper;

    @Resource
    private StationAccService stationAccService;

    @Resource
    private TaskRemoteCfgMapper taskRemoteCfgMapper;

    @Resource
    private SimpleResponse SimpleResponse;

    @Resource
    private TaskRemoteCfgService taskRemoteCfgService;

    @Resource
    private TAicbqCfgService tAicbqCfgService;

    /*@Resource
    private TMaintenanceRecordsService tMaintenanceRecordsService;*/

    public Map<String, Object> findAllTTaskDown(TTaskDownModel queryModel) {
        Map<String, Object> resMap = new HashMap<>();

        TTaskDownExample example = new TTaskDownExample();
        TTaskDownExample.Criteria criteria = example.createCriteria();

        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(queryModel.getDeviceSn())) {
            if (queryModel.getDeviceSn().length() == BaseConstant.LENGTH_DEVICE_SN) {
                criteria.andDeviceSnEqualTo(queryModel.getDeviceSn());
            } else {
                criteria.andDeviceSnLike(StringUtil.getLikeFormat(queryModel.getDeviceSn()));
            }
        }
        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(queryModel.getStationCode())) {
            if (queryModel.getStationCode().length() == BaseConstant.LENGTH_STATION_CODE) {
                criteria.andStationCodeEqualTo(queryModel.getStationCode());
            } else {
                criteria.andStationCodeLike(StringUtil.getLikeFormat(queryModel.getStationCode()));
            }
        }

        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(queryModel.getFinishedFlag()) &&
                !queryModel.getFinishedFlag().equals("9")) {
            criteria.andFinishedFlagEqualTo(queryModel.getFinishedFlag());
        }

        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(queryModel.getTaskType()) &&
                !queryModel.getTaskType().equals("0")) {
            criteria.andTaskTypeEqualTo(queryModel.getTaskType());
        }

        if (queryModel.getTaskLevel() != null && queryModel.getTaskLevel() > 0) {
            criteria.andTaskLevelEqualTo(queryModel.getTaskLevel());
        }
        if (queryModel.getCreateTimeStart() != null) {
            criteria.andCreateTimeGreaterThan(queryModel.getCreateTimeStart());
        }

        if (queryModel.getCreateTimeEndEnd() != null) {
            criteria.andCreateTimeLessThan(queryModel.getCreateTimeEndEnd());
        }
        example.setOrderByClause("CREATE_TIME desc");
        Page<Object> pageObject = PageHelper.startPage(queryModel.getPage(), queryModel.getRows());
        List<TTaskDownModel> resList = selectByExample(example);
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

    private List<TTaskDownModel> selectByExample(TTaskDownExample example) {
        List<TTaskDown> taskDowns = tTaskDownMapper.selectByExample(example);
        List<TTaskDownModel> resList = new ArrayList<>();
        for (TTaskDown TTaskDown : taskDowns) {
            TTaskDownModel model = new TTaskDownModel();
            BeanUtils.copyProperties(TTaskDown, model);
            resList.add(model);
        }
        return resList;
    }

    public TTaskDownModel saveTTaskDown(TTaskDownModel model) {
        //有SN把遥测站编码查出来
        StationAccModel stationModel = stationAccService.findStationAccByDeviceSn(model.getDeviceSn());
        if (stationModel != null) {
            model.setStationCode(stationModel.getStationCode());
        } else {
            model.setStationCode("0000000000");                 //没建遥测站时也能远程配置和召测 2022-07-23 guozhao
        }

        model.setFinishedFlag(TaskStatus.NOT_EXECUTED.getCode());
        model.setTaskDownId(StringUtil.getUuid());
        model.setCreateTime(new Date());
        TTaskDown TTaskDown = new TTaskDown();
        BeanUtils.copyProperties(model, TTaskDown);
        int insert = tTaskDownMapper.insert(TTaskDown);
        model.setId(TTaskDown.getId());
        return model;
    }

    public TTaskDownModel updateTTaskDown(TTaskDownModel model) {
        TTaskDown taskDown = tTaskDownMapper.selectByPrimaryKey(model.getId());
        if (taskDown == null) {
            return null;
        }

        //远程配置,从未执行改为取消了同步任务状态
        if (taskDown.getFinishedFlag().equals(TaskStatus.NOT_EXECUTED.getCode()) &&
                model.getFinishedFlag().equals(TaskStatus.CANCELLED.getCode()) &&
                taskDown.getTaskType().equals("2")) {
            TaskRemoteCfgModel cfgModel = taskRemoteCfgService.findTaskRemoteCfgByTaskid(taskDown.getTaskId());
            if (cfgModel != null) {
                model.setFinishedTime( new Date());
                cfgModel.setFinishedFlag(model.getFinishedFlag());
                taskRemoteCfgService.updateTaskRemoteCfg(cfgModel);
            }
        }

        BeanUtils.copyProperties(model, taskDown);
        int i = tTaskDownMapper.updateByPrimaryKey(taskDown);
        return model;
    }

    /**
     * 根据远程配置的任务状态
     * @param cfgModel
     */
    public void updateFinishedFlagByTaskRemoteCfg(TaskRemoteCfgModel cfgModel) {
        TTaskDownExample example = new TTaskDownExample();
        TTaskDownExample.Criteria criteria = example.createCriteria();
        criteria.andTaskIdEqualTo(cfgModel.getTaskId());
        List<TTaskDownModel> list = selectByExample(example);
        if(list.isEmpty()){
            return;
        }

        TTaskDownModel model = list.get(0);
        model.setFinishedFlag(cfgModel.getFinishedFlag());
        model.setFinishedTime(cfgModel.getFinishedTime());

        TTaskDown taskDown =new TTaskDown();
        BeanUtils.copyProperties(model, taskDown);
        tTaskDownMapper.updateByPrimaryKey(taskDown);
    }

    public int deleteTTaskDown(int id) {
        //如果类型是远程配置的,同步删除taskRemoteCfg表中数据
        TTaskDown entity = tTaskDownMapper.selectByPrimaryKey(id);
        if (entity != null && entity.getTaskType().equals("2")) {
            taskRemoteCfgService.deleteTaskRemoteCfgByTaskid(entity.getTaskId());
        }
        int i = tTaskDownMapper.deleteByPrimaryKey(id);
        return i;
    }

    public List<TTaskDownModel> findTTaskDown(String deviceSn, String stationCode, String finishedFlag) {
        List<TTaskDownModel> resModels = new ArrayList<>();
        TTaskDownExample example = new TTaskDownExample();
        TTaskDownExample.Criteria criteria = example.createCriteria();
        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(deviceSn)) {
            criteria.andDeviceSnEqualTo(deviceSn);
        }

        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(stationCode)) {
            criteria.andStationCodeEqualTo(stationCode);
        }

        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(finishedFlag)) {
            criteria.andFinishedFlagEqualTo(finishedFlag);
        }

        example.setOrderByClause(" TASK_LEVEL desc");           //优先获取高等级任务

        List<TTaskDown> tAicbqCfgs = tTaskDownMapper.selectByExample(example);
        for (TTaskDown taicbqCfg : tAicbqCfgs) {
            TTaskDownModel model = new TTaskDownModel();
            BeanUtils.copyProperties(taicbqCfg, model);
            resModels.add(model);
        }
        return resModels;
    }


    //更新taskdown 表及相关任务表完成标志
    public TTaskDown updateTTaskDownAndRelateTask(String taskdownid) {
        Date finishDate = new Date();
        TTaskDownExample example = new TTaskDownExample();
        TTaskDownExample.Criteria criteria = example.createCriteria();
        criteria.andTaskDownIdEqualTo(taskdownid);
        List<TTaskDown> tTaskDowns = tTaskDownMapper.selectByExample(example);
        if (tTaskDowns.size() > 0) {
            TTaskDown tTaskDown = tTaskDowns.get(0);
            tTaskDown.setFinishedFlag(TaskStatus.EXECUTED.getCode());
            tTaskDown.setFinishedTime(finishDate);
            tTaskDownMapper.updateByPrimaryKey(tTaskDown);
            //处理先关任务
            if (tTaskDown.getTaskType().equals("1")) {//下发审核结果

            } else if (tTaskDown.getTaskType().equals("2")) {//远程配置
                String taskId_mx = tTaskDown.getTaskId();
                TaskRemoteCfgExample remoteCfgExample = new TaskRemoteCfgExample();
                TaskRemoteCfgExample.Criteria remotecriteria = remoteCfgExample.createCriteria();
                remotecriteria.andTaskIdEqualTo(taskId_mx);
                List<TaskRemoteCfg> taskRemoteCfgs = taskRemoteCfgMapper.selectByExample(remoteCfgExample);
                if (taskRemoteCfgs.size() > 0) {
                    TaskRemoteCfg taskRemoteCfg = taskRemoteCfgs.get(0);
                    taskRemoteCfg.setFinishedFlag(TaskStatus.EXECUTED.getCode());
                    taskRemoteCfg.setFinishedTime(finishDate);
                    taskRemoteCfgMapper.updateByPrimaryKey(taskRemoteCfg);

                    //配置成功后,根据任务生成维护记录(修改为使用读数生成) 2023-08-01 guozhao
                    ////tMaintenanceRecordsService.generateRecordByTaskRemoteCfg(taskRemoteCfg);
                }
            } else if (tTaskDown.getTaskType().equals("3")) {//获取远程配置
                //暂时不用处理
            }

            return tTaskDown;
        }
        return null;
    }

    //根据遥测站代码查找下行任务，并生成回复报文
    public List<String> generateReplyByTaskid(String deviceSn, String stationcode, boolean isReviewPush) {
        try {
            List<String> resList = new ArrayList<>();
            TTaskDownExample example = new TTaskDownExample();
            TTaskDownExample.Criteria criteria = example.createCriteria();
            //优先使用SN检索任务(现场配置可能没有) 2022-07-15 guozhao
            if (StringUtils.isNotEmpty(deviceSn)) {
                criteria.andDeviceSnEqualTo(deviceSn);
                System.out.println("查询下行任务_执行条件SN:" + deviceSn);
            } else {
                criteria.andStationCodeEqualTo(stationcode);
                System.out.println("查询下行任务_执行条件ID:" + stationcode);
            }

            criteria.andFinishedFlagEqualTo(TaskStatus.NOT_EXECUTED.getCode());
            example.setOrderByClause(" TASK_LEVEL,CREATE_TIME desc");           //优先获取高等级任务
            List<TTaskDown> tTaskDowns = tTaskDownMapper.selectByExample(example);

            if (tTaskDowns.size() > 0) {
                TTaskDown tTaskDown = tTaskDowns.get(0);
                resList.add(tTaskDown.getTaskDownId());

                if (tTaskDown.getTaskType().equals("2")) {//远程配置
                    TaskRemoteCfgExample remoteCfgExample = new TaskRemoteCfgExample();
                    TaskRemoteCfgExample.Criteria remotecriteria = remoteCfgExample.createCriteria();
                    remotecriteria.andTaskIdEqualTo(tTaskDown.getTaskId());
                    List<TaskRemoteCfg> taskRemoteCfgs = taskRemoteCfgMapper.selectByExample(remoteCfgExample);
                    if (taskRemoteCfgs.size() > 0) {
                        TaskRemoteCfg taskRemoteCfg = taskRemoteCfgs.get(0);
                        TaskRemoteCfgModel remoteCfgModel = new TaskRemoteCfgModel();
                        BeanUtils.copyProperties(taskRemoteCfg, remoteCfgModel);
                        String s = SimpleResponse.generateResponse_remotecfg(remoteCfgModel, tTaskDown.getStationCode(), isReviewPush);
                        resList.add(s);
                        return resList;
                    }
                } else if (tTaskDown.getTaskType().equals("3")) {//召测
                    TTaskDownModel taskDownModel = new TTaskDownModel();
                    BeanUtils.copyProperties(tTaskDown, taskDownModel);
                    String s = SimpleResponse.generateResponse_zhaocecfg(taskDownModel, isReviewPush);
                    resList.add(s);
                    return resList;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据对象查询是否已经存在未执行的同等级下行任务
     *
     * @param model
     * @return
     */
    public boolean existTTaskDownSameLevel(TTaskDownModel model) {
        TTaskDownExample example = new TTaskDownExample();
        TTaskDownExample.Criteria criteria = example.createCriteria();
        criteria.andDeviceSnEqualTo(model.getDeviceSn());
        criteria.andTaskLevelEqualTo(model.getTaskLevel());
        criteria.andTaskTypeEqualTo(model.getTaskType());
        criteria.andFinishedFlagEqualTo(TaskStatus.NOT_EXECUTED.getCode());
        List<TTaskDown> list = tTaskDownMapper.selectByExample(example);

        return list != null && list.size() > 0;
    }

    /**
     * 根据Taskid删除记录(删除远程配置记录时使用)
     *
     * @param taskid
     * @return
     */
    public int deleteTTaskDownByTaskid(String taskid) {
        TTaskDownExample example = new TTaskDownExample();
        TTaskDownExample.Criteria criteria = example.createCriteria();
        criteria.andTaskIdEqualTo(taskid);
        return tTaskDownMapper.deleteByExample(example);
    }

    /**
     * 根据taskDownId删除记录_批量任务模块使用(同步删除远程配置表)
     *
     * @param taskDownId
     * @return
     */
    public int deleteTTaskDownByTaskid_Batch(String taskDownId) {
        TTaskDownExample example = new TTaskDownExample();
        TTaskDownExample.Criteria criteria = example.createCriteria();
        criteria.andTaskDownIdEqualTo(taskDownId);
        List<TTaskDown> list = tTaskDownMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            TTaskDown tTaskDown = list.get(0);
            taskRemoteCfgService.deleteTaskRemoteCfgByTaskId(tTaskDown.getTaskId());
            return tTaskDownMapper.deleteByPrimaryKey(tTaskDown.getId());
        }
        return 0;
    }

    /**
     * 根据设备SN和ID号生成召测任务
     * 收到中图报文后,如果参数表中没有当前设备的配置或ID变了,自动生成召测任务
     *
     * @param deviceSn
     * @param stationCode
     */
    public boolean generateTaskDownByDeviceSnAndStationCode(String deviceSn, String stationCode) {
        List<TAicbqCfgModel> cfgList = tAicbqCfgService.findTAicbqCfg(deviceSn, "", "1");
        boolean isGenerate = true;
        if (cfgList != null && cfgList.size() > 0) {
            TAicbqCfgModel cfgModel = cfgList.get(0);
            isGenerate = !cfgModel.getStationCode().equals(stationCode);
        }

        if (isGenerate) {
            StationAccModel accModel = stationAccService.findStationAccByStationCode(stationCode);
            //遥测站点未安装或SN没有值不生成任务
            if (accModel == null || StringUtils.isEmpty(accModel.getDeviceSetupFlag()) || !accModel.getDeviceSetupFlag().equals("1") || StringUtils.isEmpty(accModel.getDeviceSn()))
                return false;

            //判断当前SN是否有未执行的任务
            TTaskDownExample example = new TTaskDownExample();
            TTaskDownExample.Criteria criteria = example.createCriteria();
            criteria.andDeviceSnEqualTo(deviceSn);
            criteria.andFinishedFlagEqualTo(TaskStatus.NOT_EXECUTED.getCode());
            List<TTaskDown> list = tTaskDownMapper.selectByExample(example);
            if (list == null || list.size() == 0) {
                TTaskDownModel model = new TTaskDownModel();
                model.setDeviceSn(deviceSn);
                model.setStationCode(stationCode);
                model.setCreateMan("自动召测");
                model.setTaskType("3");
                model.setTaskLevel(1);
                return saveTTaskDown(model) != null;
            }
        }
        return false;
    }

    /**
     * 根据拷机明细列表创建召测任务
     *
     * @param checkDetailModels
     * @return
     */
    public int generateTaskDownByCheckDetails(List<TCheckDetailModel> checkDetailModels) {
        if (checkDetailModels == null || checkDetailModels.size() == 0) return 0;

        int num = 0;
        for (TCheckDetailModel detailModel : checkDetailModels) {
            TTaskDownExample example = new TTaskDownExample();
            TTaskDownExample.Criteria criteria = example.createCriteria();
            criteria.andDeviceSnEqualTo(detailModel.getDeviceSn());
            criteria.andFinishedFlagEqualTo(TaskStatus.NOT_EXECUTED.getCode());
            List<TTaskDown> list = tTaskDownMapper.selectByExample(example);
            if (list == null || list.size() == 0) {
                TTaskDownModel model = new TTaskDownModel();
                model.setDeviceSn(detailModel.getDeviceSn());
                model.setStationCode(detailModel.getStationCode());
                model.setCreateMan("拷机召测");
                model.setTaskType("3");
                model.setTaskLevel(1);
                saveTTaskDown(model);
                num++;
            }
        }
        return num;
    }
}
