package cn.ibizlab.demoapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.validation.annotation.Validated;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.demoapi.dto.*;
import cn.ibizlab.demoapi.mapping.*;
import cn.ibizlab.core.sample.domain.IBIZCustom;
import cn.ibizlab.core.sample.service.IBIZCustomService;
import cn.ibizlab.core.sample.filter.IBIZCustomSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"自定义" })
@RestController("demoapi-ibizcustom")
@RequestMapping("${ibiz.rest.basePath.demoapi:/demoapi/}")
public class IBIZCustomResource {

    @Autowired
    public IBIZCustomService ibizCustomService;

    @Autowired
    @Lazy
    public IBIZCustomDTOMapping ibizCustomDtoMapping;


    @ApiOperation(value = "创建Create", tags = {"自定义" },  notes = "IBIZCustom-Create")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZCustom-Create-all') or hasPermission(this.ibizCustomDtoMapping.toDomain(#dto),'DemoSys-IBIZCustom-Create')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizcustoms")
    public ResponseEntity<IBIZCustomDTO> create
            (@Validated @RequestBody IBIZCustomDTO dto) {
        IBIZCustom domain = ibizCustomDtoMapping.toDomain(dto);
        ibizCustomService.create(domain);
        IBIZCustom rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizCustomDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "获取Get", tags = {"自定义" },  notes = "IBIZCustom-Get")
    @PostAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZCustom-Get-all') or hasPermission(this.ibizCustomDtoMapping.toDomain(returnObject.body),'DemoSys-IBIZCustom-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizcustoms/{ibizCustomId}")
    public ResponseEntity<IBIZCustomDTO> getByIbizCustomId
            (@PathVariable("ibizCustomId") String ibizCustomId) {
        IBIZCustom rt = ibizCustomService.get(ibizCustomId);
        return ResponseEntity.status(HttpStatus.OK).body(ibizCustomDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "删除Remove", tags = {"自定义" },  notes = "IBIZCustom-Remove")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZCustom-Remove-all') or hasPermission(this.ibizCustomService.get(#ibizCustomId),'DemoSys-IBIZCustom-Remove')")
    @RequestMapping(method = RequestMethod.DELETE, value = "ibizcustoms/{ibizCustomId}")
    public ResponseEntity<Boolean> removeByIbizCustomId
            (@PathVariable("ibizCustomId") String ibizCustomId) {
        Boolean rt = ibizCustomService.remove(ibizCustomId);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "更新Update", tags = {"自定义" },  notes = "IBIZCustom-Update")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZCustom-Update-all') or hasPermission(this.ibizCustomService.get(#ibizCustomId),'DemoSys-IBIZCustom-Update')")
    @VersionCheck(entity = "ibizcustom" , versionfield = "updateDate")
    @RequestMapping(method = RequestMethod.PUT, value = "ibizcustoms/{ibizCustomId}")
    public ResponseEntity<IBIZCustomDTO> updateByIbizCustomId
            (@PathVariable("ibizCustomId") String ibizCustomId, @Validated @RequestBody IBIZCustomDTO dto) {
        IBIZCustom domain = ibizCustomDtoMapping.toDomain(dto);
        domain.setIbizCustomId(ibizCustomId);
        ibizCustomService.update(domain);
        IBIZCustom rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizCustomDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "校验CheckKey", tags = {"自定义" },  notes = "IBIZCustom-CheckKey")
    @RequestMapping(method = RequestMethod.POST, value = "ibizcustoms/checkkey")
    public ResponseEntity<Integer> checkKey
            (@Validated @RequestBody IBIZCustomDTO dto) {
        IBIZCustom domain = ibizCustomDtoMapping.toDomain(dto);
        Integer rt = ibizCustomService.checkKey(domain);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "草稿GetDraft", tags = {"自定义" },  notes = "IBIZCustom-GetDraft")
    @RequestMapping(method = RequestMethod.GET, value = "ibizcustoms/getdraft")
    public ResponseEntity<IBIZCustomDTO> getDraft
            (IBIZCustomDTO dto) {
        IBIZCustom domain = ibizCustomDtoMapping.toDomain(dto);
        IBIZCustom rt = ibizCustomService.getDraft(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ibizCustomDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "保存Save", tags = {"自定义" },  notes = "IBIZCustom-Save")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZCustom-Save-all') or hasPermission(this.ibizCustomDtoMapping.toDomain(#dto),'DemoSys-IBIZCustom-Save')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizcustoms/save")
    public ResponseEntity<IBIZCustomDTO> save
            (@Validated @RequestBody IBIZCustomDTO dto) {
        IBIZCustom domain = ibizCustomDtoMapping.toDomain(dto);
        ibizCustomService.save(domain);
        IBIZCustom rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizCustomDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "查询FetchDefault", tags = {"自定义" },  notes = "IBIZCustom-FetchDefault")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZCustom-searchDefault-all','DemoSys-IBIZCustom-Get-all') or hasPermission(#dto,'DemoSys-IBIZCustom-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizcustoms/fetchdefault")
    public ResponseEntity<List<IBIZCustomDTO>> fetchDefault
            (IBIZCustomSearchContext dto) {
        Page<IBIZCustom> domains = ibizCustomService.searchDefault(dto) ;
        List<IBIZCustomDTO> list = ibizCustomDtoMapping.toDto(domains.getContent());
            return ResponseEntity.status(HttpStatus.OK)
            .header("x-page", String.valueOf(dto.getPageable().getPageNumber()))
            .header("x-per-page", String.valueOf(dto.getPageable().getPageSize()))
            .header("x-total", String.valueOf(domains.getTotalElements()))
            .body(list);
    }


    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZCustom-Create-all')")
    @ApiOperation(value = "批量新建自定义", tags = {"自定义" },  notes = "批量新建自定义")
	@RequestMapping(method = RequestMethod.POST, value = "ibizcustoms/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<IBIZCustomDTO> dtos) {
        ibizCustomService.createBatch(ibizCustomDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZCustom-Update-all')")
    @ApiOperation(value = "批量更新自定义", tags = {"自定义" },  notes = "批量更新自定义")
	@RequestMapping(method = RequestMethod.PUT, value = "ibizcustoms/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<IBIZCustomDTO> dtos) {
        ibizCustomService.updateBatch(ibizCustomDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZCustom-Save-all')")
    @ApiOperation(value = "批量保存自定义", tags = {"自定义" },  notes = "批量保存自定义")
	@RequestMapping(method = RequestMethod.POST, value = "ibizcustoms/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<IBIZCustomDTO> dtos) {
        ibizCustomService.saveBatch(ibizCustomDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZCustom-Save-all')")
    @ApiOperation(value = "批量导入自定义", tags = {"自定义" },  notes = "批量导入自定义")
	@RequestMapping(method = RequestMethod.POST, value = "ibizcustoms/import")
    public ResponseEntity<Map> importData(@RequestParam(value = "config") String config ,@RequestBody List<IBIZCustomDTO> dtos) {
        Map rs=new HashMap();
        if(ObjectUtils.isEmpty(dtos)){
            rs.put("rst", 1);
            rs.put("msg", "未传入内容");
            return ResponseEntity.status(HttpStatus.NO_CONTENT).body(rs);
        }
        else{
            List<IBIZCustom> list=ibizCustomDtoMapping.toDomain(dtos);
            List<IBIZCustom> rtList=new ArrayList();
            list.forEach(item->{
                if(ibizCustomService.save(item))
                    rtList.add(item);
            });
            rs.put("rst", 0);
            rs.put("data",rtList);
        }
        return  ResponseEntity.status(HttpStatus.OK).body(rs);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZCustom-Remove-all')")
    @ApiOperation(value = "批量删除自定义", tags = {"自定义" },  notes = "批量删除自定义")
	@RequestMapping(method = RequestMethod.DELETE, value = {"ibizcustoms","/ibizcustoms/batch"})
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        ibizCustomService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }
}
