package ${packageName}.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ${packageName}.common.Result;
import ${packageName}.entity.${ClassName};
#if($hasQingCurrentUserColumn)
import ${packageName}.entity.PortalUser;
import ${packageName}.security.PortalAuthTokenStore;
#end
import ${packageName}.service.I${ClassName}Service;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
#if($hasQingCurrentUserColumn)
import javax.servlet.http.HttpServletRequest;
#end
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

#if($hasQingCurrentUserColumn)
    @Resource
    private PortalAuthTokenStore tokenStore;

#end

    #if($allowAdd == '1' || $allowEdit == '1')
    @PostMapping
    public Result<Void> save(@RequestBody ${ClassName} ${className})
    {
        #if($allowAdd == '1' && $allowEdit == '1')
        ${className}Service.saveOrUpdate(${className});
        #elseif($allowAdd == '1')
        ${className}Service.save(${className});
        #else
        ${className}Service.updateById(${className});
        #end
        return Result.success();
    }
    #end

    #if($allowRemove == '1')
    @DeleteMapping("/{${pkColumn.javaField}}")
    public Result<Void> delete(@PathVariable ${pkColumn.javaType} ${pkColumn.javaField})
    {
        ${className}Service.removeById(${pkColumn.javaField});
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result<Void> deleteBatch(@RequestBody List<${pkColumn.javaType}> ${pkColumn.javaField}s)
    {
        ${className}Service.removeByIds(${pkColumn.javaField}s);
        return Result.success();
    }
    #end

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

    @GetMapping("/{${pkColumn.javaField}}")
    public Result<${ClassName}> findOne(@PathVariable ${pkColumn.javaType} ${pkColumn.javaField})
    {
        return Result.success(${className}Service.getById(${pkColumn.javaField}));
    }

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

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception
    {
        List<${ClassName}> list = ${className}Service.list();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        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();
    }

    #if($allowAdd == '1')
    @PostMapping("/import")
    public Result<Void> imp(MultipartFile file) throws Exception
    {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<${ClassName}> list = reader.readAll(${ClassName}.class);
        ${className}Service.saveBatch(list);
        return Result.success();
    }
    #end

    private boolean hasValue(Object value)
    {
        return value != null && StringUtils.isNotBlank(String.valueOf(value));
    }

#if($hasQingCurrentUserColumn)
    private boolean isCurrentUserOnly(Map<String, Object> params)
    {
        return params != null && "true".equalsIgnoreCase(String.valueOf(params.get("__currentUserOnly")));
    }

    private String resolveToken(HttpServletRequest request)
    {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer "))
        {
            return authorization.substring("Bearer ".length());
        }
        return request.getHeader("X-Portal-Token");
    }
#end
}
