package com.hw.dms.service.impl;

import java.util.Date;
import java.util.List;

import com.hw.common.core.constant.SecurityConstants;
import com.hw.common.core.domain.R;
import com.hw.common.core.utils.DateUtils;
import com.hw.common.core.utils.uuid.Seq;
import com.hw.common.security.utils.SecurityUtils;
import com.hw.dms.domain.DmsPlanRepair;
import com.hw.job.api.RemoteJobService;
import com.hw.job.api.domain.SysJob;
import com.hw.job.api.util.CronUtils;
import com.hw.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

import com.hw.common.core.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.hw.dms.domain.DmsPlanMaintDetail;
import com.hw.dms.mapper.DmsPlanMaintMapper;
import com.hw.dms.domain.DmsPlanMaint;
import com.hw.dms.service.IDmsPlanMaintService;

/**
 * 保养计划信息Service业务层处理
 *
 * @author xins
 * @date 2024-01-08
 */
@Service
public class DmsPlanMaintServiceImpl implements IDmsPlanMaintService {
    @Autowired
    private DmsPlanMaintMapper dmsPlanMaintMapper;

    @Autowired
    private RemoteJobService remoteJobService;

    /**
     * 查询保养计划信息
     *
     * @param planMaintId 保养计划信息主键
     * @return 保养计划信息
     */
    @Override
    public DmsPlanMaint selectDmsPlanMaintByPlanMaintId(Long planMaintId) {
        DmsPlanMaint dmsPlanMaint = dmsPlanMaintMapper.selectPlanMaintJoinJobByPlanMaintId(planMaintId);

        Long timeLimit = dmsPlanMaint.getTimeLimit();
        if (timeLimit != null) {
            Long days = timeLimit / (24 * 60 * 60l);
            Long hours = timeLimit % (24 * 60 * 60l);
//            System.out.println(days);
//            System.out.println(hours);
            dmsPlanMaint.setTimeLimitDays(days);
            dmsPlanMaint.setTimeLimitHours(hours / (60 * 60l));
        }
        return dmsPlanMaint;
    }

    /**
     * 查询保养计划信息列表
     *
     * @param dmsPlanMaint 保养计划信息
     * @return 保养计划信息
     */
    @Override
    public List<DmsPlanMaint> selectDmsPlanMaintList(DmsPlanMaint dmsPlanMaint) {

        List<DmsPlanMaint> dmsPlanMaints = dmsPlanMaintMapper.selectDmsPlanMaintList(dmsPlanMaint);
        for (DmsPlanMaint d : dmsPlanMaints) {
            Long timeLimit = d.getTimeLimit();
            d.setTimeLimitDays(timeLimit / (24 * 60 * 60L));
            d.setTimeLimitHours((timeLimit % (24 * 60 * 60L)) / (60 * 60l));
        }

        return dmsPlanMaints;
    }

