package cn.ibizlab.api.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.api.dto.*;
import cn.ibizlab.api.mapping.*;
import cn.ibizlab.core.lite.domain.MetaEntity;
import cn.ibizlab.core.lite.service.IMetaEntityService;
import cn.ibizlab.core.lite.filter.MetaEntitySearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"实体" })
@RestController("api-metaentity")
@RequestMapping("")
public class MetaEntityResource {

    @Autowired
    public IMetaEntityService metaentityService;

    @Autowired
    @Lazy
    public MetaEntityMapping metaentityMapping;

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Create-all')")
    @ApiOperation(value = "新建实体", tags = {"实体" },  notes = "新建实体")
	@RequestMapping(method = RequestMethod.POST, value = "/metaentities")
    public ResponseEntity<MetaEntityDTO> create(@Validated @RequestBody MetaEntityDTO metaentitydto) {
        MetaEntity domain = metaentityMapping.toDomain(metaentitydto);
		metaentityService.create(domain);
        MetaEntityDTO dto = metaentityMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Create-all')")
    @ApiOperation(value = "批量新建实体", tags = {"实体" },  notes = "批量新建实体")
	@RequestMapping(method = RequestMethod.POST, value = "/metaentities/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<MetaEntityDTO> metaentitydtos) {
        metaentityService.createBatch(metaentityMapping.toDomain(metaentitydtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Get-all')")
    @ApiOperation(value = "获取实体", tags = {"实体" },  notes = "获取实体")
	@RequestMapping(method = RequestMethod.GET, value = "/metaentities/{metaentity_id}")
    public ResponseEntity<MetaEntityDTO> get(@PathVariable("metaentity_id") String metaentity_id) {
        MetaEntity domain = metaentityService.get(metaentity_id);
        MetaEntityDTO dto = metaentityMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Remove-all')")
    @ApiOperation(value = "删除实体", tags = {"实体" },  notes = "删除实体")
	@RequestMapping(method = RequestMethod.DELETE, value = "/metaentities/{metaentity_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("metaentity_id") String metaentity_id) {
         return ResponseEntity.status(HttpStatus.OK).body(metaentityService.remove(metaentity_id));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Remove-all')")
    @ApiOperation(value = "批量删除实体", tags = {"实体" },  notes = "批量删除实体")
	@RequestMapping(method = RequestMethod.DELETE, value = "/metaentities/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        metaentityService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "metaentity" , versionfield = "updatedate")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Update-all')")
    @ApiOperation(value = "更新实体", tags = {"实体" },  notes = "更新实体")
	@RequestMapping(method = RequestMethod.PUT, value = "/metaentities/{metaentity_id}")
    public ResponseEntity<MetaEntityDTO> update(@PathVariable("metaentity_id") String metaentity_id, @RequestBody MetaEntityDTO metaentitydto) {
		MetaEntity domain  = metaentityMapping.toDomain(metaentitydto);
        domain .setEntityId(metaentity_id);
		metaentityService.update(domain );
		MetaEntityDTO dto = metaentityMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Update-all')")
    @ApiOperation(value = "批量更新实体", tags = {"实体" },  notes = "批量更新实体")
	@RequestMapping(method = RequestMethod.PUT, value = "/metaentities/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<MetaEntityDTO> metaentitydtos) {
        metaentityService.updateBatch(metaentityMapping.toDomain(metaentitydtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "检查实体", tags = {"实体" },  notes = "检查实体")
	@RequestMapping(method = RequestMethod.POST, value = "/metaentities/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody MetaEntityDTO metaentitydto) {
        return  ResponseEntity.status(HttpStatus.OK).body(metaentityService.checkKey(metaentityMapping.toDomain(metaentitydto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-GetDefaultModel-all')")
    @ApiOperation(value = "GetDefaultModel", tags = {"实体" },  notes = "GetDefaultModel")
	@RequestMapping(method = RequestMethod.GET, value = "/metaentities/{metaentity_id}/getdefaultmodel")
    public ResponseEntity<MetaEntityDTO> getDefaultModel(@PathVariable("metaentity_id") String metaentity_id, MetaEntityDTO metaentitydto) {
        MetaEntity domain = metaentityMapping.toDomain(metaentitydto);
        domain.setEntityId(metaentity_id);
        domain = metaentityService.getDefaultModel(domain);
        metaentitydto = metaentityMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(metaentitydto);
    }
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-GetDefaultModel-all')")
    @ApiOperation(value = "批量处理[GetDefaultModel]", tags = {"实体" },  notes = "批量处理[GetDefaultModel]")
	@RequestMapping(method = RequestMethod.GET, value = "/metaentities/getdefaultmodelbatch")
    public ResponseEntity<Boolean> getDefaultModelBatch(@RequestBody List<MetaEntityDTO> metaentitydtos) {
        List<MetaEntity> domains = metaentityMapping.toDomain(metaentitydtos);
        boolean result = metaentityService.getDefaultModelBatch(domains);
        return ResponseEntity.status(HttpStatus.OK).body(result);
    }

    @ApiOperation(value = "获取实体草稿", tags = {"实体" },  notes = "获取实体草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/metaentities/getdraft")
    public ResponseEntity<MetaEntityDTO> getDraft(MetaEntityDTO dto) {
        MetaEntity domain = metaentityMapping.toDomain(dto);
        return ResponseEntity.status(HttpStatus.OK).body(metaentityMapping.toDto(metaentityService.getDraft(domain)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Save-all')")
    @ApiOperation(value = "保存实体", tags = {"实体" },  notes = "保存实体")
	@RequestMapping(method = RequestMethod.POST, value = "/metaentities/save")
    public ResponseEntity<MetaEntityDTO> save(@RequestBody MetaEntityDTO metaentitydto) {
        MetaEntity domain = metaentityMapping.toDomain(metaentitydto);
        metaentityService.save(domain);
        return ResponseEntity.status(HttpStatus.OK).body(metaentityMapping.toDto(domain));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Save-all')")
    @ApiOperation(value = "批量保存实体", tags = {"实体" },  notes = "批量保存实体")
	@RequestMapping(method = RequestMethod.POST, value = "/metaentities/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<MetaEntityDTO> metaentitydtos) {
        metaentityService.saveBatch(metaentityMapping.toDomain(metaentitydtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-searchDefault-all')")
	@ApiOperation(value = "获取数据集", tags = {"实体" } ,notes = "获取数据集")
    @RequestMapping(method= RequestMethod.GET , value="/metaentities/fetchdefault")
	public ResponseEntity<List<MetaEntityDTO>> fetchDefault(MetaEntitySearchContext context) {
        Page<MetaEntity> domains = metaentityService.searchDefault(context) ;
        List<MetaEntityDTO> list = metaentityMapping.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','ibzdst-MetaEntity-searchDefault-all')")
	@ApiOperation(value = "查询数据集", tags = {"实体" } ,notes = "查询数据集")
    @RequestMapping(method= RequestMethod.POST , value="/metaentities/searchdefault")
	public ResponseEntity<Page<MetaEntityDTO>> searchDefault(@RequestBody MetaEntitySearchContext context) {
        Page<MetaEntity> domains = metaentityService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(metaentityMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}



    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Create-all')")
    @ApiOperation(value = "根据系统建立实体", tags = {"实体" },  notes = "根据系统建立实体")
	@RequestMapping(method = RequestMethod.POST, value = "/dstsystems/{dstsystem_id}/metaentities")
    public ResponseEntity<MetaEntityDTO> createByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id, @RequestBody MetaEntityDTO metaentitydto) {
        MetaEntity domain = metaentityMapping.toDomain(metaentitydto);
        domain.setSystemId(dstsystem_id);
		metaentityService.create(domain);
        MetaEntityDTO dto = metaentityMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Create-all')")
    @ApiOperation(value = "根据系统批量建立实体", tags = {"实体" },  notes = "根据系统批量建立实体")
	@RequestMapping(method = RequestMethod.POST, value = "/dstsystems/{dstsystem_id}/metaentities/batch")
    public ResponseEntity<Boolean> createBatchByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id, @RequestBody List<MetaEntityDTO> metaentitydtos) {
        List<MetaEntity> domainlist=metaentityMapping.toDomain(metaentitydtos);
        for(MetaEntity domain:domainlist){
            domain.setSystemId(dstsystem_id);
        }
        metaentityService.createBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Get-all')")
    @ApiOperation(value = "根据系统获取实体", tags = {"实体" },  notes = "根据系统获取实体")
	@RequestMapping(method = RequestMethod.GET, value = "/dstsystems/{dstsystem_id}/metaentities/{metaentity_id}")
    public ResponseEntity<MetaEntityDTO> getByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id, @PathVariable("metaentity_id") String metaentity_id) {
        MetaEntity domain = metaentityService.get(metaentity_id);
        MetaEntityDTO dto = metaentityMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Remove-all')")
    @ApiOperation(value = "根据系统删除实体", tags = {"实体" },  notes = "根据系统删除实体")
	@RequestMapping(method = RequestMethod.DELETE, value = "/dstsystems/{dstsystem_id}/metaentities/{metaentity_id}")
    public ResponseEntity<Boolean> removeByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id, @PathVariable("metaentity_id") String metaentity_id) {
		return ResponseEntity.status(HttpStatus.OK).body(metaentityService.remove(metaentity_id));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Remove-all')")
    @ApiOperation(value = "根据系统批量删除实体", tags = {"实体" },  notes = "根据系统批量删除实体")
	@RequestMapping(method = RequestMethod.DELETE, value = "/dstsystems/{dstsystem_id}/metaentities/batch")
    public ResponseEntity<Boolean> removeBatchByDstSystem(@RequestBody List<String> ids) {
        metaentityService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "metaentity" , versionfield = "updatedate")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Update-all')")
    @ApiOperation(value = "根据系统更新实体", tags = {"实体" },  notes = "根据系统更新实体")
	@RequestMapping(method = RequestMethod.PUT, value = "/dstsystems/{dstsystem_id}/metaentities/{metaentity_id}")
    public ResponseEntity<MetaEntityDTO> updateByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id, @PathVariable("metaentity_id") String metaentity_id, @RequestBody MetaEntityDTO metaentitydto) {
        MetaEntity domain = metaentityMapping.toDomain(metaentitydto);
        domain.setSystemId(dstsystem_id);
        domain.setEntityId(metaentity_id);
		metaentityService.update(domain);
        MetaEntityDTO dto = metaentityMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Update-all')")
    @ApiOperation(value = "根据系统批量更新实体", tags = {"实体" },  notes = "根据系统批量更新实体")
	@RequestMapping(method = RequestMethod.PUT, value = "/dstsystems/{dstsystem_id}/metaentities/batch")
    public ResponseEntity<Boolean> updateBatchByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id, @RequestBody List<MetaEntityDTO> metaentitydtos) {
        List<MetaEntity> domainlist=metaentityMapping.toDomain(metaentitydtos);
        for(MetaEntity domain:domainlist){
            domain.setSystemId(dstsystem_id);
        }
        metaentityService.updateBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "根据系统检查实体", tags = {"实体" },  notes = "根据系统检查实体")
	@RequestMapping(method = RequestMethod.POST, value = "/dstsystems/{dstsystem_id}/metaentities/checkkey")
    public ResponseEntity<Boolean> checkKeyByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id, @RequestBody MetaEntityDTO metaentitydto) {
        return  ResponseEntity.status(HttpStatus.OK).body(metaentityService.checkKey(metaentityMapping.toDomain(metaentitydto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-GetDefaultModel-all')")
    @ApiOperation(value = "根据系统实体", tags = {"实体" },  notes = "根据系统实体")
	@RequestMapping(method = RequestMethod.GET, value = "/dstsystems/{dstsystem_id}/metaentities/{metaentity_id}/getdefaultmodel")
    public ResponseEntity<MetaEntityDTO> getDefaultModelByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id, @PathVariable("metaentity_id") String metaentity_id, MetaEntityDTO metaentitydto) {
        MetaEntity domain = metaentityMapping.toDomain(metaentitydto);
        domain.setSystemId(dstsystem_id);
        domain = metaentityService.getDefaultModel(domain) ;
        metaentitydto = metaentityMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(metaentitydto);
    }
    @ApiOperation(value = "批量处理[根据系统实体]", tags = {"实体" },  notes = "批量处理[根据系统实体]")
	@RequestMapping(method = RequestMethod.GET, value = "/dstsystems/{dstsystem_id}/metaentities/getdefaultmodelbatch")
    public ResponseEntity<Boolean> getDefaultModelByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id, @RequestBody List<MetaEntityDTO> metaentitydtos) {
        List<MetaEntity> domains = metaentityMapping.toDomain(metaentitydtos);
        boolean result = metaentityService.getDefaultModelBatch(domains);
        return ResponseEntity.status(HttpStatus.OK).body(result);
    }
    @ApiOperation(value = "根据系统获取实体草稿", tags = {"实体" },  notes = "根据系统获取实体草稿")
    @RequestMapping(method = RequestMethod.GET, value = "/dstsystems/{dstsystem_id}/metaentities/getdraft")
    public ResponseEntity<MetaEntityDTO> getDraftByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id, MetaEntityDTO dto) {
        MetaEntity domain = metaentityMapping.toDomain(dto);
        domain.setSystemId(dstsystem_id);
        return ResponseEntity.status(HttpStatus.OK).body(metaentityMapping.toDto(metaentityService.getDraft(domain)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Save-all')")
    @ApiOperation(value = "根据系统保存实体", tags = {"实体" },  notes = "根据系统保存实体")
	@RequestMapping(method = RequestMethod.POST, value = "/dstsystems/{dstsystem_id}/metaentities/save")
    public ResponseEntity<MetaEntityDTO> saveByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id, @RequestBody MetaEntityDTO metaentitydto) {
        MetaEntity domain = metaentityMapping.toDomain(metaentitydto);
        domain.setSystemId(dstsystem_id);
        metaentityService.save(domain);
        return ResponseEntity.status(HttpStatus.OK).body(metaentityMapping.toDto(domain));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-Save-all')")
    @ApiOperation(value = "根据系统批量保存实体", tags = {"实体" },  notes = "根据系统批量保存实体")
	@RequestMapping(method = RequestMethod.POST, value = "/dstsystems/{dstsystem_id}/metaentities/savebatch")
    public ResponseEntity<Boolean> saveBatchByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id, @RequestBody List<MetaEntityDTO> metaentitydtos) {
        List<MetaEntity> domainlist=metaentityMapping.toDomain(metaentitydtos);
        for(MetaEntity domain:domainlist){
             domain.setSystemId(dstsystem_id);
        }
        metaentityService.saveBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaEntity-searchDefault-all')")
	@ApiOperation(value = "根据系统获取数据集", tags = {"实体" } ,notes = "根据系统获取数据集")
    @RequestMapping(method= RequestMethod.GET , value="/dstsystems/{dstsystem_id}/metaentities/fetchdefault")
	public ResponseEntity<List<MetaEntityDTO>> fetchMetaEntityDefaultByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id,MetaEntitySearchContext context) {
        context.setN_systemid_eq(dstsystem_id);
        Page<MetaEntity> domains = metaentityService.searchDefault(context) ;
        List<MetaEntityDTO> list = metaentityMapping.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','ibzdst-MetaEntity-searchDefault-all')")
	@ApiOperation(value = "根据系统查询数据集", tags = {"实体" } ,notes = "根据系统查询数据集")
    @RequestMapping(method= RequestMethod.POST , value="/dstsystems/{dstsystem_id}/metaentities/searchdefault")
	public ResponseEntity<Page<MetaEntityDTO>> searchMetaEntityDefaultByDstSystem(@PathVariable("dstsystem_id") String dstsystem_id, @RequestBody MetaEntitySearchContext context) {
        context.setN_systemid_eq(dstsystem_id);
        Page<MetaEntity> domains = metaentityService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(metaentityMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

