package cn.ibizlab.eam.webapi.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.transaction.annotation.Transactional;
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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import cn.ibizlab.eam.webapi.dto.*;
import cn.ibizlab.eam.webapi.mapping.*;
import cn.ibizlab.eam.core.eam_core.domain.EMObject;
import cn.ibizlab.eam.core.eam_core.service.IEMObjectService;
import cn.ibizlab.eam.core.eam_core.filter.EMObjectSearchContext;




@Slf4j
@Api(tags = {"EMObject" })
@RestController("WebApi-emobject")
@RequestMapping("")
public class EMObjectResource {

    @Autowired
    private IEMObjectService emobjectService;

    @Autowired
    @Lazy
    private EMObjectMapping emobjectMapping;




    @ApiOperation(value = "Save", tags = {"EMObject" },  notes = "Save")
	@RequestMapping(method = RequestMethod.POST, value = "/emobjects/save")
    public ResponseEntity<Boolean> save(@RequestBody EMObjectDTO emobjectdto) {
        return ResponseEntity.status(HttpStatus.OK).body(emobjectService.save(emobjectMapping.toDomain(emobjectdto)));
    }

    @ApiOperation(value = "SaveBatch", tags = {"EMObject" },  notes = "SaveBatch")
	@RequestMapping(method = RequestMethod.POST, value = "/emobjects/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<EMObjectDTO> emobjectdtos) {
        emobjectService.saveBatch(emobjectMapping.toDomain(emobjectdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }




    @ApiOperation(value = "CheckKey", tags = {"EMObject" },  notes = "CheckKey")
	@RequestMapping(method = RequestMethod.POST, value = "/emobjects/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody EMObjectDTO emobjectdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(emobjectService.checkKey(emobjectMapping.toDomain(emobjectdto)));
    }




    @PreAuthorize("hasPermission(#emobject_id,'Get',{this.getEntity(),'Sql'})")
    @ApiOperation(value = "Get", tags = {"EMObject" },  notes = "Get")
	@RequestMapping(method = RequestMethod.GET, value = "/emobjects/{emobject_id}")
    public ResponseEntity<EMObjectDTO> get(@PathVariable("emobject_id") String emobject_id) {
        EMObject domain = emobjectService.get(emobject_id);
        EMObjectDTO dto = emobjectMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }




    @ApiOperation(value = "GetDraft", tags = {"EMObject" },  notes = "GetDraft")
	@RequestMapping(method = RequestMethod.GET, value = "/emobjects/getdraft")
    public ResponseEntity<EMObjectDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(emobjectMapping.toDto(emobjectService.getDraft(new EMObject())));
    }




    @PreAuthorize("hasPermission('','Create',{this.getEntity(),'Sql'})")
    @ApiOperation(value = "Create", tags = {"EMObject" },  notes = "Create")
	@RequestMapping(method = RequestMethod.POST, value = "/emobjects")
    @Transactional
    public ResponseEntity<EMObjectDTO> create(@RequestBody EMObjectDTO emobjectdto) {
        EMObject domain = emobjectMapping.toDomain(emobjectdto);
		emobjectService.create(domain);
        EMObjectDTO dto = emobjectMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }
    @PreAuthorize("hasPermission('','Create',{this.getEntity(),'Sql'})")
    @ApiOperation(value = "createBatch", tags = {"EMObject" },  notes = "createBatch")
	@RequestMapping(method = RequestMethod.POST, value = "/emobjects/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<EMObjectDTO> emobjectdtos) {
        emobjectService.createBatch(emobjectMapping.toDomain(emobjectdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }




    @PreAuthorize("hasPermission(#emobject_id,'Update',{this.getEntity(),'Sql'})")
    @ApiOperation(value = "Update", tags = {"EMObject" },  notes = "Update")
	@RequestMapping(method = RequestMethod.PUT, value = "/emobjects/{emobject_id}")
    @Transactional
    public ResponseEntity<EMObjectDTO> update(@PathVariable("emobject_id") String emobject_id, @RequestBody EMObjectDTO emobjectdto) {
		EMObject domain = emobjectMapping.toDomain(emobjectdto);
        domain.setEmobjectid(emobject_id);
		emobjectService.update(domain);
		EMObjectDTO dto = emobjectMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(#emobject_id,'Update',{this.getEntity(),'Sql'})")
    @ApiOperation(value = "UpdateBatch", tags = {"EMObject" },  notes = "UpdateBatch")
	@RequestMapping(method = RequestMethod.PUT, value = "/emobjects/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<EMObjectDTO> emobjectdtos) {
        emobjectService.updateBatch(emobjectMapping.toDomain(emobjectdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }




    @PreAuthorize("hasPermission(#emobject_id,'Remove',{this.getEntity(),'Sql'})")
    @ApiOperation(value = "Remove", tags = {"EMObject" },  notes = "Remove")
	@RequestMapping(method = RequestMethod.DELETE, value = "/emobjects/{emobject_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("emobject_id") String emobject_id) {
         return ResponseEntity.status(HttpStatus.OK).body(emobjectService.remove(emobject_id));
    }

    @ApiOperation(value = "RemoveBatch", tags = {"EMObject" },  notes = "RemoveBatch")
	@RequestMapping(method = RequestMethod.DELETE, value = "/emobjects/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        emobjectService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','eam_practice02-EMObject-Default-all')")
	@ApiOperation(value = "fetchDEFAULT", tags = {"EMObject" } ,notes = "fetchDEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/emobjects/fetchdefault")
	public ResponseEntity<List<EMObjectDTO>> fetchDefault(EMObjectSearchContext context) {
        Page<EMObject> domains = emobjectService.searchDefault(context) ;
        List<EMObjectDTO> list = emobjectMapping.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','eam_practice02-EMObject-Default-all')")
	@ApiOperation(value = "searchDEFAULT", tags = {"EMObject" } ,notes = "searchDEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/emobjects/searchdefault")
	public ResponseEntity<Page<EMObjectDTO>> searchDefault(@RequestBody EMObjectSearchContext context) {
        Page<EMObject> domains = emobjectService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(emobjectMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','eam_practice02-EMObject-IndexDER-all')")
	@ApiOperation(value = "fetchIndexDER", tags = {"EMObject" } ,notes = "fetchIndexDER")
    @RequestMapping(method= RequestMethod.GET , value="/emobjects/fetchindexder")
	public ResponseEntity<List<EMObjectDTO>> fetchIndexDER(EMObjectSearchContext context) {
        Page<EMObject> domains = emobjectService.searchIndexDER(context) ;
        List<EMObjectDTO> list = emobjectMapping.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','eam_practice02-EMObject-IndexDER-all')")
	@ApiOperation(value = "searchIndexDER", tags = {"EMObject" } ,notes = "searchIndexDER")
    @RequestMapping(method= RequestMethod.POST , value="/emobjects/searchindexder")
	public ResponseEntity<Page<EMObjectDTO>> searchIndexDER(@RequestBody EMObjectSearchContext context) {
        Page<EMObject> domains = emobjectService.searchIndexDER(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(emobjectMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}


    /**
     * 用户权限校验
     * @return
     */
	public EMObject getEntity(){
        return new EMObject();
    }

}
