package com.testor.ddd.safetyControl.domain.riskPointSource.service.impl;

import cn.hutool.core.util.StrUtil;
import com.testor.ddd.safetyControl.domain.riskPointSource.entity.TSafeRiskPointSourceRepo;
import com.testor.ddd.safetyControl.domain.riskPointSource.service.RiskPointSourceService;
import com.testor.ddd.safetyControl.interfaces.model.dto.riskPointSource.TSafeRiskPointSourceDTO;
import com.testor.ddd.safetyControl.interfaces.model.dto.riskPointSource.TSafeRiskPointSourceDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.vo.riskPoint.RiskPointSourceVO;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RiskPointSourceServiceImpl implements RiskPointSourceService {

    @Resource
    private TSafeRiskPointSourceRepo riskPointSourceRepo;

    public boolean saveBatch(String orgId, String pointId, List<TSafeRiskPointSourceDTO> riskPointSourceDTOList){
        if(StrUtil.isBlank(orgId) || StrUtil.isBlank(pointId)
        || riskPointSourceDTOList == null || riskPointSourceDTOList.size() == 0) {
            return false;
        }

        List<String> sourIdList = new ArrayList();
        for(TSafeRiskPointSourceDTO riskPointSourceDTO:riskPointSourceDTOList) {
            sourIdList.add(riskPointSourceDTO.getSourceId());
        }
        TSafeRiskPointSourceDTOParam param = new TSafeRiskPointSourceDTOParam();
        param.setNotPointId(pointId);
        param.setCondSourceIdList(sourIdList);
        param.setStatus(BizConstants.STATUS_ENABLE);
        List<RiskPointSourceVO> list = riskPointSourceRepo.listAll(param);
        // 检测如果已存在 关联的危险源 则不允许保存
        if(list != null && list.size() > 0) {
            return false;
        }

        riskPointSourceRepo.deleteByPointId(pointId);
        riskPointSourceDTOList.stream().forEach(item -> {
            item.setOrgId(orgId);
            item.setPointId(pointId);
        });

        return riskPointSourceRepo.saveBatch(riskPointSourceDTOList);
    }
}
