package com.ruoyi.zhdd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.zhdd.domain.IncidentProcess;
import com.ruoyi.zhdd.domain.IncidentTask;
import com.ruoyi.zhdd.domain.PlanTask;
import com.ruoyi.zhdd.domain.bo.IncidentProcessBo;
import com.ruoyi.zhdd.domain.vo.IncidentProcessVo;
import com.ruoyi.zhdd.service.IIncidentProcessService;
import com.ruoyi.zhdd.service.IIncidentTaskService;
import com.ruoyi.zhdd.service.IPlanService;
import com.ruoyi.zhdd.service.IPlanTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.zhdd.domain.bo.IncidentBo;
import com.ruoyi.zhdd.domain.vo.IncidentVo;
import com.ruoyi.zhdd.domain.Incident;
import com.ruoyi.zhdd.mapper.IncidentMapper;
import com.ruoyi.zhdd.service.IIncidentService;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 事件基础Service业务层处理
 *
 * @author xitong
 * @date 2021-09-28
 */
@Service
public class IncidentServiceImpl extends ServicePlusImpl<IncidentMapper, Incident, IncidentVo> implements IIncidentService {

    @Autowired
    private IIncidentProcessService incidentProcessService;
    @Autowired
    private IPlanService planService;
    @Autowired
    private IIncidentTaskService incidentTaskService;

    @Override
    public IncidentVo queryById(String id){
        return getVoById(id);
    }

    @Override
    public TableDataInfo<IncidentVo> queryPageList(IncidentBo bo) {
        PagePlus<Incident, IncidentVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<IncidentVo> queryList(IncidentBo bo) {
        return listVo(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<Incident> buildQueryWrapper(IncidentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Incident> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getType() != null, Incident::getType, bo.getType());
        lqw.eq(bo.getLevel() != null, Incident::getLevel, bo.getLevel());
        lqw.eq(StringUtils.isNotBlank(bo.getAddr()), Incident::getAddr, bo.getAddr());
        lqw.eq(StringUtils.isNotBlank(bo.getLocations()), Incident::getLocations, bo.getLocations());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateDept()), Incident::getCreateDept, bo.getCreateDept());
        lqw.eq(StringUtils.isNotBlank(bo.getSource()), Incident::getSource, bo.getSource());
        lqw.eq(StringUtils.isNotBlank(bo.getDes()), Incident::getDes, bo.getDes());
        lqw.eq(StringUtils.isNotBlank(bo.getPic()), Incident::getPic, bo.getPic());
        lqw.eq(StringUtils.isNotBlank(bo.getVideo()), Incident::getVideo, bo.getVideo());
        lqw.eq(StringUtils.isNotBlank(bo.getExpr1()), Incident::getExpr1, bo.getExpr1());
        lqw.eq(StringUtils.isNotBlank(bo.getExpr2()), Incident::getExpr2, bo.getExpr2());
        lqw.eq(StringUtils.isNotBlank(bo.getExprJson()), Incident::getExprJson, bo.getExprJson());
        lqw.like(StringUtils.isNotBlank(bo.getName()), Incident::getName, bo.getName());
        lqw.eq(bo.getStatus() != null, Incident::getStatus, bo.getStatus());
        lqw.eq(bo.getMadinDept() != null, Incident::getMadinDept, bo.getMadinDept());
        lqw.eq(StringUtils.isNotBlank(bo.getAssistDept()), Incident::getAssistDept, bo.getAssistDept());
        if (params.get("beginTime") != null && params.get("endTime") != null) {
            lqw.between(Incident::getCreateTime, Timestamp.valueOf(Convert.toStr(params.get("beginTime"))+ " 00:00:00"), Timestamp.valueOf(Convert.toStr(params.get("endTime")) + " 23:59:59"));
        }
        lqw.in(bo.getLevels() != null && bo.getLevels().size() > 0, Incident::getLevel, bo.getLevels());
        return lqw;
    }

    @Override
    public Boolean insertByBo(IncidentBo bo) {
        Incident add = BeanUtil.toBean(bo, Incident.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(IncidentBo bo) {
        // 是否为状态变更
        boolean flag = false;
        // 查询变更前信息
        IncidentVo beforeInfo = getVoById(bo.getId());
        if (beforeInfo != null) {
            flag = !(beforeInfo.getStatus().equals(bo.getStatus()));
        }
        Incident update = BeanUtil.toBean(bo, Incident.class);
        validEntityBeforeSave(update);
        if (flag && bo.getStatus() == 3) {
            // 待处置状态
            if (StrUtil.isBlank(bo.getMadinDept())) {
                throw new ServiceException("请选择主办单位！");
            }
//            // 查询初始设置的处置方案
//            List<PlanTask> planTask = planService.queryTask(bo.getMadinDept(), bo.getType(), bo.getLevel());
//            List<IncidentTask> incidentTasks = new ArrayList<>();
//            for (PlanTask task : planTask) {
//                IncidentTask incidentTask = new IncidentTask();
//                incidentTask.setIncidentId(update.getId());
//                incidentTask.setTaskName(task.getTaskName());
//                incidentTask.setTaskDes(task.getTaskDes());
//                incidentTask.setSource(1);
//                incidentTasks.add(incidentTask);
//            }
//            incidentTaskService.saveAll(incidentTasks);
        } else if (flag && bo.getStatus() == 4) {
            // 如果为归档的话，处置过程至少有一个
            IncidentProcessBo incidentProcessBo = new IncidentProcessBo();
            incidentProcessBo.setIncidentId(update.getId());
            List<IncidentProcessVo> incidentProcessVos = incidentProcessService.queryList(incidentProcessBo);
            if (incidentProcessVos.size() == 0) {
                throw new ServiceException("至少需要一条处置过程！");
            }
        }
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Incident entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }
}
