package com.ruoyi.zhdd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
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.PlanFile;
import com.ruoyi.zhdd.domain.PlanTask;
import com.ruoyi.zhdd.domain.bo.PlanFileBo;
import com.ruoyi.zhdd.domain.bo.PlanTaskBo;
import com.ruoyi.zhdd.domain.vo.PlanTaskVo;
import com.ruoyi.zhdd.service.IPlanFileService;
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.PlanBo;
import com.ruoyi.zhdd.domain.vo.PlanVo;
import com.ruoyi.zhdd.domain.Plan;
import com.ruoyi.zhdd.mapper.PlanMapper;
import com.ruoyi.zhdd.service.IPlanService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 预案管理Service业务层处理
 *
 * @author xitong
 * @date 2021-09-28
 */
@Service
public class PlanServiceImpl extends ServicePlusImpl<PlanMapper, Plan, PlanVo> implements IPlanService {

    @Autowired
    private IPlanTaskService planTaskService;
    @Autowired
    private IPlanFileService planFileService;

    @Override
    public PlanVo queryById(String id){
        PlanVo voById = getVoById(id);
        // 查询预案的任务
        PlanTaskBo planTaskBo = new PlanTaskBo();
        planTaskBo.setPlanId(id);
        List<PlanTaskVo> planTaskVos = planTaskService.queryList(planTaskBo);
        List<PlanTaskVo> one = new ArrayList<>();
        List<PlanTaskVo> two = new ArrayList<>();
        List<PlanTaskVo> three = new ArrayList<>();
        List<PlanTaskVo> four = new ArrayList<>();
        Map<String, List<PlanTaskVo>> map = new HashMap<>(4);
        for (PlanTaskVo planTaskVo : planTaskVos) {
            if (planTaskVo.getLevel() == 1) {
                one.add(planTaskVo);
            } else if (planTaskVo.getLevel() == 2) {
                two.add(planTaskVo);
            } else if (planTaskVo.getLevel() == 3) {
                three.add(planTaskVo);
            } else if (planTaskVo.getLevel() == 4) {
                four.add(planTaskVo);
            }
        }
        map.put("1", one);
        map.put("2", two);
        map.put("3", three);
        map.put("4", four);
        voById.setPlanTasks(map);
        PlanFileBo planFileBo = new PlanFileBo();
        planFileBo.setPlanId(id);
        voById.setPlanFiles(planFileService.queryList(planFileBo));
        return voById;
    }

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

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

    private LambdaQueryWrapper<Plan> buildQueryWrapper(PlanBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Plan> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), Plan::getName, bo.getName());
        lqw.eq(bo.getType() != null, Plan::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateDept()), Plan::getCreateDept, bo.getCreateDept());
        return lqw;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(PlanBo bo) {
        // 根据类型和部门查询是否存在数据
        List<PlanVo> planVos = listVo(Wrappers.<Plan>lambdaQuery().eq(Plan::getType, bo.getType()).eq(Plan::getCreateDept, bo.getCreateDept()));
        if (planVos != null && planVos.size() > 0) {
            throw new ServiceException("已存在该类型的预案，请勿重复输入！");
        }
        Plan add = BeanUtil.toBean(bo, Plan.class);
        validEntityBeforeSave(add);
        save(add);
        String planId = add.getId();
        // 处理预案内容数据
        for (PlanTask planTask : bo.getPlanTasks()) {
            planTask.setPlanId(planId);
        }
        // 处理预案文件
        if (bo.getPlanFiles() != null) {
            for (PlanFile planFile : bo.getPlanFiles()) {
                planFile.setPlanId(planId);
            }
        }
        planTaskService.saveAll(bo.getPlanTasks());
        planFileService.saveAll(bo.getPlanFiles());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(PlanBo bo) {
        Plan update = BeanUtil.toBean(bo, Plan.class);
        validEntityBeforeSave(update);
        updateById(update);
        String planId = update.getId();
        // 处理预案内容数据,更新之前先删除
        planTaskService.remove(Wrappers.<PlanTask>lambdaQuery().eq(PlanTask::getPlanId, planId));
        for (PlanTask planTask : bo.getPlanTasks()) {
            planTask.setId(null);
            planTask.setPlanId(planId);
        }
        planFileService.remove(Wrappers.<PlanFile>lambdaQuery().eq(PlanFile::getPlanId, planId));
        // 处理预案文件
        for (PlanFile planFile : bo.getPlanFiles()) {
            planFile.setId(null);
            planFile.setPlanId(planId);
        }
        planTaskService.saveAll(bo.getPlanTasks());
        planFileService.saveAll(bo.getPlanFiles());
        return true;
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        removeByIds(ids);
        // 同时删除预案任务数据
        planTaskService.remove(Wrappers.<PlanTask>lambdaQuery().in(PlanTask::getPlanId, ids));
        planFileService.remove(Wrappers.<PlanFile>lambdaQuery().in(PlanFile::getPlanId, ids));
        return true;
    }

    @Override
    public List<PlanTask> queryTask(String dept, Integer type, Integer level) {
        return baseMapper.queryTask(dept, type, level);
    }
}
