package ${packageName}.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.net.URLEncoder;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot.common.Result;
import org.springframework.web.multipart.MultipartFile;
import com.example.springboot.entity.User;
import com.example.springboot.utils.TokenUtils;
import com.example.springboot.service.IUserService;

import ${packageName}.service.I${ClassName}Service;
import ${packageName}.entity.${ClassName};

/**
 * ${functionName}Controller
 * 
 * @author ${author}
 * @date ${datetime}
 */
@RestController
@RequestMapping("/${moduleName}/${businessName}")
public class ${ClassName}Controller
{
    @Resource
    private I${ClassName}Service ${className}Service;

    private final String now = DateUtil.now();

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody ${ClassName} ${className}) {
        if (${className}.getId() == null) {
            //${className}.setTime(DateUtil.now());
            //${className}.setUser(TokenUtils.getCurrentUser().getNickname());
            //${className}.setUserid(TokenUtils.getCurrentUser().getId());
        }
        ${className}Service.saveOrUpdate(${className});
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        ${className}Service.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        ${className}Service.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(${className}Service.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(${className}Service.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam(required = false) Integer pageNum,
                          @RequestParam(required = false) Integer pageSize,
                          @RequestParam(required = false) Map<String, Object> params) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        QueryWrapper<${ClassName}> queryWrapper = new QueryWrapper<>();
#foreach ($column in $columns)
#if($column.isQuery == "1")
#set($queryType=$column.queryType)
#set($javaField=$column.javaField)
#set($columnName=$column.columnName)
#if($column.queryType == "EQ")
        queryWrapper.eq(StringUtils.isNotEmpty((String)params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#elseif($queryType == "NE")
        queryWrapper.ne(StringUtils.isNotEmpty((String)params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#elseif($queryType == "GT")
        queryWrapper.gt(StringUtils.isNotEmpty((String)params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#elseif($queryType == "GTE")
        queryWrapper.ge(StringUtils.isNotEmpty((String)params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#elseif($queryType == "LT")
        queryWrapper.lt(StringUtils.isNotEmpty((String)params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#elseif($queryType == "LTE")
        queryWrapper.le(StringUtils.isNotEmpty((String)params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#elseif($queryType == "LIKE")
        queryWrapper.like(StringUtils.isNotEmpty((String)params.get("${javaField}")), "${columnName}", params.get("${javaField}"));
#end
#end
#end
        queryWrapper.orderByDesc("${pkColumn.columnName}");
        return Result.success(${className}Service.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
    * 导出接口
    */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<${ClassName}> list = ${className}Service.list();
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("${functionName}信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        List<${ClassName}> list = reader.readAll(${ClassName}.class);

        ${className}Service.saveBatch(list);
        return Result.success();
    }
}
