package com.njcn.advance.service.assess.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njcn.advance.enums.AdvanceResponseEnum;
import com.njcn.advance.mapper.assess.AssessDicCableTypeMapper;
import com.njcn.advance.pojo.param.assess.AssessDicCableTypeQuery;
import com.njcn.advance.pojo.po.assess.AssessDicCableType;
import com.njcn.advance.pojo.po.assess.AssessDicHarmonicCharacter;
import com.njcn.advance.service.assess.IAssessDicCableTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 线缆类型字典 服务实现类
 * </p>
 *
 * @author cdf
 * @since 2025-06-06
 */
@Service
public class AssessDicCableTypeServiceImpl extends ServiceImpl<AssessDicCableTypeMapper, AssessDicCableType>
        implements IAssessDicCableTypeService {

    @Override
    public AssessDicCableType getByLinetypeId(String linetypeId) {
        return this.getOne(Wrappers.<AssessDicCableType>lambdaQuery()
                .eq(AssessDicCableType::getLinetypeId, linetypeId));
    }

    @Override
    public List<AssessDicCableType> listByType(String linetypeType) {
        return this.list(Wrappers.<AssessDicCableType>lambdaQuery()
                .eq(AssessDicCableType::getLinetypeType, linetypeType));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(AssessDicCableTypeQuery param) {
        AssessDicCableType entity = new AssessDicCableType();
        int count = this.count(new LambdaQueryWrapper<AssessDicCableType>()
                .eq(AssessDicCableType::getLinetypeName, param.getLinetypeName())
        );
        if (count > 0) {
            throw new BusinessException(AdvanceResponseEnum.CABLETYPE_NAME_REPETITION);
        }
        BeanUtil.copyProperties(param,entity);
        return this.save(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AssessDicCableTypeQuery.UpdateAssessDicCableTypeQuery updateQuery) {
        AssessDicCableType entity = this.getByLinetypeId(updateQuery.getLinetypeId());
        if (entity != null) {
            int count = this.count(new LambdaQueryWrapper<AssessDicCableType>()
                    .ne(AssessDicCableType::getLinetypeId, updateQuery.getLinetypeId())
                    .eq(AssessDicCableType::getLinetypeName, updateQuery.getLinetypeName())
            );
            if (count > 0) {
                throw new BusinessException(AdvanceResponseEnum.CABLETYPE_NAME_REPETITION);
            }
            BeanUtil.copyProperties(updateQuery,entity);
            this.updateById(entity);
        }
    }
}