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.DstDataSource;
import cn.ibizlab.core.lite.service.IDstDataSourceService;
import cn.ibizlab.core.lite.filter.DstDataSourceSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"数据源" })
@RestController("api-dstdatasource")
@RequestMapping("")
public class DstDataSourceResource {

    @Autowired
    public IDstDataSourceService dstdatasourceService;

    @Autowired
    @Lazy
    public DstDataSourceMapping dstdatasourceMapping;

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DstDataSource-Create-all')")
    @ApiOperation(value = "新建数据源", tags = {"数据源" },  notes = "新建数据源")
	@RequestMapping(method = RequestMethod.POST, value = "/dstdatasources")
    public ResponseEntity<DstDataSourceDTO> create(@Validated @RequestBody DstDataSourceDTO dstdatasourcedto) {
        DstDataSource domain = dstdatasourceMapping.toDomain(dstdatasourcedto);
		dstdatasourceService.create(domain);
        DstDataSourceDTO dto = dstdatasourceMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DstDataSource-Create-all')")
    @ApiOperation(value = "批量新建数据源", tags = {"数据源" },  notes = "批量新建数据源")
	@RequestMapping(method = RequestMethod.POST, value = "/dstdatasources/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<DstDataSourceDTO> dstdatasourcedtos) {
        dstdatasourceService.createBatch(dstdatasourceMapping.toDomain(dstdatasourcedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DstDataSource-Update-all')")
    @ApiOperation(value = "更新数据源", tags = {"数据源" },  notes = "更新数据源")
	@RequestMapping(method = RequestMethod.PUT, value = "/dstdatasources/{dstdatasource_id}")
    public ResponseEntity<DstDataSourceDTO> update(@PathVariable("dstdatasource_id") String dstdatasource_id, @RequestBody DstDataSourceDTO dstdatasourcedto) {
		DstDataSource domain  = dstdatasourceMapping.toDomain(dstdatasourcedto);
        domain .setDsId(dstdatasource_id);
		dstdatasourceService.update(domain );
		DstDataSourceDTO dto = dstdatasourceMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DstDataSource-Update-all')")
    @ApiOperation(value = "批量更新数据源", tags = {"数据源" },  notes = "批量更新数据源")
	@RequestMapping(method = RequestMethod.PUT, value = "/dstdatasources/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<DstDataSourceDTO> dstdatasourcedtos) {
        dstdatasourceService.updateBatch(dstdatasourceMapping.toDomain(dstdatasourcedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DstDataSource-Remove-all')")
    @ApiOperation(value = "删除数据源", tags = {"数据源" },  notes = "删除数据源")
	@RequestMapping(method = RequestMethod.DELETE, value = "/dstdatasources/{dstdatasource_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("dstdatasource_id") String dstdatasource_id) {
         return ResponseEntity.status(HttpStatus.OK).body(dstdatasourceService.remove(dstdatasource_id));
    }

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

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DstDataSource-Get-all')")
    @ApiOperation(value = "获取数据源", tags = {"数据源" },  notes = "获取数据源")
	@RequestMapping(method = RequestMethod.GET, value = "/dstdatasources/{dstdatasource_id}")
    public ResponseEntity<DstDataSourceDTO> get(@PathVariable("dstdatasource_id") String dstdatasource_id) {
        DstDataSource domain = dstdatasourceService.get(dstdatasource_id);
        DstDataSourceDTO dto = dstdatasourceMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取数据源草稿", tags = {"数据源" },  notes = "获取数据源草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/dstdatasources/getdraft")
    public ResponseEntity<DstDataSourceDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(dstdatasourceMapping.toDto(dstdatasourceService.getDraft(new DstDataSource())));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DstDataSource-BuildDS-all')")
    @ApiOperation(value = "buildDS", tags = {"数据源" },  notes = "buildDS")
	@RequestMapping(method = RequestMethod.POST, value = "/dstdatasources/{dstdatasource_id}/buildds")
    public ResponseEntity<DstDataSourceDTO> buildDS(@PathVariable("dstdatasource_id") String dstdatasource_id, @RequestBody DstDataSourceDTO dstdatasourcedto) {
        DstDataSource domain = dstdatasourceMapping.toDomain(dstdatasourcedto);
        domain.setDsId(dstdatasource_id);
        domain = dstdatasourceService.buildDS(domain);
        dstdatasourcedto = dstdatasourceMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dstdatasourcedto);
    }
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DstDataSource-BuildDS-all')")
    @ApiOperation(value = "批量处理[buildDS]", tags = {"数据源" },  notes = "批量处理[buildDS]")
	@RequestMapping(method = RequestMethod.POST, value = "/dstdatasources/{dstdatasource_id}/builddsbatch")
    public ResponseEntity<Boolean> buildDSBatch(@RequestBody List<DstDataSourceDTO> dstdatasourcedtos) {
        return ResponseEntity.status(HttpStatus.OK).body(dstdatasourceService.buildDSBatch(dstdatasourceMapping.toDomain(dstdatasourcedtos)));
    }

    @ApiOperation(value = "检查数据源", tags = {"数据源" },  notes = "检查数据源")
	@RequestMapping(method = RequestMethod.POST, value = "/dstdatasources/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody DstDataSourceDTO dstdatasourcedto) {
        return  ResponseEntity.status(HttpStatus.OK).body(dstdatasourceService.checkKey(dstdatasourceMapping.toDomain(dstdatasourcedto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DstDataSource-Save-all')")
    @ApiOperation(value = "保存数据源", tags = {"数据源" },  notes = "保存数据源")
	@RequestMapping(method = RequestMethod.POST, value = "/dstdatasources/save")
    public ResponseEntity<Boolean> save(@RequestBody DstDataSourceDTO dstdatasourcedto) {
        return ResponseEntity.status(HttpStatus.OK).body(dstdatasourceService.save(dstdatasourceMapping.toDomain(dstdatasourcedto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DstDataSource-Save-all')")
    @ApiOperation(value = "批量保存数据源", tags = {"数据源" },  notes = "批量保存数据源")
	@RequestMapping(method = RequestMethod.POST, value = "/dstdatasources/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<DstDataSourceDTO> dstdatasourcedtos) {
        dstdatasourceService.saveBatch(dstdatasourceMapping.toDomain(dstdatasourcedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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


}

