package com.foreverwin.mesnac.equip.service.impl;

import com.foreverwin.mesnac.common.constant.Constants;
import com.foreverwin.mesnac.equip.mapper.ResourceInspectTaskMapper;
import com.foreverwin.mesnac.equip.model.ResourceInspectTask;
import com.foreverwin.mesnac.equip.service.ResourceInspectPlanService;
import com.foreverwin.mesnac.equip.service.ResourceInspectTaskJobService;
import com.foreverwin.mesnac.equip.service.ResourceInspectTaskService;
import com.foreverwin.modular.core.util.CommonMethods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class ResourceInspectTaskJobServiceImpl implements ResourceInspectTaskJobService {

    @Autowired
    ResourceInspectTaskMapper resourceInspectTaskMapper;
    @Autowired
    ResourceInspectPlanService resourceInspectPlanService;
    @Autowired
    ResourceInspectTaskService resourceInspectTaskService;

    @Override
    public void resourceInspectTaskJobProcess(String site) {
        String user = CommonMethods.getUser();
        ResourceInspectTask resourceInspectTask = new ResourceInspectTask();
        resourceInspectTask.setSite(site);
        resourceInspectTask.setCategory(Constants.INSPECTION_TYPE_DM);
        LocalDate now = LocalDate.now();
        LocalDateTime startDate = LocalDateTime.parse(now.minusDays(1) + "T00:00:00");
        LocalDateTime endDate = LocalDateTime.parse(now + "T00:00:00");
        resourceInspectTask.setPlanStartDate(startDate);
        resourceInspectTask.setPlanCompleteDate(endDate);
        List<ResourceInspectTask> inspectTaskList = resourceInspectTaskMapper.getInspectTaskList(resourceInspectTask);
        for (ResourceInspectTask inspectTask: inspectTaskList) {
            resourceInspectPlanService.autoCreateTaskByResourceInspectTask(inspectTask);
            inspectTask.setModifyUser(user);
            inspectTask.setModifiedDateTime(LocalDateTime.now());
        }
        if (inspectTaskList.size() > 0){
            resourceInspectTaskService.updateBatchById(inspectTaskList);
        }
    }
}
