package com.aucma.dms.service.impl;


import com.aucma.common.core.domain.model.LoginUser;
import com.aucma.common.utils.DateUtils;
import com.aucma.common.utils.SecurityUtils;
import com.aucma.common.utils.StringUtils;
import com.aucma.common.utils.uuid.Seq;
import com.aucma.dms.domain.DmsPlanMaint;
import com.aucma.dms.domain.DmsPlanMaintDetail;
import com.aucma.dms.mapper.DmsPlanMaintMapper;
import com.aucma.dms.service.IDmsPlanMaintService;
import com.aucma.quartz.util.CronUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 保养计划信息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 day = "*";
        String month = "*";
        String week = "*";
        String year = "*";
        String cron = "";
        if (dmsPlanMaint.getDay()!=null){
            day = dmsPlanMaint.getDay().toString();
        }
        if (dmsPlanMaint.getMonth()!=null){
            month = dmsPlanMaint.getMonth().toString();
        }
        if (dmsPlanMaint.getWeek()!=null){
            Long weekDay = dmsPlanMaint.getWeek() + 1;
            week = weekDay.toString();
        }
        if (dmsPlanMaint.getYear()!=null){
            year = dmsPlanMaint.getYear().toString();
        }
        if (dmsPlanMaint.getMaintLevel().equals(1l)){
            cron = "0 0 "+dmsPlanMaint.getHour()+" "+day+" "+month+" ?";
        }
        if (dmsPlanMaint.getMaintLevel().equals(2l)){
            cron = "0 0 "+dmsPlanMaint.getHour()+" ?"+" "+month+" "+week;
        }
        if (dmsPlanMaint.getMaintLevel().equals(3l)){
            cron = "0 0 "+dmsPlanMaint.getHour()+" "+day+" "+ month+" ? "+year;
        }
        String planMaintCode = Seq.getId(Seq.planMaintSeqType, Seq.planMaintCode);
//        String cron = "* * "+dmsPlanMaint.getHour()+" ? * "+week;
/*        SysJob job = new SysJob();
        job.setJobName("保养计划编号" + planMaintCode + "工单任务");
        job.setJobGroup("DEFAULT");
        job.setInvokeTarget("ryTask.getDmsBillsMaint(\"" + planMaintCode + "\")");
        job.setCronExpression(cron);
        job.setMisfirePolicy("1");
        job.setConcurrent("1");
        job.setStatus("1");
        R<Integer> jobIdR = remoteJobService.add(SecurityConstants.INNER, job);*/

        String time = cron;
        //通过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));
        // 设置默认值：IS_FLAG 为 null 时默认为 0
        if (dmsPlanMaint.getIsFlag() == null) {
            dmsPlanMaint.setIsFlag(0L);
        }
        dmsPlanMaint.setCreateBy(SecurityUtils.getLoginUser()==null ? SecurityUtils.getUserId() :SecurityUtils.getLoginUser().getUser().getUserId());
        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.getLoginUser()==null ? SecurityUtils.getUserId() :SecurityUtils.getLoginUser().getUser().getUserId());
        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.getUserId());
                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;
    }

}
