package com.njzscloud.common.gen;

import com.njzscloud.common.core.utils.Mime;
import com.njzscloud.common.core.utils.R;
import com.njzscloud.common.gen.support.Generator;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 代码模板
 */
@Slf4j
@RestController
@RequestMapping("/tpl")
@RequiredArgsConstructor
public class TplController {

    private final TplService tplService;

    /**
     * 新增
     */
    @PostMapping("/add")
    public R<?> add(@RequestBody TplEntity tplEntity) {
        tplService.add(tplEntity);
        return R.success();
    }

    /**
     * 修改
     */
    @PostMapping("/modify")
    public R<?> modify(@RequestBody TplEntity tplEntity) {
        tplService.modify(tplEntity);
        return R.success();
    }

    /**
     * 删除
     */
    @PostMapping("/del")
    public R<?> del(@RequestBody List<Long> ids) {
        tplService.del(ids);
        return R.success();
    }

    @PostMapping("/generate")
    public void generate(@RequestParam String tplName, @RequestBody(required = false) Map<String, Object> data, HttpServletResponse response) {
        try {
            response.setContentType(Mime.u8Val(Mime.TXT));
            Generator.generate(tplName, data, response.getOutputStream());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 详情
     */
    @GetMapping("/detail")
    public R<TplEntity> detail(@RequestParam Long id) {
        return R.success(tplService.detail(id));
    }

    /**
     * 分页查询
     */
    @GetMapping("/paging")
    public R<PageResult<TplEntity>> paging(PageParam pageParam, TplEntity tplEntity) {
        return R.success(tplService.paging(pageParam, tplEntity));
    }

}
