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.util.DateUtil;
import com.testor.module.hazard.dao.THazardDisclosureDao;
import com.testor.module.hazard.model.domain.THazardDisclosure;
import com.testor.module.hazard.model.domain.THazardDisclosureDetails;
import com.testor.module.hazard.model.dto.THazardDisclosureDTO;
import com.testor.module.hazard.model.dto.THazardWorkPlanDTO;
import com.testor.module.hazard.service.THazardDisclosureDetailsService;
import com.testor.module.hazard.service.THazardDisclosureService;
import com.testor.module.hazard.service.THazardWorkPlanService;
import com.tongtech.tfw.backend.common.models.exceptions.ServiceException;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.apache.commons.lang3.StringUtils;
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.util.Date;
import java.util.List;

/**
 * 危险作业-交底信息Service业务层处理
 * 
 * @author testor-framework
 * @date 2024-12-28 19:52:55
 */
@Service
public class THazardDisclosureServiceImpl extends SuperServiceImpl<THazardDisclosureDao, THazardDisclosure> implements THazardDisclosureService
{
    @Autowired(required = false)
    private THazardDisclosureDao tHazardDisclosureDao;
    @Autowired
    private THazardDisclosureDetailsService tHazardDisclosureDetailsService;
    @Autowired
    private THazardWorkPlanService tHazardWorkPlanService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public THazardDisclosure saveOrUpdateEntity(THazardDisclosureDTO addRequest) {
        THazardDisclosure data= BeanHelper.beanToBean(addRequest,  THazardDisclosure.class);
        String id = addRequest.getId();

        LambdaQueryWrapper<THazardDisclosure> tHazardDisclosureLambdaQueryWrapper = new LambdaQueryWrapper<THazardDisclosure>()
                .eq(THazardDisclosure::getPlanId, addRequest.getPlanId())
                .eq(THazardDisclosure::getWorkTypeId, addRequest.getWorkTypeId())
                .orderByDesc(THazardDisclosure::getBatch);


        //新增
        if (StringUtils.isBlank(id)) {
            //获取交底记录
            List<THazardDisclosure> tHazardDisclosures = this.list(tHazardDisclosureLambdaQueryWrapper);
            //如果记录不为空
            if (tHazardDisclosures != null && !tHazardDisclosures.isEmpty()) {
                THazardDisclosure tHazardDisclosure = tHazardDisclosures.get(0);
                Date createDate = tHazardDisclosure.getCreateDate();
                LocalDateTime createDatelocalDateTime = DateUtil.dateToLocalDateTime(createDate);

                //如果当前时间在最大批次之后
                if (DateUtil.notSameDayAndAfter(LocalDateTime.now(),createDatelocalDateTime)){
                    data.setBatch(tHazardDisclosure.getBatch() + 1);
                }else {
                    throw new ServiceException("同一天只能新增一次同作业类型的安全交底");
                }
            }
        }else {
            //修改
            THazardDisclosure existingEntity = this.getById(id);
            if (existingEntity != null){
                Integer batch = existingEntity.getBatch();
                // 检查是否有同一批次但不同ID的记录
                tHazardDisclosureLambdaQueryWrapper.ne(THazardDisclosure::getId, id)
                        .eq(THazardDisclosure::getBatch, batch);
                if (this.count(tHazardDisclosureLambdaQueryWrapper) > 0) {
                    throw new RuntimeException("当前危险作业计划已存在该作业类型安全交底信息");
                }
            }
        }

        this.saveOrUpdate(data);
        tHazardDisclosureDetailsService.remove(new QueryWrapper<THazardDisclosureDetails>().eq("disclosure_id",data.getId()));
        List<THazardDisclosureDetails> hazardDisclosureDetailsList = addRequest.getHazardDisclosureDetailsList();
        if (hazardDisclosureDetailsList != null) {
            for (THazardDisclosureDetails hazardDisclosureDetails : hazardDisclosureDetailsList) {
                hazardDisclosureDetails.setDisclosureId(data.getId());
                tHazardDisclosureDetailsService.save(hazardDisclosureDetails);
            }
        }
        return data;
    }

    @Override
    public THazardDisclosureDTO getDetailsById(String planId, String workTypeId, String batch) {
        List<THazardDisclosure> tHazardDisclosures = this.list(new QueryWrapper<THazardDisclosure>()
                .eq("plan_id", planId)
                .eq("work_type_id",workTypeId)
                .eq("batch",batch)
                .orderByDesc("create_date"));
        THazardDisclosureDTO tHazardDisclosureDTO = new THazardDisclosureDTO();
        THazardWorkPlanDTO tHazardWorkPlanDTO = tHazardWorkPlanService.getDetailsById(planId);
        tHazardDisclosureDTO.setHazardWorkPlanDTO(tHazardWorkPlanDTO);
        if (tHazardDisclosures != null && !tHazardDisclosures.isEmpty()) {
            THazardDisclosure tHazardDisclosure = tHazardDisclosures.get(0);
            tHazardDisclosureDTO = BeanHelper.beanToBean(tHazardDisclosure, THazardDisclosureDTO.class);
            String orgNamesByUserIds = tHazardWorkPlanService.getOrgNamesByUserIds(tHazardWorkPlanDTO.getOperator());
            //被交底机构
            tHazardWorkPlanDTO.setDisclosedUnitName(orgNamesByUserIds);
            tHazardDisclosureDTO.setHazardDisclosureDetailsList(tHazardDisclosureDetailsService.list(new QueryWrapper<THazardDisclosureDetails>().eq("disclosure_id", tHazardDisclosure.getId())));
            return tHazardDisclosureDTO;
        }
        return null;
    }


}
