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 javax.servlet.ServletRequest;
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.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.IIBIZBOOKService;
import cn.ibizlab.core.sample.filter.IBIZBOOKSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"图书" })
@RestController("DemoAPI-ibizbook")
@RequestMapping("")
public class IBIZBOOKResource {

    @Autowired
    public IIBIZBOOKService ibizbookService;

    @Autowired
    @Lazy
    public IBIZBOOKMapping ibizbookMapping;

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

    @PreAuthorize("hasPermission(this.ibizbookMapping.toDomain(#ibizbookdtos),'DemoSys-IBIZBOOK-Create')")
    @ApiOperation(value = "批量新建图书", tags = {"图书" },  notes = "批量新建图书")
	@RequestMapping(method = RequestMethod.POST, value = "/ibizbooks/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<IBIZBOOKDTO> ibizbookdtos) {
        ibizbookService.createBatch(ibizbookMapping.toDomain(ibizbookdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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

    @PreAuthorize("hasPermission(this.ibizbookService.getIbizbookByEntities(this.ibizbookMapping.toDomain(#ibizbookdtos)),'DemoSys-IBIZBOOK-Update')")
    @ApiOperation(value = "批量更新图书", tags = {"图书" },  notes = "批量更新图书")
	@RequestMapping(method = RequestMethod.PUT, value = "/ibizbooks/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<IBIZBOOKDTO> ibizbookdtos) {
        ibizbookService.updateBatch(ibizbookMapping.toDomain(ibizbookdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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

    @PreAuthorize("hasPermission(this.ibizbookService.getIbizbookByIds(#ids),'DemoSys-IBIZBOOK-Remove')")
    @ApiOperation(value = "批量删除图书", tags = {"图书" },  notes = "批量删除图书")
	@RequestMapping(method = RequestMethod.DELETE, value = "/ibizbooks/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        ibizbookService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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

    @ApiOperation(value = "获取图书草稿", tags = {"图书" },  notes = "获取图书草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/ibizbooks/getdraft")
    public ResponseEntity<IBIZBOOKDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(ibizbookMapping.toDto(ibizbookService.getDraft(new IBIZBOOK())));
    }

    @ApiOperation(value = "检查图书", tags = {"图书" },  notes = "检查图书")
	@RequestMapping(method = RequestMethod.POST, value = "/ibizbooks/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody IBIZBOOKDTO ibizbookdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(ibizbookService.checkKey(ibizbookMapping.toDomain(ibizbookdto)));
    }

    @PreAuthorize("hasPermission(this.ibizbookMapping.toDomain(#ibizbookdto),'DemoSys-IBIZBOOK-Save')")
    @ApiOperation(value = "保存图书", tags = {"图书" },  notes = "保存图书")
	@RequestMapping(method = RequestMethod.POST, value = "/ibizbooks/save")
    public ResponseEntity<Boolean> save(@RequestBody IBIZBOOKDTO ibizbookdto) {
        return ResponseEntity.status(HttpStatus.OK).body(ibizbookService.save(ibizbookMapping.toDomain(ibizbookdto)));
    }

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

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZBOOK-UpdatePress-all')")
    @ApiOperation(value = "更新出版社", tags = {"图书" },  notes = "更新出版社")
	@RequestMapping(method = RequestMethod.PUT, value = "/ibizbooks/{ibizbook_id}/updatepress")
    public ResponseEntity<IBIZBOOKDTO> updatePress(@PathVariable("ibizbook_id") String ibizbook_id, @RequestBody IBIZBOOKDTO ibizbookdto) {
        IBIZBOOK domain = ibizbookMapping.toDomain(ibizbookdto);
        domain.setIbizbookid(ibizbook_id);
        domain = ibizbookService.updatePress(domain);
        ibizbookdto = ibizbookMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ibizbookdto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZBOOK-searchDefault-all') and hasPermission(#context,'DemoSys-IBIZBOOK-Get')")
	@ApiOperation(value = "获取数据集", tags = {"图书" } ,notes = "获取数据集")
    @RequestMapping(method= RequestMethod.GET , value="/ibizbooks/fetchdefault")
	public ResponseEntity<List<IBIZBOOKDTO>> fetchDefault(IBIZBOOKSearchContext context) {
        Page<IBIZBOOK> domains = ibizbookService.searchDefault(context) ;
        List<IBIZBOOKDTO> list = ibizbookMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZBOOK-searchDefault-all') and hasPermission(#context,'DemoSys-IBIZBOOK-Get')")
	@ApiOperation(value = "查询数据集", tags = {"图书" } ,notes = "查询数据集")
    @RequestMapping(method= RequestMethod.POST , value="/ibizbooks/searchdefault")
	public ResponseEntity<Page<IBIZBOOKDTO>> searchDefault(@RequestBody IBIZBOOKSearchContext context) {
        Page<IBIZBOOK> domains = ibizbookService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(ibizbookMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}


    @Autowired
    cn.ibizlab.core.sample.mapping.IBIZBOOKDataImport dataimportImpMapping;

    @RequestMapping(method = RequestMethod.POST, value = "/ibizbooks/import")
    public ResponseEntity<JSONObject> importData(@RequestParam(value = "config") String config , @RequestBody List<IBIZBOOK> dtos){
        JSONObject rs=new JSONObject();
        if(dtos.size()==0){
            rs.put("rst", 1);
            rs.put("msg", "未传入内容");
            return ResponseEntity.status(HttpStatus.NO_CONTENT).body(rs);
        }
        else{
            if("DataImport".equals(config)){
                rs=ibizbookService.importData(dataimportImpMapping.toDomain(dtos),1000,false);
            }
            return ResponseEntity.status(HttpStatus.OK).body(rs);
        }
    }
}

