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

import cn.hutool.core.util.StrUtil;
import com.testor.ddd.safetyControl.domain.riskPoint.entity.TSafeRiskPointRepo;
import com.testor.ddd.safetyControl.domain.riskPoint.service.RiskPointService;
import com.testor.ddd.safetyControl.interfaces.model.dto.riskPoint.TSafeRiskPointDTO;
import com.testor.ddd.safetyControl.interfaces.model.dto.riskPoint.TSafeRiskPointDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.vo.riskPoint.TSafeRiskPointVO;
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 RiskPointServiceImpl implements RiskPointService {

    @Resource
    private TSafeRiskPointRepo riskPointRepo;


    /**
     * 编辑空间
     *
     * @param riskPointDto
     * @return
     */
    public BaseResponse<TSafeRiskPointDTO> editRiskPoint(String userId, String orgId, TSafeRiskPointDTO riskPointDto) {
        BaseResponse baseResponse = new BaseResponse<>();

        String dataId = riskPointDto.getId();

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

        if (StrUtil.isBlank(dataId)) { // 新增
            riskPointDto.setCreateBy(userId);
            riskPointDto.setOrgId(orgId);
            riskPointDto = riskPointRepo.insert(riskPointDto);
            baseResponse.setData(riskPointDto);
            return baseResponse;
        }

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

        riskPointDto.setUpdateBy(userId);
        riskPointDto =riskPointRepo.updateById(riskPointDto);
        baseResponse.setData(riskPointDto);
        return baseResponse;
    }

    public BaseResponseList<TSafeRiskPointVO> listByPage(TSafeRiskPointDTOParam param){
        BaseResponseList<TSafeRiskPointVO> baseResponseList=new BaseResponseList<>();
        baseResponseList = riskPointRepo.listPage(param);
        return baseResponseList;
    }

    public TSafeRiskPointDTO findById(String id){
        return riskPointRepo.findById(id);
    }

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