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

import cn.hutool.core.util.StrUtil;
import com.testor.ddd.safetyControl.domain.riskMap.entity.TSafeRiskMapRepo;
import com.testor.ddd.safetyControl.domain.riskMap.service.RiskMapService;
import com.testor.ddd.safetyControl.interfaces.model.dto.riskMap.TSafeRiskMapDTO;
import com.testor.ddd.safetyControl.interfaces.model.dto.riskMap.TSafeRiskMapDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.vo.riskMap.TSafeRiskMapVO;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
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 RiskMapServiceImpl implements RiskMapService {

    @Resource
    private TSafeRiskMapRepo riskMapRepo;


    /**
     * 编辑空间
     *
     * @param riskMapDto
     * @return
     */
    @Override
    public BaseResponse<TSafeRiskMapDTO> editRiskMap(String userId, String orgId, TSafeRiskMapDTO riskMapDto) {
        BaseResponse baseResponse = new BaseResponse<>();


        boolean checkResult = checkUniqueness(orgId, riskMapDto.getId(), riskMapDto.getName());
        if (!checkResult) {
            baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
            baseResponse.setMsg("已存在相同名称的数据");
            return baseResponse;
        }

        String dataId = riskMapDto.getId();
        if (StrUtil.isBlank(dataId)) { // 新增
            riskMapDto.setCreateBy(userId);
            riskMapDto.setOrgId(orgId);
            riskMapDto = riskMapRepo.insert(riskMapDto);
            baseResponse.setData(riskMapDto);
            return baseResponse;
        }

        if (!orgId.equals(riskMapDto.getOrgId())) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("当前用户无法操作该条数据");
            return baseResponse;
        }

        riskMapDto.setUpdateBy(userId);
        riskMapDto =riskMapRepo.updateById(riskMapDto);
        baseResponse.setData(riskMapDto);
        return baseResponse;
    }

    @Override
    public BaseResponseList<TSafeRiskMapVO> listByPage(TSafeRiskMapDTOParam param){
        BaseResponseList<TSafeRiskMapVO> baseResponseList=new BaseResponseList<>();
        baseResponseList = riskMapRepo.listPage(param);
        return baseResponseList;
    }

    public TSafeRiskMapDTO findById(String id){
        return riskMapRepo.findById(id);
    }

    /**
     * 检测 名称 是否都唯一
     * @return true - 唯一； false - 不唯一
     */
    public boolean checkUniqueness(String orgId, String sourceId, String name){
        List<TSafeRiskMapDTO> sourceDTOList = riskMapRepo.checkUniqueness(orgId, sourceId, name);
        if(sourceDTOList == null || sourceDTOList.size() == 0) {
            return true;
        }
        return false;
    }
}
