package ${package};

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.constant.GlobalConstant;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.${outputArea}.dto.Add${entityClass}Dto;
import com.xjrsoft.module.${outputArea}.dto.Update${entityClass}Dto;
import cn.dev33.satoken.annotation.SaCheckPermission;
<#if codeRules != "">
import com.xjrsoft.module.system.service.ICodeRuleService;
</#if>
<#if isImport || isExport>
import com.alibaba.excel.EasyExcel;
</#if>
<#if isImport>
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
</#if>
<#if isExport>
import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.http.ResponseEntity;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
</#if>

<#if !isPage>
import com.xjrsoft.module.${outputArea}.dto.${entityClass}ListDto;
<#else>
import com.xjrsoft.module.${outputArea}.dto.${entityClass}PageDto;
</#if>
import com.xjrsoft.module.${outputArea}.entity.${entityClass};
import com.xjrsoft.module.${outputArea}.service.I${className}Service;
<#if !isPage>
import com.xjrsoft.module.${outputArea}.vo.${entityClass}ListVo;
<#else>
import com.xjrsoft.module.${outputArea}.vo.${entityClass}PageVo;
</#if>
<#if isDataAuth>
import com.xjrsoft.module.authority.dto.BatchSetDataAuthDto;
import java.util.stream.Collectors;
import java.util.ArrayList;
</#if>

import com.xjrsoft.module.${outputArea}.vo.${entityClass}Vo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
* @title: ${tableComment}
* @Author ${author}
* @Date: ${date}
* @Version 1.0
*/
@RestController
@RequestMapping("/${outputArea}" + "/${className?lower_case}")
@Api(value = "/${outputArea}"  + "/${className?lower_case}",tags = "${tableComment}代码")
@AllArgsConstructor
public class ${className}Controller {


