package cn.estsh.i3plus.core.apiservice.serviceimpl.busi;

import cn.estsh.i3plus.core.api.iservice.busi.ISysTaskPlanService;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SessionUser;
import cn.estsh.i3plus.pojo.platform.bean.SysRefTaskCyclePlan;
import cn.estsh.i3plus.pojo.platform.bean.SysTaskPlan;
import cn.estsh.i3plus.pojo.platform.platbean.SysLogTaskTime;
import cn.estsh.i3plus.pojo.platform.platrepositorymongo.SysLogTaskTimeRepository;
import cn.estsh.i3plus.pojo.platform.repository.SysRefTaskCyclePlanRepository;
import cn.estsh.i3plus.pojo.platform.repository.SysTaskPlanRepository;
import cn.estsh.i3plus.pojo.platform.sqlpack.CoreHqlPack;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Description : 定时任务业务接口实现
 * @Reference   :
 * @Author      : wei.peng
 * @Date        : 2018-10-22 16:58:43.974
 * @Modify      :
 **/
@Service
public class SysTaskPlanService implements ISysTaskPlanService {

    public static final Logger LOGGER = LoggerFactory.getLogger(SysTaskPlanService.class);

    @Autowired
    private SysTaskPlanRepository sysTaskPlanRDao;

    @Autowired
    private SysRefTaskCyclePlanRepository sysRefTaskCyclePlanRDao;

    @Autowired
    private SysLogTaskTimeRepository sysLogTaskTimeRDao;

    @Override
    @ApiOperation(value = "新增任务计划", notes = "新增任务计划")
    public SysTaskPlan insertSysTaskPlan(SysTaskPlan sysTaskPlan) {
        // 唯一校验
        if (sysTaskPlanRDao.isExitByProperty(new String[]{"name", "groupName"}, new String[]{sysTaskPlan.getName(), sysTaskPlan.getGroupName()})) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("定时任务已存在")
                    .setErrorSolution("请重新输入任务名称和组名称")
                    .build();
        }

        sysTaskPlan = sysTaskPlanRDao.insert(sysTaskPlan);

        SysRefTaskCyclePlan refTaskCyclePlan = new SysRefTaskCyclePlan();
        refTaskCyclePlan.setTaskCycleId(sysTaskPlan.getTaskCycleId());
        refTaskCyclePlan.setTaskPlanId(sysTaskPlan.getId());
        refTaskCyclePlan.setTaskPlanName(sysTaskPlan.getName());
        refTaskCyclePlan.setTaskPlanGroupName(sysTaskPlan.getGroupName());

        // 添加表达式与触发器关系表
        sysRefTaskCyclePlanRDao.insert(refTaskCyclePlan);
        return sysTaskPlan;
    }

    @Override
    @ApiOperation(value = "修改任务计划", notes = "修改任务计划")
    public void updateSysTaskPlan(SysTaskPlan sysTaskPlan) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        SysTaskPlan oldSysTaskPlan = sysTaskPlanRDao.getById(sysTaskPlan.getId());

        // 更新关系表
        sysRefTaskCyclePlanRDao.updateByProperties(new String[]{"taskPlanName", "taskPlanGroupName"},
                new String[]{oldSysTaskPlan.getName(), oldSysTaskPlan.getGroupName()},
                "taskCycleId", oldSysTaskPlan.getTaskCycleId()
        );

        sysTaskPlan.setTaskPlanExecNum(oldSysTaskPlan.getTaskPlanExecNum());
        sysTaskPlan.setLastRunDateTime(oldSysTaskPlan.getLastRunDateTime());
        sysTaskPlan.setTaskPlanStatus(oldSysTaskPlan.getTaskPlanStatus());
        sysTaskPlanRDao.update(sysTaskPlan);
    }

    @Override
    @ApiOperation(value = "修改任务计划状态", notes = "修改任务计划状态")
    public void updateSysTaskPlanStatus(Long id, int status, SessionUser user) {
        LOGGER.info("定时任务 SYS_MENU  id:{} status:{} user:{}", id, status, user);
        SysTaskPlan sysTaskPlan = sysTaskPlanRDao.getById(id);
        sysTaskPlan.setTaskPlanStatus(status);
        sysTaskPlan.setModifyUser(user.getUserName());
        sysTaskPlanRDao.update(sysTaskPlan);
    }

    @Override
    @ApiOperation(value = "根据根据id删除数据")
    public void deleteSysTaskPlanById(Long id) {
        SysTaskPlan sysTaskPlan = sysTaskPlanRDao.getById(id);
        ValidatorBean.checkNotNull(sysTaskPlan, "定时任务不存在");

        sysTaskPlanRDao.deleteById(id);

        // 删除关系表数据
        sysRefTaskCyclePlanRDao.deleteByProperties(new String[]{"taskPlanName", "taskPlanGroupName"},
                new Object[]{sysTaskPlan.getName(), sysTaskPlan.getGroupName()});
    }

    @Override
    @ApiOperation(value = "查询所有任务计划")
    public List<SysTaskPlan> listSysTaskPlan() {
        return sysTaskPlanRDao.list();
    }

    @Override
    @ApiOperation(value = "根据id查询任务计划数据", notes = "根据id查询任务计划数据")
    public SysTaskPlan getSysTaskPlanById(Long id) {
        return sysTaskPlanRDao.getById(id);
    }

    @Override
    @ApiOperation(value = "任务计划复杂查询，分页，排序", notes = "任务计划复杂查询，分页，排序")
    public ListPager querySysTaskPlanByPager(SysTaskPlan sysTaskPlan, Pager pager) {
        if (sysTaskPlan == null) {
            pager = PagerHelper.getPager(pager, sysTaskPlanRDao.listCount());
            return new ListPager(sysTaskPlanRDao.listPager(pager), pager);
        } else {
            String hqlPack = CoreHqlPack.packHqlSysTaskPlan(sysTaskPlan);
            pager = PagerHelper.getPager(pager, sysTaskPlanRDao.findByHqlWhereCount(hqlPack));
            return new ListPager(sysTaskPlanRDao.findByHqlWherePage(hqlPack + sysTaskPlan.orderBy(), pager), pager);
        }
    }

    @Override
    @ApiOperation(value = "查询任务计划", notes = "根据任务计划名称与组名称查询")
    public SysTaskPlan getSysTaskPlanByNameAndGroup(String name, String groupName) {
        List<SysTaskPlan> sysTaskPlanList = sysTaskPlanRDao.findByProperty(new String[]{"name", "groupName"}, new Object[]{name, groupName});
        if (sysTaskPlanList != null && sysTaskPlanList.size() != 0) {
            return sysTaskPlanList.get(0);
        }
        return null;
    }

    @Override
    @ApiOperation(value = "添加定时任务执行日志", notes = "添加定时任务执行日志")
    public void logInsertSysLogTaskTime(SysLogTaskTime sysLogTaskTime) {
        sysLogTaskTimeRDao.insert(sysLogTaskTime);
    }
}
