package cn.ibizlab.businesscentral.centralapi.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 org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.runtime.domain.Connection;
import cn.ibizlab.businesscentral.core.runtime.service.IConnectionService;
import cn.ibizlab.businesscentral.core.runtime.filter.ConnectionSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"连接" })
@RestController("CentralApi-connection")
@RequestMapping("")
public class ConnectionResource {

    @Autowired
    public IConnectionService connectionService;

    @Autowired
    @Lazy
    public ConnectionMapping connectionMapping;

    @PreAuthorize("hasPermission(this.connectionMapping.toDomain(#connectiondto),'iBizBusinessCentral-Connection-Create')")
    @ApiOperation(value = "新建连接", tags = {"连接" },  notes = "新建连接")
	@RequestMapping(method = RequestMethod.POST, value = "/connections")
    @Transactional
    public ResponseEntity<ConnectionDTO> create(@RequestBody ConnectionDTO connectiondto) {
        Connection domain = connectionMapping.toDomain(connectiondto);
		connectionService.create(domain);
        ConnectionDTO dto = connectionMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.connectionMapping.toDomain(#connectiondtos),'iBizBusinessCentral-Connection-Create')")
    @ApiOperation(value = "批量新建连接", tags = {"连接" },  notes = "批量新建连接")
	@RequestMapping(method = RequestMethod.POST, value = "/connections/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<ConnectionDTO> connectiondtos) {
        connectionService.createBatch(connectionMapping.toDomain(connectiondtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "connection" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.connectionService.get(#connection_id),'iBizBusinessCentral-Connection-Update')")
    @ApiOperation(value = "更新连接", tags = {"连接" },  notes = "更新连接")
	@RequestMapping(method = RequestMethod.PUT, value = "/connections/{connection_id}")
    @Transactional
    public ResponseEntity<ConnectionDTO> update(@PathVariable("connection_id") String connection_id, @RequestBody ConnectionDTO connectiondto) {
		Connection domain  = connectionMapping.toDomain(connectiondto);
        domain .setConnectionid(connection_id);
		connectionService.update(domain );
		ConnectionDTO dto = connectionMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.connectionService.getConnectionByEntities(this.connectionMapping.toDomain(#connectiondtos)),'iBizBusinessCentral-Connection-Update')")
    @ApiOperation(value = "批量更新连接", tags = {"连接" },  notes = "批量更新连接")
	@RequestMapping(method = RequestMethod.PUT, value = "/connections/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<ConnectionDTO> connectiondtos) {
        connectionService.updateBatch(connectionMapping.toDomain(connectiondtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.connectionService.get(#connection_id),'iBizBusinessCentral-Connection-Remove')")
    @ApiOperation(value = "删除连接", tags = {"连接" },  notes = "删除连接")
	@RequestMapping(method = RequestMethod.DELETE, value = "/connections/{connection_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("connection_id") String connection_id) {
         return ResponseEntity.status(HttpStatus.OK).body(connectionService.remove(connection_id));
    }

    @PreAuthorize("hasPermission(this.connectionService.getConnectionByIds(#ids),'iBizBusinessCentral-Connection-Remove')")
    @ApiOperation(value = "批量删除连接", tags = {"连接" },  notes = "批量删除连接")
	@RequestMapping(method = RequestMethod.DELETE, value = "/connections/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        connectionService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.connectionMapping.toDomain(returnObject.body),'iBizBusinessCentral-Connection-Get')")
    @ApiOperation(value = "获取连接", tags = {"连接" },  notes = "获取连接")
	@RequestMapping(method = RequestMethod.GET, value = "/connections/{connection_id}")
    public ResponseEntity<ConnectionDTO> get(@PathVariable("connection_id") String connection_id) {
        Connection domain = connectionService.get(connection_id);
        ConnectionDTO dto = connectionMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取连接草稿", tags = {"连接" },  notes = "获取连接草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/connections/getdraft")
    public ResponseEntity<ConnectionDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(connectionMapping.toDto(connectionService.getDraft(new Connection())));
    }

    @ApiOperation(value = "检查连接", tags = {"连接" },  notes = "检查连接")
	@RequestMapping(method = RequestMethod.POST, value = "/connections/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody ConnectionDTO connectiondto) {
        return  ResponseEntity.status(HttpStatus.OK).body(connectionService.checkKey(connectionMapping.toDomain(connectiondto)));
    }

    @PreAuthorize("hasPermission(this.connectionMapping.toDomain(#connectiondto),'iBizBusinessCentral-Connection-Save')")
    @ApiOperation(value = "保存连接", tags = {"连接" },  notes = "保存连接")
	@RequestMapping(method = RequestMethod.POST, value = "/connections/save")
    public ResponseEntity<Boolean> save(@RequestBody ConnectionDTO connectiondto) {
        return ResponseEntity.status(HttpStatus.OK).body(connectionService.save(connectionMapping.toDomain(connectiondto)));
    }

    @PreAuthorize("hasPermission(this.connectionMapping.toDomain(#connectiondtos),'iBizBusinessCentral-Connection-Save')")
    @ApiOperation(value = "批量保存连接", tags = {"连接" },  notes = "批量保存连接")
	@RequestMapping(method = RequestMethod.POST, value = "/connections/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<ConnectionDTO> connectiondtos) {
        connectionService.saveBatch(connectionMapping.toDomain(connectiondtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Connection-searchByParentKey-all') and hasPermission(#context,'iBizBusinessCentral-Connection-Get')")
	@ApiOperation(value = "获取ByParentKey", tags = {"连接" } ,notes = "获取ByParentKey")
    @RequestMapping(method= RequestMethod.GET , value="/connections/fetchbyparentkey")
	public ResponseEntity<List<ConnectionDTO>> fetchByParentKey(ConnectionSearchContext context) {
        Page<Connection> domains = connectionService.searchByParentKey(context) ;
        List<ConnectionDTO> list = connectionMapping.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','iBizBusinessCentral-Connection-searchByParentKey-all') and hasPermission(#context,'iBizBusinessCentral-Connection-Get')")
	@ApiOperation(value = "查询ByParentKey", tags = {"连接" } ,notes = "查询ByParentKey")
    @RequestMapping(method= RequestMethod.POST , value="/connections/searchbyparentkey")
	public ResponseEntity<Page<ConnectionDTO>> searchByParentKey(@RequestBody ConnectionSearchContext context) {
        Page<Connection> domains = connectionService.searchByParentKey(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(connectionMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Connection-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Connection-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"连接" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/connections/fetchdefault")
	public ResponseEntity<List<ConnectionDTO>> fetchDefault(ConnectionSearchContext context) {
        Page<Connection> domains = connectionService.searchDefault(context) ;
        List<ConnectionDTO> list = connectionMapping.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','iBizBusinessCentral-Connection-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Connection-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"连接" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/connections/searchdefault")
	public ResponseEntity<Page<ConnectionDTO>> searchDefault(@RequestBody ConnectionSearchContext context) {
        Page<Connection> domains = connectionService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(connectionMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