    private final I${className}Service ${className?uncap_first}Service;
<#if codeRules != "">
    private final ICodeRuleService codeRuleService;
</#if>

<#if !isPage>
    @GetMapping(value = "/list")
    @ApiOperation(value="${entityClass}列表(不分页)")
    @SaCheckPermission("${className?lower_case}:detail")
    public R list(@Valid ${entityClass}ListDto dto){

        LambdaQueryWrapper<${entityClass}> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
            <#--属性遍历-->
            <#list fields as field>
                <#if field.fieldType == "String">
                    .like(StrUtil.isNotBlank(dto.get${field.fieldName?cap_first}()),${entityClass}::get${field.fieldName?cap_first},dto.get${field.fieldName?cap_first}())
                <#elseif field.fieldType == "Integer" || field.fieldType == "Long"|| field.fieldType == "Double"|| field.fieldType == "Float"|| field.fieldType == "Boolean"|| field.fieldType == "BigDecimal" >
                    .eq(ObjectUtil.isNotNull(dto.get${field.fieldName?cap_first}()),${entityClass}::get${field.fieldName?cap_first},dto.get${field.fieldName?cap_first}())
                <#elseif field.fieldType == "LocalDateTime" || field.fieldType == "LocalTime">
                    .between(ObjectUtil.isNotNull(dto.get${field.fieldName?cap_first}Start()) && ObjectUtil.isNotNull(dto.get${field.fieldName?cap_first}End()),${entityClass}::get${field.fieldName?cap_first},dto.get${field.fieldName?cap_first}Start(),dto.get${field.fieldName?cap_first}End())
                <#else>
                    .like(StrUtil.isNotBlank(dto.get${field.fieldName?cap_first}()),${entityClass}::get${field.fieldName?cap_first},dto.get${field.fieldName?cap_first}())
                </#if>
            </#list>
                <#--默认排序-->
                <#if orderField?? && orderField != "">
                    <#if orderType>
                    .orderByDesc(${entityClass}::get${orderField?cap_first})
                    <#else>
                    .orderByAsc(${entityClass}::get${orderField?cap_first})
                    </#if>
<#--                    如果需要根据前端所传字段排序 屏蔽上面  放开下面-->
<#--                    .orderBy(StrUtil.isBlank(dto.getOrderField()),${orderType?string("false","true")},${entityClass}::get${orderField?cap_first})-->
<#--                    .last(StrUtil.isNotBlank(dto.getOrderField()) && StrUtil.isNotBlank(dto.getOrder()),"order by " + dto.getOrderField() + StringPool.SPACE + dto.getOrder())-->
                </#if>
                    .select(${entityClass}.class,x -> VoToColumnUtil.fieldsToColumns(${entityClass}ListVo.class).contains(x.getProperty()));

        List<${entityClass}> list = ${className?uncap_first}Service.list(queryWrapper);
        List<${entityClass}ListVo> listVos = BeanUtil.copyToList(list, ${entityClass}ListVo.class);
        return R.ok(listVos);
    }
<#else>
    @GetMapping(value = "/page")
    @ApiOperation(value="${entityClass}列表(分页)")
    @SaCheckPermission("${className?lower_case}:detail")
    public R page(@Valid ${entityClass}PageDto dto){

        LambdaQueryWrapper<${entityClass}> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
        <#--属性遍历-->
        <#list fields as field>
            <#if field.fieldType == "String">
                .like(StrUtil.isNotBlank(dto.get${field.fieldName?cap_first}()),${entityClass}::get${field.fieldName?cap_first},dto.get${field.fieldName?cap_first}())
            <#elseif field.fieldType == "Integer" || field.fieldType == "Long"|| field.fieldType == "Double"|| field.fieldType == "Float"|| field.fieldType == "Boolean" || field.fieldType == "BigDecimal" >
                .eq(ObjectUtil.isNotNull(dto.get${field.fieldName?cap_first}()),${entityClass}::get${field.fieldName?cap_first},dto.get${field.fieldName?cap_first}())
            <#elseif field.fieldType == "LocalDateTime" || field.fieldType == "LocalTime">
                .between(ObjectUtil.isNotNull(dto.get${field.fieldName?cap_first}Start()) && ObjectUtil.isNotNull(dto.get${field.fieldName?cap_first}End()),${entityClass}::get${field.fieldName?cap_first},dto.get${field.fieldName?cap_first}Start(),dto.get${field.fieldName?cap_first}End())
            <#else>
                .like(StrUtil.isNotBlank(dto.get${field.fieldName?cap_first}()),${entityClass}::get${field.fieldName?cap_first},dto.get${field.fieldName?cap_first}())
            </#if>
        </#list>
            <#--默认排序-->
            <#if orderField?? && orderField != "">
                <#if orderType>
                    .orderByDesc(${entityClass}::get${orderField?cap_first})
                <#else>
                    .orderByAsc(${entityClass}::get${orderField?cap_first})
                </#if>
<#--                .orderBy(StrUtil.isBlank(dto.getOrderField()),${orderType?string("false","true")},${entityClass}::get${orderField?cap_first})-->
            </#if>
                .select(${entityClass}.class,x -> VoToColumnUtil.fieldsToColumns(${entityClass}PageVo.class).contains(x.getProperty()));
        IPage<${entityClass}> page = ${className?uncap_first}Service.page(ConventPage.getPage(dto), queryWrapper);
        PageOutput<${entityClass}PageVo> pageOutput = ConventPage.getPageOutput(page, ${entityClass}PageVo.class);
        return R.ok(pageOutput);
    }
</#if>

    @GetMapping(value = "/info")
    @ApiOperation(value="根据id查询${entityClass}信息")
    @SaCheckPermission("${className?lower_case}:detail")
    public R info(@RequestParam ${pkType} id){
        ${entityClass} ${entityClass?uncap_first} = ${className?uncap_first}Service.${isMulti?string("getByIdDeep","getById")}(id);
        if (${entityClass?uncap_first} == null) {
           return R.error("找不到此数据！");
        }
        return R.ok(BeanUtil.toBean(${entityClass?uncap_first}, ${entityClass}Vo.class));
    }


