package com.njzscloud.common.gen;

import cn.hutool.core.map.MapUtil;
import com.njzscloud.common.gen.support.TemplateEngine;
import com.njzscloud.common.gen.support.Tpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 代码模板
 */
@Slf4j
@Service
public class SysTplService extends ServiceImpl<SysTplMapper, SysTplEntity> implements IService<SysTplEntity> {

    /**
     * 新增
     *
     * @param sysTplEntity 数据
     */
    public void add(SysTplEntity sysTplEntity) {
        Tpl tpl = sysTplEntity.getTpl();
        if (tpl == null) {
            sysTplEntity.setTpl(new Tpl());
        }

        Map<String, Object> modelData = sysTplEntity.getModelData();
        if (modelData == null) {
            sysTplEntity.setModelData(MapUtil.empty());
        }
        this.save(sysTplEntity);
    }

    /**
     * 修改
     *
     * @param sysTplEntity 数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void modify(SysTplEntity sysTplEntity) {
        Long id = sysTplEntity.getId();
        SysTplEntity oldData = this.getById(id);
        TemplateEngine.rmEngine(oldData.getTplName());
        this.updateById(sysTplEntity);
    }

    /**
     * 删除
     *
     * @param ids Ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 详情
     *
     * @param id Id
     * @return SysTplEntity 结果
     */
    public SysTplEntity detail(Long id) {
        return this.getById(id);
    }

    /**
     * 分页查询
     *
     * @param sysTplEntity 筛选条件
     * @param pageParam    分页参数
     * @return PageResult&lt;SysTplEntity&gt; 分页结果
     */
    public PageResult<SysTplEntity> paging(PageParam pageParam, SysTplEntity sysTplEntity) {
        return PageResult.of(this.page(pageParam.toPage(), Wrappers.<SysTplEntity>query(sysTplEntity)));
    }

}
