package com.highdatas.mdm.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.highdatas.mdm.entity.SysAssemble;
import com.highdatas.mdm.entity.SysAssembleParams;
import com.highdatas.mdm.mapper.SysAssembleParamsMapper;
import com.highdatas.mdm.service.ISysAssembleParamsService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.highdatas.mdm.service.ISysAssembleService;
import com.highdatas.mdm.util.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.support.CronSequenceGenerator;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kimi
 * @since 2020-02-20
 */
@Slf4j
@Service
public class SysAssembleParamsServiceImpl extends ServiceImpl<SysAssembleParamsMapper, SysAssembleParams> implements ISysAssembleParamsService {
    @Autowired
    ISysAssembleParamsService paramsService;
    @Autowired
    ISysAssembleService assembleService;


    @Override
    public boolean updateCornVal(String assembleId, String cron) {
        SysAssemble assemble = assembleService.selectById(assembleId);
        if (assemble == null ) {
            return false;
        }
        SysAssembleParams sysAssembleParams = paramsService.selectOne(new EntityWrapper<SysAssembleParams>().eq("parent_id", assembleId).eq("code", Constant.Cron));
        if (sysAssembleParams == null) {
            return false;
        }
        if (StringUtils.isEmpty(cron)) {
            return false;
        }
        if (!CronSequenceGenerator.isValidExpression(cron)) {
            return false;
        }
        CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cron);
        Date currentTime = new Date();
        Date nextTimePoint = cronSequenceGenerator.next(currentTime);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        sysAssembleParams.setVal(simpleDateFormat.format(nextTimePoint));
        boolean update = sysAssembleParams.updateById();
        return update;
    }
}