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

import cn.hutool.core.util.StrUtil;
import com.testor.ddd.safetyControl.domain.riskOwner.entity.TSafeRiskOwnerRepo;
import com.testor.ddd.safetyControl.domain.riskOwner.service.RiskOwnerService;
import com.testor.ddd.safetyControl.interfaces.model.dto.riskOwner.TSafeRiskOwnerDTO;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import org.springframework.stereotype.Service;

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

@Service
public class RiskOwnerServiceImpl implements RiskOwnerService {

    @Resource
    private TSafeRiskOwnerRepo riskOwnerRepo;


    /**
     * 编辑空间
     * @param type 1-危险源；2-风险点（风险分级）
     * @param riskBizId 危险源/风险点 id
     * @return
     */
    public BaseResponse editRiskOwner(Integer type, String riskBizId, List<TSafeRiskOwnerDTO> riskOwnerDtoList) throws RuntimeException {
        BaseResponse baseResponse = new BaseResponse<>();

        if((type != 1 && type != 2)
                || StrUtil.isBlank(riskBizId) ) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("参数缺失！");
            return baseResponse;
        }

        boolean deleteResult = riskOwnerRepo.deleteByRiskBizId(riskBizId);
//        if(!deleteResult) {
//            throw new RuntimeException("更改管控部门及负责人失败");
//        }

        if(riskOwnerDtoList == null || riskOwnerDtoList.size() == 0) {
            return baseResponse;
        }

        riskOwnerDtoList.forEach(riskOwnerDTO -> {
            riskOwnerDTO.setRiskId(riskBizId);
            riskOwnerDTO.setType(type);
        });
        boolean saveResult = riskOwnerRepo.saveBatch(riskOwnerDtoList);
        if(!saveResult) {
            throw new RuntimeException("更新管控部门及负责人失败");
        }
        return baseResponse;
    }

}
