package com.testor.module.hazard.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.common.core.utils.StringUtils;
import com.testor.module.hazard.dao.THazardAssessmentDao;
import com.testor.module.hazard.model.domain.THazardAssessment;
import com.testor.module.hazard.model.domain.THazardAssessmentDetails;
import com.testor.module.hazard.model.domain.THazardWorkPlan;
import com.testor.module.hazard.model.dto.THazardAssessmentDTO;
import com.testor.module.hazard.service.THazardAssessmentDetailsService;
import com.testor.module.hazard.service.THazardAssessmentService;
import com.testor.module.hazard.service.THazardWorkPlanService;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.springframework.stereotype.Service;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 安全风险分析Service业务层处理
 * 
 * @author testor-framework
 * @date 2024-12-24 17:17:29
 */
@Service
public class THazardAssessmentServiceImpl extends SuperServiceImpl<THazardAssessmentDao, THazardAssessment> implements THazardAssessmentService
{
    @Autowired(required = false)
    private THazardAssessmentDao tHazardAssessmentDao;
    @Autowired
    private THazardAssessmentDetailsService tHazardAssessmentDetailsService;
    @Autowired
    private THazardWorkPlanService tHazardWorkPlanService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public THazardAssessment addEntity(THazardAssessmentDTO tHazardAssessmentDTO) {
        THazardAssessment data = BeanHelper.beanToBean(tHazardAssessmentDTO, THazardAssessment.class);
        this.saveOrUpdate(data);
        String id = data.getId();
        tHazardAssessmentDetailsService.remove(new QueryWrapper<THazardAssessmentDetails>().eq("assessment_id", id));
        List<THazardAssessmentDetails> tHazardAssessmentDetails = tHazardAssessmentDTO.getTHazardAssessmentDetails();
        for (THazardAssessmentDetails tHazardAssessmentDetail : tHazardAssessmentDetails) {
            tHazardAssessmentDetail.setAssessmentId(id);
            tHazardAssessmentDetail.setId(IdHelper.getId32bit());
            tHazardAssessmentDetailsService.save(tHazardAssessmentDetail);
        }
        return data;
    }

    @Override
    public THazardAssessmentDTO getDetailsById(String typeId,String planId,String completeTime) {
        THazardAssessment tHazardAssessment = null;
        final int MAX_ATTEMPTS = 5;

        int count = this.count(
                new LambdaQueryWrapper<THazardAssessment>()
                        .eq(THazardAssessment::getWorkTypeId, typeId)
                        .eq(THazardAssessment::getPlanId, planId));
        if(count>1){
            if (StringUtils.isEmpty(completeTime)) {
                // 构建不含时间条件的查询
                tHazardAssessment = this.getOne(
                        new LambdaQueryWrapper<THazardAssessment>()
                                .eq(THazardAssessment::getWorkTypeId, typeId)
                                .eq(THazardAssessment::getPlanId, planId)
                );
            } else {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                // 尝试原始时间
                tHazardAssessment = this.getOne(
                        new LambdaQueryWrapper<THazardAssessment>()
                                .eq(THazardAssessment::getWorkTypeId, typeId)
                                .eq(THazardAssessment::getPlanId, planId)
                                .eq(THazardAssessment::getCreateDate, completeTime)
                );

                // 时间递减查询（最多5次）
                if (tHazardAssessment == null) {
                    LocalDateTime dateTime = LocalDateTime.parse(completeTime, formatter);

                    for (int i = 1; i <= MAX_ATTEMPTS; i++) {
                        // 每次递减1秒
                        LocalDateTime adjustedTime = dateTime.minusSeconds(i);
                        String newTime = adjustedTime.format(formatter);

                        // 每次创建全新的查询条件
                        tHazardAssessment = this.getOne(
                                new LambdaQueryWrapper<THazardAssessment>()
                                        .eq(THazardAssessment::getWorkTypeId, typeId)
                                        .eq(THazardAssessment::getPlanId, planId)
                                        .eq(THazardAssessment::getCreateDate, newTime)
                        );

                        if (tHazardAssessment != null) break;
                    }
                }
            }
        }else{
            tHazardAssessment = this.getOne(
                    new LambdaQueryWrapper<THazardAssessment>()
                            .eq(THazardAssessment::getWorkTypeId, typeId)
                            .eq(THazardAssessment::getPlanId, planId)
            );
        }

        if(tHazardAssessment == null){
            return null;
        }


        THazardAssessmentDTO tHazardAssessmentDTO = BeanHelper.beanToBean(tHazardAssessment, THazardAssessmentDTO.class);
        THazardWorkPlan tHazardWorkPlan = tHazardWorkPlanService.getById(tHazardAssessment.getPlanId());
        //设置作业单位
        String workUnit = tHazardWorkPlan.getWorkUnit();
        tHazardAssessmentDTO.setWorkUnitName(tHazardWorkPlanService.getOrgNamesByOrgId(workUnit));;
        //作业内容
        tHazardAssessmentDTO.setWorkContent(tHazardWorkPlan.getWorkContent());
        //作业开始时间
        tHazardAssessmentDTO.setScheduledStartTime(tHazardWorkPlan.getScheduledStartTime());
        //作业结束时间
        tHazardAssessmentDTO.setScheduledEndTime(tHazardWorkPlan.getScheduledEndTime());
        //作业地点
        tHazardAssessmentDTO.setWorkLocation(tHazardWorkPlan.getWorkLocation());
        List<THazardAssessmentDetails> assessmentId = tHazardAssessmentDetailsService.list(new QueryWrapper<THazardAssessmentDetails>().eq("assessment_id", tHazardAssessment.getId()));
        for(THazardAssessmentDetails tHazardAssessmentDetails : assessmentId){
            if(StringUtils.isEmpty(tHazardAssessmentDetails.getConsequence())){
                tHazardAssessmentDetails.setConsequence("");
            }
            if(StringUtils.isEmpty(tHazardAssessmentDetails.getControlMeasures())){
                tHazardAssessmentDetails.setControlMeasures("");
            }
            if(StringUtils.isEmpty(tHazardAssessmentDetails.getMajorRisk())){
                tHazardAssessmentDetails.setMajorRisk("");
            }
        }
        tHazardAssessmentDTO.setTHazardAssessmentDetails(assessmentId);
        return tHazardAssessmentDTO;
    }

    @Override
    public void initData(String workTypes, THazardWorkPlan tHazardWorkPlan) {
        String[] workTypesArray = workTypes.split(",");
        for (String workType : workTypesArray) {
            THazardAssessment tHazardAssessment = new THazardAssessment();
            tHazardAssessment.setId(IdHelper.getId32bit());
            tHazardAssessment.setWorkTypeId(workType);
            tHazardAssessment.setPlanId(tHazardWorkPlan.getId());
            this.save(tHazardAssessment);
        }
    }
}
