package com.dsk.cscec.service.impl;

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.AdvisoryBodyCustomFormData;
import com.dsk.cscec.domain.AdvisoryBodyCustomFormTemplate;
import com.dsk.cscec.mapper.AdvisoryBodyCustomFormDataMapper;
import com.dsk.cscec.mapper.AdvisoryBodyCustomFormTemplateMapper;
import com.dsk.cscec.service.AdvisoryBodyCustomFormDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 咨询机构自定义表单数据表(AdvisoryBodyCustomFormData)表服务实现类
 *
 * @author sxk
 * @since 2023-12-20 17:33:31
 */
@Slf4j
@Service("advisoryBodyCustomFormService")
public class AdvisoryBodyCustomFormDataServiceImpl extends ServiceImpl<AdvisoryBodyCustomFormDataMapper, AdvisoryBodyCustomFormData> implements AdvisoryBodyCustomFormDataService {
    @Resource
    private AdvisoryBodyCustomFormDataMapper baseMapper;
    @Resource
    private AdvisoryBodyCustomFormTemplateMapper templateMapper;

    /**
     * 编辑自定义表单数据表数据
     *
     * @param customFormData 编辑信息
     * @return 编辑结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer editCustomFormData(AdvisoryBodyCustomFormData customFormData) {
        //校验自定义表单模板是否存在
        if (!templateMapper.exists(new LambdaQueryWrapper<AdvisoryBodyCustomFormTemplate>()
                .eq(AdvisoryBodyCustomFormTemplate::getTemplateId, customFormData.getTemplateId()))) {
            throw new ServiceException("自定义表单模板不存在");
        }

        //数据存在,走更新覆盖;否则走新增
        if (baseMapper.exists(new LambdaQueryWrapper<AdvisoryBodyCustomFormData>()
                .eq(AdvisoryBodyCustomFormData::getProjectKey, customFormData.getProjectKey()))) {
            log.info("项目{}更新自定义表单数据", customFormData.getTemplateId());
            return baseMapper.updateById(customFormData);
        } else {
            log.info("项目{}新增自定义表单数据", customFormData.getTemplateId());
            return baseMapper.insert(customFormData);
        }
    }
}
