package com.njzscloud.common.gen;

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

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

/**
 * 代码模板
 */
@Slf4j
@Service
public class TplService extends ServiceImpl<TplMapper, TplEntity> implements IService<TplEntity> {

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

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

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

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

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

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

}
