package ${packageName}.controller;

import java.io.Serializable;
import java.util.List;
import java.util.regex.Pattern;


import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.core.controller.HcyBaseController;
import com.hchyun.common.utils.ServerResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hchyun.common.annotation.Log;
import com.hchyun.common.core.entity.AjaxResult;
import com.hchyun.common.enums.BusinessType;
import ${packageName}.entity.${ClassName};
import ${packageName}.service.${ClassName}Service;
import com.hchyun.common.utils.poi.ExcelUtil;
#if($table.crud || $table.sub)
import com.hchyun.common.core.page.TableDataInfo;
#elseif($table.tree)
#end

/**
 * ${functionName}Controller
 * 
 * @author ${author}
 * @date ${datetime}
 */
@Api(value = "${functionName}管理",tags = "${functionName}管理")
@RestController
@RequestMapping("/${moduleName}/${businessName}")
public class ${ClassName}Controller extends HcyBaseController {
    protected final Logger logger = LoggerFactory.getLogger(${ClassName}Controller.class);

    @Autowired
    private ${ClassName}Service ${className}Service;

    /**
     * 查询${functionName}列表
     */
    @ApiOperation("查询${functionName}列表")
    @PreAuthorize("@ss.hasPermi('${permissionPrefix}:list')")
    @GetMapping("/list")
#if($table.crud || $table.sub)
    public Serializable list(${ClassName} ${className}) {
        try {
            startPage();
            ServerResult<List<${ClassName}>> serverResult = ${className}Service.select${ClassName}List(${className});
            if (serverResult.isStart()) {
                return getDataTable(serverResult.getData());
            } else {
                return AjaxResult.info(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }
#elseif($table.tree)
    public AjaxResult list(${ClassName} ${className})
    {
        List<${ClassName}> list = ${className}Service.select${ClassName}List(${className});
        return AjaxResult.success(list);
    }
#end

    /**
     * 导出${functionName}列表
     */
    @ApiOperation("导出${functionName}列表")
    @PreAuthorize("@ss.hasPermi('${permissionPrefix}:export')")
    @Log(title = "${functionName}", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(${ClassName} ${className}) {
        try {
            ServerResult<List<${ClassName}>> serverResult = ${className}Service.select${ClassName}List(${className});
            ExcelUtil<${ClassName}> util = new ExcelUtil<${ClassName}>(${ClassName}. class);
            if (serverResult.isStart()) {
                return util.exportExcel(serverResult.getData(), "${businessName}");
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    /**
     * 获取${functionName}详细信息
     */
    @ApiOperation("获取${functionName}详细信息")
    @ApiImplicitParam(name = "${pkColumn.javaField}" , value = "${functionName}${pkColumn.javaField}" , required = true, dataType = "${pkColumn.javaType}" , paramType = "path")
    @PreAuthorize("@ss.hasPermi('${permissionPrefix}:query')")
    @GetMapping(value = "/{${pkColumn.javaField}}")
    public AjaxResult getInfo(@PathVariable("${pkColumn.javaField}") ${pkColumn.javaType} ${pkColumn.javaField}) {
        try {
            ServerResult<${ClassName}> serverResult = ${className}Service.select${ClassName}ById(${pkColumn.javaField});
            if (serverResult.isStart()) {
                return AjaxResult.success(serverResult.getData());
            } else {
                return AjaxResult.info(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    /**
     * 新增${functionName}
     */
    @ApiOperation("新增${functionName}")
    @ApiImplicitParam(name = "${className}" , value = "新增${functionName}信息" , dataType = "${ClassName}")
    @PreAuthorize("@ss.hasPermi('${permissionPrefix}:add')")
    @Log(title = "${functionName}", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ${ClassName} ${className}) {
#foreach ($column in $columns)
#if($column.isRequired == 1)
#if($column.javaField.length() > 2 && $column.javaField.substring(1,2).matches("[A-Z]"))
    #set($AttrName=$column.javaField)
#else
    #set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
#end
#if($column.javaType.equals("String"))
        if (${className}.get${AttrName}() == null || ${className}.get${AttrName}().equals("")) {
#elseif($column.javaType.equals("Integer")||$column.javaType.equals("Long"))
        if (${className}.get${AttrName}() == null || ${className}.get${AttrName}()<0) {
#end
            return AjaxResult.error("${column.columnComment}不能为空!");
        }
#end
#if($column.isRegular != 1)
        if (!Pattern.matches("${column.regular}",${className}.get${AttrName}())){
            return AjaxResult.error("${column.columnComment}格式错误!");
        }
#end
#end
        try {
            ServerResult<Integer> serverResult = ${className}Service.insert${ClassName}(${className});
            if (serverResult.isStart()) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    /**
     * 修改${functionName}
     */
    @ApiOperation("修改${functionName}")
    @ApiImplicitParam(name = "${className}" , value = "修改${functionName}信息" , dataType = "${ClassName}")
    @PreAuthorize("@ss.hasPermi('${permissionPrefix}:edit')")
    @Log(title = "${functionName}", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ${ClassName} ${className}) {
        try {

#foreach ($column in $columns)
#if($column.isRequired == 1)
#if($column.javaField.length() > 2 && $column.javaField.substring(1,2).matches("[A-Z]"))
    #set($AttrName=$column.javaField)
#else
    #set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
#end
#if($column.javaType.equals("String"))
            if (${className}.get${AttrName}() == null || ${className}.get${AttrName}().equals("")) {
#elseif($column.javaType.equals("Integer")||$column.javaType.equals("Long"))
            if (${className}.get${AttrName}() == null || ${className}.get${AttrName}()<0) {
#end
                return AjaxResult.error("${column.columnComment}不能为空!");
            }
#end
#if($column.isRegular != 1)
            if (!Pattern.matches("${column.regular}",${className}.get${AttrName}())){
                return AjaxResult.error("${column.columnComment}格式错误!");
            }
#end
#end
            ServerResult<Integer> serverResult = ${className}Service.update${ClassName}(${className});
            if (serverResult.isStart()) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    /**
     * 删除${functionName}
     */
    @ApiOperation("删除${functionName}")
    @ApiImplicitParam(name = "${pkColumn.javaField}s" , value = "${functionName}${pkColumn.javaField}s" , required = true, dataType = "${pkColumn.javaType}" , paramType = "path")
    @PreAuthorize("@ss.hasPermi('${permissionPrefix}:remove')")
    @Log(title = "${functionName}", businessType = BusinessType.DELETE)
	@DeleteMapping("/{${pkColumn.javaField}s}")
    public AjaxResult remove(@PathVariable ${pkColumn.javaType}[] ${pkColumn.javaField}s) {
        try {
            if (${pkColumn.javaField}s.length<0){
                return AjaxResult.error("id不能为空!");
            }
            ServerResult<Integer> serverResult = ${className}Service.delete${ClassName}ByIds(${pkColumn.javaField}s);
            if (serverResult.isStart()) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        }catch (RuntimeException e){
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }
}
