package com.dsk.cscec.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsk.common.exception.ServiceException;
import com.dsk.cscec.domain.AdvisoryBodyCustomFormTemplate;
import com.dsk.cscec.mapper.AdvisoryBodyCustomFormTemplateMapper;
import com.dsk.cscec.service.AdvisoryBodyCustomFormTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 咨询机构自定义表单模板表(AdvisoryBodyCustomFormTemplate)表服务实现类
 *
 * @author sxk
 * @since 2024-01-15 16:53:20
 */
@Slf4j
@Service("advisoryBodyCustomFormTemplateService")
public class AdvisoryBodyCustomFormTemplateServiceImpl extends ServiceImpl<AdvisoryBodyCustomFormTemplateMapper, AdvisoryBodyCustomFormTemplate> implements AdvisoryBodyCustomFormTemplateService {
    @Resource
    private AdvisoryBodyCustomFormTemplateMapper baseMapper;

    /**
     * 编辑自定义表单模板
     *
     * @param customFormTemplate 编辑对象
     * @return 编辑结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer editCustomFormTemplate(AdvisoryBodyCustomFormTemplate customFormTemplate) {
        //模板ID为空,则为新增,否则为更新覆盖
        Long templateId = customFormTemplate.getTemplateId();
        if (ObjectUtil.isNull(templateId)) {
            templateId = IdUtil.getSnowflakeNextId();
            customFormTemplate.setTemplateId(templateId);
            log.info("新增自定义表单模板,模板ID:{}", templateId);
            return baseMapper.insert(customFormTemplate);
        } else {
            //校验模板是否存在
            if (!baseMapper.exists(new LambdaQueryWrapper<AdvisoryBodyCustomFormTemplate>()
                    .eq(AdvisoryBodyCustomFormTemplate::getTemplateId, customFormTemplate.getTemplateId()))) {
                throw new ServiceException("该自定义表单模板不存在");
            }
            log.info("更新自定义表单模板{}", templateId);
            return baseMapper.updateById(customFormTemplate);
        }
    }
}
