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.IBIZBOOK;
import cn.ibizlab.core.sample.service.IBIZBOOKService;
import cn.ibizlab.core.sample.filter.IBIZBOOKSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"图书" })
@RestController("demoapi-ibizbook")
@RequestMapping("${ibiz.rest.basePath.demoapi:/demoapi/}")
public class IBIZBOOKResource {

    @Autowired
    public IBIZBOOKService ibizbookService;

    @Autowired
    @Lazy
    public IBIZBOOKDTOMapping ibizbookdtoMapping;


    @ApiOperation(value = "创建Create", tags = {"图书" },  notes = "IBIZBOOK-Create")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZBOOK-Create-all') or hasPermission(this.ibizbookdtoMapping.toDomain(#dto),'DemoSys-IBIZBOOK-Create')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizbooks")
    public ResponseEntity<IBIZBOOKDTO> create
            (@Validated @RequestBody IBIZBOOKDTO dto) {
        IBIZBOOK domain = ibizbookdtoMapping.toDomain(dto);
        ibizbookService.create(domain);
        IBIZBOOK rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizbookdtoMapping.toDto(rt));
    }

    @ApiOperation(value = "获取Get", tags = {"图书" },  notes = "IBIZBOOK-Get")
    @PostAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZBOOK-Get-all') or hasPermission(this.ibizbookdtoMapping.toDomain(returnObject.body),'DemoSys-IBIZBOOK-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizbooks/{ibizbookid}")
    public ResponseEntity<IBIZBOOKDTO> getByIbizbookid
            (@PathVariable("ibizbookid") String ibizbookid) {
        IBIZBOOK rt = ibizbookService.get(ibizbookid);
        return ResponseEntity.status(HttpStatus.OK).body(ibizbookdtoMapping.toDto(rt));
    }

    @ApiOperation(value = "删除Remove", tags = {"图书" },  notes = "IBIZBOOK-Remove")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZBOOK-Remove-all') or hasPermission(this.ibizbookService.get(#ibizbookid),'DemoSys-IBIZBOOK-Remove')")
    @RequestMapping(method = RequestMethod.DELETE, value = "ibizbooks/{ibizbookid}")
    public ResponseEntity<Boolean> removeByIbizbookid
            (@PathVariable("ibizbookid") String ibizbookid) {
        Boolean rt = ibizbookService.remove(ibizbookid);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "更新Update", tags = {"图书" },  notes = "IBIZBOOK-Update")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZBOOK-Update-all') or hasPermission(this.ibizbookService.get(#ibizbookid),'DemoSys-IBIZBOOK-Update')")
    @VersionCheck(entity = "ibizbook" , versionfield = "updateDate")
    @RequestMapping(method = RequestMethod.PUT, value = "ibizbooks/{ibizbookid}")
    public ResponseEntity<IBIZBOOKDTO> updateByIbizbookid
            (@PathVariable("ibizbookid") String ibizbookid, @Validated @RequestBody IBIZBOOKDTO dto) {
        IBIZBOOK domain = ibizbookdtoMapping.toDomain(dto);
        domain.setIbizbookid(ibizbookid);
        ibizbookService.update(domain);
        IBIZBOOK rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizbookdtoMapping.toDto(rt));
    }

    @ApiOperation(value = "校验CheckKey", tags = {"图书" },  notes = "IBIZBOOK-CheckKey")
    @RequestMapping(method = RequestMethod.POST, value = "ibizbooks/checkkey")
    public ResponseEntity<Integer> checkKey
            (@Validated @RequestBody IBIZBOOKDTO dto) {
        IBIZBOOK domain = ibizbookdtoMapping.toDomain(dto);
        Integer rt = ibizbookService.checkKey(domain);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "草稿GetDraft", tags = {"图书" },  notes = "IBIZBOOK-GetDraft")
    @RequestMapping(method = RequestMethod.GET, value = "ibizbooks/getdraft")
    public ResponseEntity<IBIZBOOKDTO> getDraft
            (IBIZBOOKDTO dto) {
        IBIZBOOK domain = ibizbookdtoMapping.toDomain(dto);
        IBIZBOOK rt = ibizbookService.getDraft(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ibizbookdtoMapping.toDto(rt));
    }

    @ApiOperation(value = "保存Save", tags = {"图书" },  notes = "IBIZBOOK-Save")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZBOOK-Save-all') or hasPermission(this.ibizbookdtoMapping.toDomain(#dto),'DemoSys-IBIZBOOK-Save')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizbooks/save")
    public ResponseEntity<IBIZBOOKDTO> save
            (@Validated @RequestBody IBIZBOOKDTO dto) {
        IBIZBOOK domain = ibizbookdtoMapping.toDomain(dto);
        ibizbookService.save(domain);
        IBIZBOOK rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizbookdtoMapping.toDto(rt));
    }

    @ApiOperation(value = "UpdatePress", tags = {"图书" },  notes = "IBIZBOOK-UpdatePress")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZBOOK-UpdatePress-all') or hasPermission(this.ibizbookdtoMapping.toDomain(#dto),'DemoSys-IBIZBOOK-UpdatePress')")
    @RequestMapping(method = RequestMethod.PUT, value = "ibizbooks/{ibizbookid}/updatepress")
    public ResponseEntity<IBIZBOOKDTO> updatePressByIbizbookid
            (@PathVariable("ibizbookid") String ibizbookid, @Validated @RequestBody IBIZBOOKDTO dto) {
        IBIZBOOK domain = ibizbookdtoMapping.toDomain(dto);
        domain.setIbizbookid(ibizbookid);
        IBIZBOOK rt = ibizbookService.updatePress(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ibizbookdtoMapping.toDto(rt));
    }

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

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZBOOK-Update-all')")
    @ApiOperation(value = "批量更新图书", tags = {"图书" },  notes = "批量更新图书")
	@RequestMapping(method = RequestMethod.PUT, value = "ibizbooks/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<IBIZBOOKDTO> dtos) {
        ibizbookService.updateBatch(ibizbookdtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZBOOK-Save-all')")
    @ApiOperation(value = "批量保存图书", tags = {"图书" },  notes = "批量保存图书")
	@RequestMapping(method = RequestMethod.POST, value = "ibizbooks/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<IBIZBOOKDTO> dtos) {
        ibizbookService.saveBatch(ibizbookdtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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