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.IBIZStorage;
import cn.ibizlab.core.sample.service.IBIZStorageService;
import cn.ibizlab.core.sample.filter.IBIZStorageSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"存储" })
@RestController("demoapi-ibizstorage")
@RequestMapping("${ibiz.rest.basePath.demoapi:/demoapi/}")
public class IBIZStorageResource {

    @Autowired
    public IBIZStorageService ibizStorageService;

    @Autowired
    @Lazy
    public IBIZStorageDTOMapping ibizStorageDtoMapping;


    @ApiOperation(value = "创建Create", tags = {"存储" },  notes = "IBIZStorage-Create")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZStorage-Create-all') or hasPermission(this.ibizStorageDtoMapping.toDomain(#dto),'DemoSys-IBIZStorage-Create')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizstorages")
    public ResponseEntity<IBIZStorageDTO> create
            (@Validated @RequestBody IBIZStorageDTO dto) {
        IBIZStorage domain = ibizStorageDtoMapping.toDomain(dto);
        ibizStorageService.create(domain);
        IBIZStorage rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizStorageDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "获取Get", tags = {"存储" },  notes = "IBIZStorage-Get")
    @PostAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZStorage-Get-all') or hasPermission(this.ibizStorageDtoMapping.toDomain(returnObject.body),'DemoSys-IBIZStorage-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizstorages/{ibizStorageId}")
    public ResponseEntity<IBIZStorageDTO> getByIbizStorageId
            (@PathVariable("ibizStorageId") String ibizStorageId) {
        IBIZStorage rt = ibizStorageService.get(ibizStorageId);
        return ResponseEntity.status(HttpStatus.OK).body(ibizStorageDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "删除Remove", tags = {"存储" },  notes = "IBIZStorage-Remove")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZStorage-Remove-all') or hasPermission(this.ibizStorageService.get(#ibizStorageId),'DemoSys-IBIZStorage-Remove')")
    @RequestMapping(method = RequestMethod.DELETE, value = "ibizstorages/{ibizStorageId}")
    public ResponseEntity<Boolean> removeByIbizStorageId
            (@PathVariable("ibizStorageId") String ibizStorageId) {
        Boolean rt = ibizStorageService.remove(ibizStorageId);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "更新Update", tags = {"存储" },  notes = "IBIZStorage-Update")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZStorage-Update-all') or hasPermission(this.ibizStorageService.get(#ibizStorageId),'DemoSys-IBIZStorage-Update')")
    @VersionCheck(entity = "ibizstorage" , versionfield = "updateDate")
    @RequestMapping(method = RequestMethod.PUT, value = "ibizstorages/{ibizStorageId}")
    public ResponseEntity<IBIZStorageDTO> updateByIbizStorageId
            (@PathVariable("ibizStorageId") String ibizStorageId, @Validated @RequestBody IBIZStorageDTO dto) {
        IBIZStorage domain = ibizStorageDtoMapping.toDomain(dto);
        domain.setIbizStorageId(ibizStorageId);
        ibizStorageService.update(domain);
        IBIZStorage rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizStorageDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "校验CheckKey", tags = {"存储" },  notes = "IBIZStorage-CheckKey")
    @RequestMapping(method = RequestMethod.POST, value = "ibizstorages/checkkey")
    public ResponseEntity<Integer> checkKey
            (@Validated @RequestBody IBIZStorageDTO dto) {
        IBIZStorage domain = ibizStorageDtoMapping.toDomain(dto);
        Integer rt = ibizStorageService.checkKey(domain);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "草稿GetDraft", tags = {"存储" },  notes = "IBIZStorage-GetDraft")
    @RequestMapping(method = RequestMethod.GET, value = "ibizstorages/getdraft")
    public ResponseEntity<IBIZStorageDTO> getDraft
            (IBIZStorageDTO dto) {
        IBIZStorage domain = ibizStorageDtoMapping.toDomain(dto);
        IBIZStorage rt = ibizStorageService.getDraft(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ibizStorageDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "保存Save", tags = {"存储" },  notes = "IBIZStorage-Save")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZStorage-Save-all') or hasPermission(this.ibizStorageDtoMapping.toDomain(#dto),'DemoSys-IBIZStorage-Save')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizstorages/save")
    public ResponseEntity<IBIZStorageDTO> save
            (@Validated @RequestBody IBIZStorageDTO dto) {
        IBIZStorage domain = ibizStorageDtoMapping.toDomain(dto);
        ibizStorageService.save(domain);
        IBIZStorage rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizStorageDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "查询FetchDefault", tags = {"存储" },  notes = "IBIZStorage-FetchDefault")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZStorage-searchDefault-all','DemoSys-IBIZStorage-Get-all') or hasPermission(#dto,'DemoSys-IBIZStorage-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizstorages/fetchdefault")
    public ResponseEntity<List<IBIZStorageDTO>> fetchDefault
            (IBIZStorageSearchContext dto) {
        Page<IBIZStorage> domains = ibizStorageService.searchDefault(dto) ;
        List<IBIZStorageDTO> list = ibizStorageDtoMapping.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-IBIZStorage-Create-all')")
    @ApiOperation(value = "批量新建存储", tags = {"存储" },  notes = "批量新建存储")
	@RequestMapping(method = RequestMethod.POST, value = "ibizstorages/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<IBIZStorageDTO> dtos) {
        ibizStorageService.createBatch(ibizStorageDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZStorage-Update-all')")
    @ApiOperation(value = "批量更新存储", tags = {"存储" },  notes = "批量更新存储")
	@RequestMapping(method = RequestMethod.PUT, value = "ibizstorages/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<IBIZStorageDTO> dtos) {
        ibizStorageService.updateBatch(ibizStorageDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZStorage-Save-all')")
    @ApiOperation(value = "批量保存存储", tags = {"存储" },  notes = "批量保存存储")
	@RequestMapping(method = RequestMethod.POST, value = "ibizstorages/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<IBIZStorageDTO> dtos) {
        ibizStorageService.saveBatch(ibizStorageDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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