    /**
     * 新增保养计划信息
     *
     * @param dmsPlanMaint 保养计划信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertDmsPlanMaint(DmsPlanMaint dmsPlanMaint) {
        String planMaintCode = Seq.getId(Seq.planMaintSeqType, Seq.planMaintCode);

        SysJob job = new SysJob();
        job.setJobName("保养计划编号" + planMaintCode + "工单任务");
        job.setJobGroup("DEFAULT");
        job.setInvokeTarget("ryTask.getDmsBillsMaint(\"" + planMaintCode + "\")");
        job.setCronExpression(dmsPlanMaint.getCronExpression());
        job.setMisfirePolicy("1");
        job.setConcurrent("1");
        job.setStatus("1");
        R<Integer> jobIdR = remoteJobService.add(SecurityConstants.INNER, job);

        String time = dmsPlanMaint.getCronExpression();
        //通过cron表达式获取下一次执行时间
        Date nextExecution = CronUtils.getNextExecution(time);
        dmsPlanMaint.setMaintTime(nextExecution);
        dmsPlanMaint.setJobId(jobIdR.getData().longValue());
        dmsPlanMaint.setPlanMaintCode(planMaintCode);
        Long timeLimitDays = dmsPlanMaint.getTimeLimitDays()==null?0L:dmsPlanMaint.getTimeLimitDays();
        Long timeLimitHours = dmsPlanMaint.getTimeLimitHours() == null?0L:dmsPlanMaint.getTimeLimitHours();
        dmsPlanMaint.setTimeLimit((timeLimitDays * 24 * 60 * 60)
                + (timeLimitHours * 60 * 60));
        dmsPlanMaint.setIsFlag(1l);
        dmsPlanMaint.setCreateBy(SecurityUtils.getUsername());
        dmsPlanMaint.setCreateTime(DateUtils.getNowDate());
        int rows = dmsPlanMaintMapper.insertDmsPlanMaint(dmsPlanMaint);

        return rows;
    }

    /**
     * 修改保养计划信息
     *
     * @param dmsPlanMaint 保养计划信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateDmsPlanMaint(DmsPlanMaint dmsPlanMaint) {
        Long jobId = dmsPlanMaint.getJobId();
        String cronExpression = dmsPlanMaint.getCronExpression();
        if(StringUtils.isNotEmpty(cronExpression)){
            if (jobId == null) {
                String planMaintCode = dmsPlanMaint.getPlanMaintCode();
                SysJob job = new SysJob();
                job.setJobName("保养计划编号" + planMaintCode + "工单任务");
                job.setJobGroup("DEFAULT");
                job.setInvokeTarget("ryTask.getDmsBillsMaint(\"" + planMaintCode + "\")");
                job.setCronExpression(dmsPlanMaint.getCronExpression());
                job.setMisfirePolicy("1");
                job.setConcurrent("1");
                job.setStatus("1");
                R<Integer> jobIdR = remoteJobService.add(SecurityConstants.INNER, job);
                dmsPlanMaint.setJobId(jobIdR.getData().longValue());
            } else {
                SysJob sysJob = remoteJobService.getJobInfo(jobId, SecurityConstants.INNER);
                if (sysJob != null) {
                    sysJob.setCronExpression(dmsPlanMaint.getCronExpression());
                    remoteJobService.update(SecurityConstants.INNER, sysJob);
                }
            }
        }

        String time = dmsPlanMaint.getCronExpression();
        //通过cron表达式获取下一次执行时间
        Date nextExecution = CronUtils.getNextExecution(time);
        dmsPlanMaint.setMaintTime(nextExecution);
        Long timeLimitDays = dmsPlanMaint.getTimeLimitDays()==null?0L:dmsPlanMaint.getTimeLimitDays();
        Long timeLimitHours = dmsPlanMaint.getTimeLimitHours() == null?0L:dmsPlanMaint.getTimeLimitHours();
        dmsPlanMaint.setTimeLimit((timeLimitDays * 24 * 60 * 60)
                + (timeLimitHours * 60 * 60));
        dmsPlanMaint.setUpdateBy(SecurityUtils.getUsername());
        dmsPlanMaint.setUpdateTime(DateUtils.getNowDate());
        return dmsPlanMaintMapper.updateDmsPlanMaint(dmsPlanMaint);
    }

    /**
     * 批量删除保养计划信息
     *
     * @param planMaintIds 需要删除的保养计划信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDmsPlanMaintByPlanMaintIds(Long[] planMaintIds) {
        int planMaintLength = planMaintIds.length;
        Long[] jobIds = new Long[planMaintLength];
        for (int i = 0; i < planMaintIds.length; i++) {
            Long planMaintId = planMaintIds[i];
            DmsPlanMaint dmsPlanMaint = dmsPlanMaintMapper.selectDmsPlanMaintByPlanMaintId(planMaintId);
            jobIds[i] = dmsPlanMaint.getJobId();
        }

        remoteJobService.remove(SecurityConstants.INNER, jobIds);

        return dmsPlanMaintMapper.deleteDmsPlanMaintByPlanMaintIds(planMaintIds);
    }

    /**
     * 删除保养计划信息信息
     *
     * @param planMaintId 保养计划信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDmsPlanMaintByPlanMaintId(Long planMaintId) {
        dmsPlanMaintMapper.deleteDmsPlanMaintDetailByPlanMaintId(planMaintId);
        return dmsPlanMaintMapper.deleteDmsPlanMaintByPlanMaintId(planMaintId);
    }

    /**
     * 新增保养计划明细信息
     *
     * @param dmsPlanMaint 保养计划信息对象
     */
    public void insertDmsPlanMaintDetail(DmsPlanMaint dmsPlanMaint) {
        List<DmsPlanMaintDetail> dmsPlanMaintDetailList = dmsPlanMaint.getDmsPlanMaintDetailList();
        Long planMaintId = dmsPlanMaint.getPlanMaintId();

        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(dmsPlanMaintDetailList)) {
            List<DmsPlanMaintDetail> list = new ArrayList<DmsPlanMaintDetail>();
            for (DmsPlanMaintDetail dmsPlanMaintDetail : dmsPlanMaintDetailList) {
                dmsPlanMaintDetail.setIsFlag(1l);
                dmsPlanMaintDetail.setCreateBy(loginUser.getUsername());
                dmsPlanMaintDetail.setPlanMaintId(planMaintId);
                list.add(dmsPlanMaintDetail);
            }
            if (list.size() > 0) {
                dmsPlanMaintMapper.batchDmsPlanMaintDetail(list);
            }
        }
    }


    /**
     * 查询保养计划信息 Join detail
     *
     * @param planMaintCode 保养计划信息Code
     * @return 保养计划信息
     */
    @Override
    public DmsPlanMaint selectDmsPlanMaintJoinByPlanMaintCode(String planMaintCode) {
        DmsPlanMaint dmsPlanMaint = dmsPlanMaintMapper.selectDmsPlanMaintJoinByPlanMaintCode(planMaintCode);

        Long timeLimit = dmsPlanMaint.getTimeLimit();
        if (timeLimit != null) {
            Long days = timeLimit / (24 * 60 * 60l);
            Long hours = timeLimit % (24 * 60 * 60l);
//            System.out.println(days);
//            System.out.println(hours);
            dmsPlanMaint.setTimeLimitDays(days);
            dmsPlanMaint.setTimeLimitHours(hours / (60 * 60l));
        }
        return dmsPlanMaint;
    }

}
