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.IBIZSample;
import cn.ibizlab.core.sample.service.IBIZSampleService;
import cn.ibizlab.core.sample.filter.IBIZSampleSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"示例数据库" })
@RestController("demoapi-ibizsample")
@RequestMapping("${ibiz.rest.basePath.demoapi:/demoapi/}")
public class IBIZSampleResource {

    @Autowired
    public IBIZSampleService ibizSampleService;

    @Autowired
    @Lazy
    public IBIZSampleDTOMapping ibizSampleDtoMapping;


    @ApiOperation(value = "创建Create", tags = {"示例数据库" },  notes = "IBIZSample-Create")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZSample-Create-all') or hasPermission(this.ibizSampleDtoMapping.toDomain(#dto),'DemoSys-IBIZSample-Create')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizsamples")
    public ResponseEntity<IBIZSampleDTO> create
            (@Validated @RequestBody IBIZSampleDTO dto) {
        IBIZSample domain = ibizSampleDtoMapping.toDomain(dto);
        ibizSampleService.create(domain);
        IBIZSample rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizSampleDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "获取Get", tags = {"示例数据库" },  notes = "IBIZSample-Get")
    @PostAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZSample-Get-all') or hasPermission(this.ibizSampleDtoMapping.toDomain(returnObject.body),'DemoSys-IBIZSample-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizsamples/{ibizSampleId}")
    public ResponseEntity<IBIZSampleDTO> getByIbizSampleId
            (@PathVariable("ibizSampleId") String ibizSampleId) {
        IBIZSample rt = ibizSampleService.get(ibizSampleId);
        return ResponseEntity.status(HttpStatus.OK).body(ibizSampleDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "删除Remove", tags = {"示例数据库" },  notes = "IBIZSample-Remove")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZSample-Remove-all') or hasPermission(this.ibizSampleService.get(#ibizSampleId),'DemoSys-IBIZSample-Remove')")
    @RequestMapping(method = RequestMethod.DELETE, value = "ibizsamples/{ibizSampleId}")
    public ResponseEntity<Boolean> removeByIbizSampleId
            (@PathVariable("ibizSampleId") String ibizSampleId) {
        Boolean rt = ibizSampleService.remove(ibizSampleId);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "更新Update", tags = {"示例数据库" },  notes = "IBIZSample-Update")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZSample-Update-all') or hasPermission(this.ibizSampleService.get(#ibizSampleId),'DemoSys-IBIZSample-Update')")
    @VersionCheck(entity = "ibizsample" , versionfield = "updateDate")
    @RequestMapping(method = RequestMethod.PUT, value = "ibizsamples/{ibizSampleId}")
    public ResponseEntity<IBIZSampleDTO> updateByIbizSampleId
            (@PathVariable("ibizSampleId") String ibizSampleId, @Validated @RequestBody IBIZSampleDTO dto) {
        IBIZSample domain = ibizSampleDtoMapping.toDomain(dto);
        domain.setIbizSampleId(ibizSampleId);
        ibizSampleService.update(domain);
        IBIZSample rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizSampleDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "校验CheckKey", tags = {"示例数据库" },  notes = "IBIZSample-CheckKey")
    @RequestMapping(method = RequestMethod.POST, value = "ibizsamples/checkkey")
    public ResponseEntity<Integer> checkKey
            (@Validated @RequestBody IBIZSampleDTO dto) {
        IBIZSample domain = ibizSampleDtoMapping.toDomain(dto);
        Integer rt = ibizSampleService.checkKey(domain);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "草稿GetDraft", tags = {"示例数据库" },  notes = "IBIZSample-GetDraft")
    @RequestMapping(method = RequestMethod.GET, value = "ibizsamples/getdraft")
    public ResponseEntity<IBIZSampleDTO> getDraft
            (IBIZSampleDTO dto) {
        IBIZSample domain = ibizSampleDtoMapping.toDomain(dto);
        IBIZSample rt = ibizSampleService.getDraft(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ibizSampleDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "保存Save", tags = {"示例数据库" },  notes = "IBIZSample-Save")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZSample-Save-all') or hasPermission(this.ibizSampleDtoMapping.toDomain(#dto),'DemoSys-IBIZSample-Save')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizsamples/save")
    public ResponseEntity<IBIZSampleDTO> save
            (@Validated @RequestBody IBIZSampleDTO dto) {
        IBIZSample domain = ibizSampleDtoMapping.toDomain(dto);
        ibizSampleService.save(domain);
        IBIZSample rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizSampleDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "查询FetchDefault", tags = {"示例数据库" },  notes = "IBIZSample-FetchDefault")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZSample-searchDefault-all','DemoSys-IBIZSample-Get-all') or hasPermission(#dto,'DemoSys-IBIZSample-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizsamples/fetchdefault")
    public ResponseEntity<List<IBIZSampleDTO>> fetchDefault
            (IBIZSampleSearchContext dto) {
        Page<IBIZSample> domains = ibizSampleService.searchDefault(dto) ;
        List<IBIZSampleDTO> list = ibizSampleDtoMapping.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-IBIZSample-Create-all')")
    @ApiOperation(value = "批量新建示例数据库", tags = {"示例数据库" },  notes = "批量新建示例数据库")
	@RequestMapping(method = RequestMethod.POST, value = "ibizsamples/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<IBIZSampleDTO> dtos) {
        ibizSampleService.createBatch(ibizSampleDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZSample-Update-all')")
    @ApiOperation(value = "批量更新示例数据库", tags = {"示例数据库" },  notes = "批量更新示例数据库")
	@RequestMapping(method = RequestMethod.PUT, value = "ibizsamples/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<IBIZSampleDTO> dtos) {
        ibizSampleService.updateBatch(ibizSampleDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZSample-Save-all')")
    @ApiOperation(value = "批量保存示例数据库", tags = {"示例数据库" },  notes = "批量保存示例数据库")
	@RequestMapping(method = RequestMethod.POST, value = "ibizsamples/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<IBIZSampleDTO> dtos) {
        ibizSampleService.saveBatch(ibizSampleDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZSample-Save-all')")
    @ApiOperation(value = "批量导入示例数据库", tags = {"示例数据库" },  notes = "批量导入示例数据库")
	@RequestMapping(method = RequestMethod.POST, value = "ibizsamples/import")
    public ResponseEntity<Map> importData(@RequestParam(value = "config") String config ,@RequestBody List<IBIZSampleDTO> 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<IBIZSample> list=ibizSampleDtoMapping.toDomain(dtos);
            List<IBIZSample> rtList=new ArrayList();
            list.forEach(item->{
                if(ibizSampleService.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-IBIZSample-Remove-all')")
    @ApiOperation(value = "批量删除示例数据库", tags = {"示例数据库" },  notes = "批量删除示例数据库")
	@RequestMapping(method = RequestMethod.DELETE, value = {"ibizsamples","/ibizsamples/batch"})
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        ibizSampleService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }
}