    @PostMapping
    @ApiOperation(value = "新增${entityClass}")
    @SaCheckPermission("${className?lower_case}:add")
    public R add(@Valid @RequestBody Add${entityClass}Dto dto){
    <#if isMulti>
        ${entityClass} ${entityClass?uncap_first} = BeanUtil.toBean(dto, ${entityClass}.class);
        boolean isSuccess = ${className?uncap_first}Service.add(${entityClass?uncap_first});
    <#else >
        ${entityClass} ${entityClass?uncap_first} = BeanUtil.toBean(dto, ${entityClass}.class);
        boolean isSuccess = ${className?uncap_first}Service.save(${entityClass?uncap_first});
    </#if>
    <#if codeRules != "">
        codeRuleService.useEncode("${codeRules}");
    </#if>
        return R.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改${entityClass}")
    @SaCheckPermission("${className?lower_case}:edit")
    public R update(@Valid @RequestBody Update${entityClass}Dto dto){

    <#if isMulti>
        ${entityClass} ${entityClass?uncap_first} = BeanUtil.toBean(dto, ${entityClass}.class);
        return R.ok(${className?uncap_first}Service.update(${entityClass?uncap_first}));
    <#else >
        ${entityClass} ${entityClass?uncap_first} = BeanUtil.toBean(dto, ${entityClass}.class);
        return R.ok(${className?uncap_first}Service.updateById(${entityClass?uncap_first}));
    </#if>

    }

    @DeleteMapping
    @ApiOperation(value = "删除")
    @SaCheckPermission("${className?lower_case}:delete")
    public R delete(@Valid @RequestBody List<${pkType}> ids){
    <#if isMulti>
        return R.ok(${className?uncap_first}Service.delete(ids));
    <#else >
        return R.ok(${className?uncap_first}Service.removeBatchByIds(ids));
    </#if>

    }
<#if isPage>
<#assign importClass = "${entityClass}Page">
<#else>
<#assign importClass = "${entityClass}List">
</#if>
<#if isImport>
    @PostMapping("/import")
    @ApiOperation(value = "导入")
    public R importData(@RequestParam MultipartFile file) throws IOException {
        List<${importClass}Vo> savedDataList = EasyExcel.read(file.getInputStream()).head(${importClass}Vo.class).sheet().doReadSync();
        ${className?uncap_first}Service.saveBatch(BeanUtil.copyToList(savedDataList, ${entityClass}.class));
        return R.ok();
    }
</#if>

<#if isExport>
    @GetMapping("/export")
    @ApiOperation(value = "导出")
    public ResponseEntity<byte[]> exportData(@Valid ${importClass}Dto dto, @RequestParam(defaultValue = "false") Boolean isTemplate) {
<#if isPage>
        List<${importClass}Vo> customerList = isTemplate != null && isTemplate ? new ArrayList<>() : ((PageOutput<${importClass}Vo>) page(dto).getData()).getList();
<#else>
        List<${importClass}Vo> customerList = (List<${importClass}Vo>) page(dto).getData());
</#if>
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, ${importClass}Vo.class).automaticMergeHead(false).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(customerList);

        return R.fileStream(bot.toByteArray(), "${className}" + ExcelTypeEnum.XLSX.getValue());
    }
</#if>
<#if isDataAuth>
    @PutMapping("/data-auth")
    @ApiOperation(value = "批量设置权限所属人")
    public R setDataAUth(@RequestBody BatchSetDataAuthDto dto){
        List<${entityClass}> toUpdateList = new ArrayList<>();
<#--        String userIdStr = dto.getUserIdList().stream().collect(Collectors.joining(StringPool.COMMA));-->
        for (Long dataId : dto.getDataIdList()) {
            ${entityClass} ${entityClass?uncap_first} = new ${entityClass}();
            ${entityClass?uncap_first}.set${pkField?cap_first}(dataId);
            ${entityClass?uncap_first}.setRuleUserId(dto.getUserIdList().get(0));
            toUpdateList.add(${entityClass?uncap_first});
        }
        return R.ok(${className?uncap_first}Service.updateBatchById(toUpdateList));
    }
</#if>
}