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.MetaModel;
import cn.ibizlab.core.lite.service.IMetaModelService;
import cn.ibizlab.core.lite.filter.MetaModelSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"模型" })
@RestController("api-metamodel")
@RequestMapping("")
public class MetaModelResource {

    @Autowired
    public IMetaModelService metamodelService;

    @Autowired
    @Lazy
    public MetaModelMapping metamodelMapping;

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-ExportFile-all')")
    @ApiOperation(value = "导出文件", tags = {"模型" },  notes = "导出文件")
	@RequestMapping(method = RequestMethod.POST, value = "/metamodels/{metamodel_id}/exportfile")
    public ResponseEntity<Void> exportFile(@PathVariable("metamodel_id") String metamodel_id, @RequestBody MetaModelDTO metamodeldto) {
        MetaModel domain = metamodelMapping.toDomain(metamodeldto);
        domain.setId(metamodel_id);
        domain = metamodelService.exportFile(domain);
        metamodeldto = metamodelMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).build();
    }
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-ExportFile-all')")
    @ApiOperation(value = "批量处理[导出文件]", tags = {"模型" },  notes = "批量处理[导出文件]")
	@RequestMapping(method = RequestMethod.POST, value = "/metamodels/{metamodel_id}/exportfilebatch")
    public ResponseEntity<Void> exportFileBatch(@RequestBody List<MetaModelDTO> metamodeldtos) {
        metamodelService.exportFileBatch(metamodelMapping.toDomain(metamodeldtos));
        return ResponseEntity.status(HttpStatus.OK).build();
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-Create-all')")
    @ApiOperation(value = "新建模型", tags = {"模型" },  notes = "新建模型")
	@RequestMapping(method = RequestMethod.POST, value = "/metamodels")
    public ResponseEntity<MetaModelDTO> create(@Validated @RequestBody MetaModelDTO metamodeldto) {
        MetaModel domain = metamodelMapping.toDomain(metamodeldto);
		metamodelService.create(domain);
        MetaModelDTO dto = metamodelMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-Create-all')")
    @ApiOperation(value = "批量新建模型", tags = {"模型" },  notes = "批量新建模型")
	@RequestMapping(method = RequestMethod.POST, value = "/metamodels/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<MetaModelDTO> metamodeldtos) {
        metamodelService.createBatch(metamodelMapping.toDomain(metamodeldtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "metamodel" , versionfield = "updatedate")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-Update-all')")
    @ApiOperation(value = "更新模型", tags = {"模型" },  notes = "更新模型")
	@RequestMapping(method = RequestMethod.PUT, value = "/metamodels/{metamodel_id}")
    public ResponseEntity<MetaModelDTO> update(@PathVariable("metamodel_id") String metamodel_id, @RequestBody MetaModelDTO metamodeldto) {
		MetaModel domain  = metamodelMapping.toDomain(metamodeldto);
        domain .setId(metamodel_id);
		metamodelService.update(domain );
		MetaModelDTO dto = metamodelMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-Update-all')")
    @ApiOperation(value = "批量更新模型", tags = {"模型" },  notes = "批量更新模型")
	@RequestMapping(method = RequestMethod.PUT, value = "/metamodels/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<MetaModelDTO> metamodeldtos) {
        metamodelService.updateBatch(metamodelMapping.toDomain(metamodeldtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-Remove-all')")
    @ApiOperation(value = "删除模型", tags = {"模型" },  notes = "删除模型")
	@RequestMapping(method = RequestMethod.DELETE, value = "/metamodels/{metamodel_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("metamodel_id") String metamodel_id) {
         return ResponseEntity.status(HttpStatus.OK).body(metamodelService.remove(metamodel_id));
    }

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

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-Get-all')")
    @ApiOperation(value = "获取模型", tags = {"模型" },  notes = "获取模型")
	@RequestMapping(method = RequestMethod.GET, value = "/metamodels/{metamodel_id}")
    public ResponseEntity<MetaModelDTO> get(@PathVariable("metamodel_id") String metamodel_id) {
        MetaModel domain = metamodelService.get(metamodel_id);
        MetaModelDTO dto = metamodelMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取模型草稿", tags = {"模型" },  notes = "获取模型草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/metamodels/getdraft")
    public ResponseEntity<MetaModelDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(metamodelMapping.toDto(metamodelService.getDraft(new MetaModel())));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-Change-all')")
    @ApiOperation(value = "change", tags = {"模型" },  notes = "change")
	@RequestMapping(method = RequestMethod.POST, value = "/metamodels/{metamodel_id}/change")
    public ResponseEntity<MetaModelDTO> change(@PathVariable("metamodel_id") String metamodel_id, @RequestBody MetaModelDTO metamodeldto) {
        MetaModel domain = metamodelMapping.toDomain(metamodeldto);
        domain.setId(metamodel_id);
        domain = metamodelService.change(domain);
        metamodeldto = metamodelMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(metamodeldto);
    }
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-Change-all')")
    @ApiOperation(value = "批量处理[change]", tags = {"模型" },  notes = "批量处理[change]")
	@RequestMapping(method = RequestMethod.POST, value = "/metamodels/{metamodel_id}/changebatch")
    public ResponseEntity<Boolean> changeBatch(@RequestBody List<MetaModelDTO> metamodeldtos) {
        return ResponseEntity.status(HttpStatus.OK).body(metamodelService.changeBatch(metamodelMapping.toDomain(metamodeldtos)));
    }

    @ApiOperation(value = "检查模型", tags = {"模型" },  notes = "检查模型")
	@RequestMapping(method = RequestMethod.POST, value = "/metamodels/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody MetaModelDTO metamodeldto) {
        return  ResponseEntity.status(HttpStatus.OK).body(metamodelService.checkKey(metamodelMapping.toDomain(metamodeldto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-ImportFile-all')")
    @ApiOperation(value = "导入文件", tags = {"模型" },  notes = "导入文件")
	@RequestMapping(method = RequestMethod.POST, value = "/metamodels/{metamodel_id}/importfile")
    public ResponseEntity<MetaModelDTO> importFile(@PathVariable("metamodel_id") String metamodel_id, @RequestBody MetaModelDTO metamodeldto) {
        MetaModel domain = metamodelMapping.toDomain(metamodeldto);
        domain.setId(metamodel_id);
        domain = metamodelService.importFile(domain);
        metamodeldto = metamodelMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(metamodeldto);
    }
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-ImportFile-all')")
    @ApiOperation(value = "批量处理[导入文件]", tags = {"模型" },  notes = "批量处理[导入文件]")
	@RequestMapping(method = RequestMethod.POST, value = "/metamodels/{metamodel_id}/importfilebatch")
    public ResponseEntity<Boolean> importFileBatch(@RequestBody List<MetaModelDTO> metamodeldtos) {
        return ResponseEntity.status(HttpStatus.OK).body(metamodelService.importFileBatch(metamodelMapping.toDomain(metamodeldtos)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-Save-all')")
    @ApiOperation(value = "保存模型", tags = {"模型" },  notes = "保存模型")
	@RequestMapping(method = RequestMethod.POST, value = "/metamodels/save")
    public ResponseEntity<Boolean> save(@RequestBody MetaModelDTO metamodeldto) {
        return ResponseEntity.status(HttpStatus.OK).body(metamodelService.save(metamodelMapping.toDomain(metamodeldto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-MetaModel-Save-all')")
    @ApiOperation(value = "批量保存模型", tags = {"模型" },  notes = "批量保存模型")
	@RequestMapping(method = RequestMethod.POST, value = "/metamodels/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<MetaModelDTO> metamodeldtos) {
        metamodelService.saveBatch(metamodelMapping.toDomain(metamodeldtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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


}

