package cn.ibizlab.core.data.rest;

import cn.ibizlab.core.data.dto.BaseData;
import cn.ibizlab.core.data.dto.FilterData;
import cn.ibizlab.core.data.dto.RequestData;
import cn.ibizlab.core.data.dto.ResponseData;
import cn.ibizlab.core.data.service.IDataService;
import cn.ibizlab.core.data.service.ModelService;
import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.util.security.AuthenticationUser;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.*;

@Slf4j
@Api(tags = {"数据" })
@RestController("api-data")
@RequestMapping({"/ibiz-repository/{system}/{scope}","/ibiz-repo/{system}",
		"/ibiz-repository/{system}/{scope}/{parentEntity}/{parentKey}","/ibiz-repo/{system}/{parentEntity}/{parentKey}",
		"/ibiz-repository/{system}/{scope}/{parentEntity}/{parentKey}/{parentEntity2}/{parentKey2}","/ibiz-repo/{system}/{parentEntity}/{parentKey}/{parentEntity2}/{parentKey2}"})
public class DataResource
{
    @Autowired
    public IDataService dataService;


	@Autowired
	public ModelService modelService;

	@ApiOperation(value = "callMethod数据", tags = {"数据" },  notes = "callMethod数据")
	@RequestMapping(method = {RequestMethod.GET}, value = {"/{entity}/call{method}","/{entity}/{key}/call{method}"})
	public ResponseEntity call(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "method",required = true) String method,
			@PathVariable(name = "key",required = false) String key,
			@RequestParam Map map) {
		RequestData requestData=new RequestData().setAll(map);
		if(requestData!=null)
			requestData.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2);
		return doCall(system,scope,parentEntity,parentKey,parentEntity2,parentKey2,entity,datasource,method,key,requestData);
	}

	@ApiOperation(value = "callMethod数据", tags = {"数据" },  notes = "callMethod数据")
	@RequestMapping(method = {RequestMethod.POST}, value = {"/{entity}/call{method}","/{entity}/{key}/call{method}"})
	public ResponseEntity doCall(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "method",required = true) String method,
			@PathVariable(name = "key",required = false) String key,
			@RequestBody(required = false) RequestData requestData) {
		if(requestData==null)
			requestData=new RequestData();
		ResponseData responseData=dataService.call(system,scope,entity,datasource,method,requestData
				.setKey(key).addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2));
		return ResponseEntity.status(HttpStatus.OK).body(responseData.getBody());
	}

	@ApiOperation(value = "批量callMethod数据", tags = {"数据" },  notes = "批量callMethod数据")
	@RequestMapping(method = {RequestMethod.POST}, value = {"/{entity}/call{method}batch"})
	public ResponseEntity callBatch(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "method",required = true) String method,
			@RequestBody List<RequestData> requestDatas) {
		if(requestDatas!=null)
			requestDatas.forEach(requestData ->dataService.call(system,scope,entity,datasource,method,requestData.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2)));
		return ResponseEntity.status(HttpStatus.OK).body(true);
	}



    @ApiOperation(value = "新建数据", tags = {"数据" },  notes = "新建数据")
	@RequestMapping(method = RequestMethod.POST, value = {"/{entity}","/{entity}/create"})
    public ResponseEntity<BaseData> create(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource, 
			@Validated @RequestBody BaseData baseData) {
		dataService.create(system,scope,entity,datasource,baseData
				.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2));
		return ResponseEntity.status(HttpStatus.OK).body(baseData);
    }

    @ApiOperation(value = "批量新建数据", tags = {"数据" },  notes = "批量新建数据")
	@RequestMapping(method = RequestMethod.POST, value = {"/{entity}/batch","/{entity}/createbatch"})
    public ResponseEntity<Boolean> createBatch(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource, 
			@RequestBody List<BaseData> baseDatas) {
		baseDatas.forEach(item->item.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2));
        dataService.createBatch(system,scope,entity,datasource,baseDatas);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "获取数据", tags = {"数据" },  notes = "获取数据")
	@RequestMapping(method = RequestMethod.GET, value = {"/{entity}","/{entity}/{key}"})
    public ResponseEntity<BaseData> get(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "key",required = false) String key,
			@RequestParam Map map) {
		BaseData baseData=BaseData.fromContext(map);
        return doGet(system,scope,parentEntity,parentKey,parentEntity2,parentKey2,entity,datasource,key,baseData);
    }

	@ApiOperation(value = "获取数据", tags = {"数据" },  notes = "获取数据")
	@RequestMapping(method = RequestMethod.POST, value = {"/{entity}/get","/{entity}/{key}/get"})
	public ResponseEntity<BaseData> doGet(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "key",required = false) String key,
			@Validated @RequestBody(required = false) BaseData baseData) {
		if(baseData==null)
		{
			if(StringUtils.isEmpty(key))
				throw new BadRequestAlertException("未找到要获取的键值信息",entity,null);
			baseData=new BaseData();
		}
		return ResponseEntity.status(HttpStatus.OK).body(dataService.getByMap(system,scope,entity,datasource,baseData.setKey(key)
				.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2)));
	}

	@ApiOperation(value = "批量删除数据", tags = {"数据" },  notes = "批量删除数据")
	@RequestMapping(method = RequestMethod.POST, value = {"/{entity}/getbatch"})
	public ResponseEntity<List<BaseData>> getBatch(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@RequestBody List<Object> datas) {
		if(ObjectUtils.isEmpty(datas))
			return ResponseEntity.status(HttpStatus.OK).body(new ArrayList<>());
		else if(datas.get(0) instanceof Map)
			return ResponseEntity.status(HttpStatus.OK).body(dataService.getByMapBatch(system,scope,entity,datasource,(List)datas));
		else
			return ResponseEntity.status(HttpStatus.OK).body(dataService.getBatch(system,scope,entity,datasource,(List)datas));
	}

    @ApiOperation(value = "删除数据", tags = {"数据" },  notes = "删除数据")
	@RequestMapping(method = RequestMethod.DELETE, value = {"/{entity}","/{entity}/{key}"})
    public ResponseEntity<Boolean> remove(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "key",required = false) String key,
			@RequestParam Map map) {
		BaseData baseData=BaseData.fromContext(map);
		return doRemove(system,scope,parentEntity,parentKey,parentEntity2,parentKey2,entity,datasource,key,baseData);
    }

	@ApiOperation(value = "删除数据", tags = {"数据" },  notes = "删除数据")
	@RequestMapping(method = RequestMethod.POST, value = {"/{entity}/remove","/{entity}/{key}/remove"})
	public ResponseEntity<Boolean> doRemove(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "key",required = false) String key,
			@RequestBody(required = false) BaseData baseData) {
		if(baseData==null)
		{
			if(StringUtils.isEmpty(key))
				throw new BadRequestAlertException("未找到要删除的键值信息",entity,null);
			baseData=new BaseData();
		}
		return ResponseEntity.status(HttpStatus.OK).body(dataService.removeByMap(system,scope,entity,datasource,baseData.setKey(key)
				.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2)));
	}

    @ApiOperation(value = "批量删除数据", tags = {"数据" },  notes = "批量删除数据")
	@RequestMapping(method = RequestMethod.DELETE, value = {"/{entity}/batch"})
    public ResponseEntity<Boolean> removeBatch(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource, 
			@RequestBody List<Object> datas) {
        return  doRemoveBatch(system,scope,parentEntity,parentKey,parentEntity2,parentKey2,entity,datasource,datas);
    }

	@ApiOperation(value = "批量删除数据", tags = {"数据" },  notes = "批量删除数据")
	@RequestMapping(method = RequestMethod.POST, value = {"/{entity}/removebatch"})
	public ResponseEntity<Boolean> doRemoveBatch(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource, 
			@RequestBody List<Object> datas) {
		if(ObjectUtils.isEmpty(datas))
			return ResponseEntity.status(HttpStatus.OK).body(true);
		else if(datas.get(0) instanceof Map)
			return ResponseEntity.status(HttpStatus.OK).body(dataService.removeByMapBatch(system,scope,entity,datasource,(List)datas));
		else
			return  ResponseEntity.status(HttpStatus.OK).body(dataService.removeBatch(system,scope,entity,datasource,(List)datas));
	}

    @ApiOperation(value = "更新数据", tags = {"数据" },  notes = "更新数据")
	@RequestMapping(method = RequestMethod.PUT, value = {"/{entity}","/{entity}/{key}"})
    public ResponseEntity<BaseData> update(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "key",required = false) String key,
			@RequestBody BaseData baseData) {
        return doUpdate(system,scope,parentEntity,parentKey,parentEntity2,parentKey2,entity,datasource,key,baseData);
    }

	@ApiOperation(value = "更新数据", tags = {"数据" },  notes = "更新数据")
	@RequestMapping(method = RequestMethod.POST, value = {"/{entity}/update","/{entity}/{key}/update"})
	public ResponseEntity<BaseData> doUpdate(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "key",required = false) String key,
			@RequestBody BaseData baseData) {
		dataService.update(system,scope,entity,datasource,baseData.setKey(key)
				.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2));
		return ResponseEntity.status(HttpStatus.OK).body(baseData);
	}

    @ApiOperation(value = "批量更新数据", tags = {"数据" },  notes = "批量更新数据")
	@RequestMapping(method = RequestMethod.PUT, value = {"/{entity}/batch"})
    public ResponseEntity<Boolean> updateBatch(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource, 
			@RequestBody List<BaseData> baseDatas) {
        return  doUpdateBatch(system,scope,parentEntity,parentKey,parentEntity2,parentKey2,entity,datasource,baseDatas);
    }

	@ApiOperation(value = "批量更新数据", tags = {"数据" },  notes = "批量更新数据")
	@RequestMapping(method = RequestMethod.POST, value = {"/{entity}/updatebatch"})
	public ResponseEntity<Boolean> doUpdateBatch(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource, 
			@RequestBody List<BaseData> baseDatas) {
		baseDatas.forEach(item->item.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2));
		dataService.updateBatch(system,scope,entity,datasource,baseDatas);
		return  ResponseEntity.status(HttpStatus.OK).body(true);
	}

    @ApiOperation(value = "检查数据", tags = {"数据" },  notes = "检查数据")
	@RequestMapping(method = {RequestMethod.GET}, value = {"/{entity}/checkkey","/{entity}/{key}/checkkey"})
    public ResponseEntity<Boolean> checkKey(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "key",required = false) String key,
			@RequestParam Map map) {
		BaseData baseData=BaseData.fromContext(map);
        return  doCheckKey(system,scope,parentEntity,parentKey,parentEntity2,parentKey2,entity,datasource,key,baseData);
    }

	@ApiOperation(value = "检查数据", tags = {"数据" },  notes = "检查数据")
	@RequestMapping(method = {RequestMethod.POST}, value = {"/{entity}/checkkey","/{entity}/{key}/checkkey"})
	public ResponseEntity<Boolean> doCheckKey(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "key",required = false) String key,
			@RequestBody(required = false) BaseData baseData) {
		if(baseData==null)
		{
			if(StringUtils.isEmpty(key))
				throw new BadRequestAlertException("未找到要检查的键值信息",entity,null);
			baseData=new BaseData();
		}
		return  ResponseEntity.status(HttpStatus.OK).body(dataService.checkKey(system,scope,entity,datasource,baseData.setKey(key)
				.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2)));
	}


	@ApiOperation(value = "获取数据草稿", tags = {"数据" },  notes = "获取数据草稿")
	@RequestMapping(method = {RequestMethod.GET}, value = {"/{entity}/getdraft","/{entity}/{key}/getdraft"})
    public ResponseEntity<BaseData> getDraft(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "key",required = false) String key,
			@RequestParam Map map) {
		BaseData baseData=BaseData.fromContext(map);
        return doGetDraft(system,scope,parentEntity,parentKey,parentEntity2,parentKey2,entity,datasource,key,baseData);
    }

	@ApiOperation(value = "获取数据草稿", tags = {"数据" },  notes = "获取数据草稿")
	@RequestMapping(method = {RequestMethod.POST}, value = {"/{entity}/getdraft","/{entity}/{key}/getdraft"})
	public ResponseEntity<BaseData> doGetDraft(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "key",required = false) String key,
			@RequestBody(required = false) BaseData baseData) {
		if(baseData==null)baseData=new BaseData();
		return ResponseEntity.status(HttpStatus.OK).body(dataService.getDraft(system,scope,entity,datasource,baseData.setKey(key)
				.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2)));
	}

    @ApiOperation(value = "保存数据", tags = {"数据" },  notes = "保存数据，自动判断插入和更新")
	@RequestMapping(method = RequestMethod.POST, value = {"/{entity}/save","/{entity}/{key}/save"})
    public ResponseEntity<BaseData> save(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "key",required = false) String key,
			@RequestBody BaseData baseData) {
        dataService.save(system,scope,entity,datasource,baseData.setKey(key)
				.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2));
        return ResponseEntity.status(HttpStatus.OK).body(baseData);
    }

    @ApiOperation(value = "批量保存数据", tags = {"数据" },  notes = "批量保存数据，自动判断插入和更新")
	@RequestMapping(method = RequestMethod.POST, value = {"/{entity}/savebatch"})
    public ResponseEntity<Boolean> saveBatch(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@RequestBody List<BaseData> baseDatas) {
		baseDatas.forEach(item->item.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2));
        dataService.saveBatch(system,scope,entity,datasource,baseDatas);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }


	@ApiOperation(value = "Select查询数据", tags = {"数据" } ,notes = "Select查询数据，GET，返回body<list>+header<page,total>")
	@RequestMapping(method= RequestMethod.GET , value={"/{entity}/select"})
	public ResponseEntity<List<BaseData>> select(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@RequestParam Map map) {
		FilterData context=FilterData.fromContext(map);
		return doSelect(system,scope,parentEntity,parentKey,parentEntity2,parentKey2,entity,datasource,context);
	}

	@ApiOperation(value = "查询数据", tags = {"数据" } ,notes = "查询数据，POST，返回body<list>+header<page,total>")
	@RequestMapping(method= RequestMethod.POST , value={"/{entity}/select"})
	public ResponseEntity<List<BaseData>> doSelect(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@RequestBody(required = false) FilterData context) {
		if(context==null)context=new FilterData();
		context.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2);
		if(context.needPage()) {
			Page<BaseData> baseDatas = dataService.select(system,scope,entity,datasource,context,context.getPageable()) ;
			List<BaseData> list = baseDatas.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(baseDatas.getTotalElements()))
					.body(list);
		}
		else {
			List<BaseData> list = dataService.select(system,scope,entity,datasource,context) ;
			return ResponseEntity.status(HttpStatus.OK)
					.header("x-page", "0")
					.header("x-per-page", String.valueOf(list.size()))
					.header("x-total", String.valueOf(list.size()))
					.body(list);
		}
	}


	@ApiOperation(value = "获取数据集", tags = {"数据" } ,notes = "获取数据集，GET，返回body<list>+header<page,total>")
    @RequestMapping(method= RequestMethod.GET , value={"/{entity}/fetch{dataset}"})
	public ResponseEntity<List<BaseData>> fetch(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "dataset",required = true) String dataset,
			@RequestParam Map map) {
		FilterData context=FilterData.fromContext(map);
		return doFetch(system,scope,parentEntity,parentKey,parentEntity2,parentKey2,entity,datasource,dataset,context);
	}

	@ApiOperation(value = "获取数据集", tags = {"数据" } ,notes = "获取数据集，POST，返回body<list>+header<page,total>")
	@RequestMapping(method= RequestMethod.POST , value={"/{entity}/fetch{dataset}"})
	public ResponseEntity<List<BaseData>> doFetch(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "dataset",required = true) String dataset,
			@RequestBody(required = false) FilterData context) {
		if(context==null)context=new FilterData();
		context.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2);
		if(context.needPage()) {
			Page<BaseData> baseDatas = dataService.fetch(system, scope, entity, datasource, dataset, context, context.getPageable());
			List<BaseData> list = baseDatas.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(baseDatas.getTotalElements()))
					.body(list);
		}
		else {
			List<BaseData> list = dataService.fetch(system,scope,entity,datasource,dataset,context) ;
			return ResponseEntity.status(HttpStatus.OK)
					.header("x-page", "0")
					.header("x-per-page", String.valueOf(list.size()))
					.header("x-total", String.valueOf(list.size()))
					.body(list);
		}
	}

	@ApiOperation(value = "获取数据集", tags = {"数据" } ,notes = "获取数据集，POST，返回body<page,total,list>")
    @RequestMapping(method= RequestMethod.POST , value={"/{entity}/search{dataset}"})
	public ResponseEntity<Page<BaseData>> search(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "dataset",required = true) String dataset,
			@RequestBody(required = false) FilterData context) {
		if(context==null)context=new FilterData();
		context.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2);
		Page<BaseData> baseDatas = dataService.fetch(system,scope,entity,datasource,dataset,context,context.getPageable()) ;
		return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(baseDatas.getContent(), context.getPageable(), baseDatas.getTotalElements()));
	}



	@ApiOperation(value = "查询数据", tags = {"数据" } ,notes = "查询数据，GET，返回body<list>+header<page,total>")
	@RequestMapping(method= RequestMethod.GET , value={"/{entity}/query{dataquery}"})
	public ResponseEntity<List<BaseData>> query(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "dataquery",required = true) String dataquery,
			@RequestParam Map map) {
		FilterData context=FilterData.fromContext(map);
		return doQuery(system,scope,parentEntity,parentKey,parentEntity2,parentKey2,entity,datasource,dataquery,context);
	}

	@ApiOperation(value = "查询数据", tags = {"数据" } ,notes = "查询数据，POST，返回body<list>+header<page,total>")
	@RequestMapping(method= RequestMethod.POST , value={"/{entity}/query{dataquery}"})
	public ResponseEntity<List<BaseData>> doQuery(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "dataquery",required = true) String dataquery,
			@RequestBody(required = false) FilterData context) {
		if(context==null)context=new FilterData();
		context.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2);
		if(context.needPage()) {
			Page<BaseData> baseDatas = dataService.query(system,scope,entity,datasource,dataquery,context,context.getPageable()) ;
			List<BaseData> list = baseDatas.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(baseDatas.getTotalElements()))
					.body(list);
		}
		else {
			List<BaseData> list = dataService.query(system,scope,entity,datasource,dataquery,context) ;
			return ResponseEntity.status(HttpStatus.OK)
					.header("x-page", "0")
					.header("x-per-page", String.valueOf(list.size()))
					.header("x-total", String.valueOf(list.size()))
					.body(list);
		}
	}

	@ApiOperation(value = "查询数据", tags = {"数据" } ,notes = "查询数据，POST，返回body<page,total,list>")
	@RequestMapping(method= RequestMethod.POST , value={"/{entity}/page{dataquery}"})
	public ResponseEntity<Page<BaseData>> queryPage(@PathVariable(name = "system",required = true) String system,
			@PathVariable(name = "scope",required = false) String scope,
			@PathVariable(name = "parentEntity",required = false) String parentEntity,
			@PathVariable(name = "parentKey",required = false) String parentKey,
			@PathVariable(name = "parentEntity2",required = false) String parentEntity2,
			@PathVariable(name = "parentKey2",required = false) String parentKey2,
			@PathVariable(name = "entity",required = true) String entity,
			@RequestParam(name = "datasource",required = false) String datasource,
			@PathVariable(name = "dataquery",required = true) String dataquery,
			@RequestBody(required = false) FilterData context) {
		if(context==null)context=new FilterData();
		context.addParent(parentEntity,parentKey).addParent(parentEntity2,parentKey2);
		Page<BaseData> baseDatas = dataService.fetch(system,scope,entity,datasource,dataquery,context,context.getPageable()) ;
		return ResponseEntity.status(HttpStatus.OK)
				.body(new PageImpl(baseDatas.getContent(), context.getPageable(), baseDatas.getTotalElements()));
	}

	@RequestMapping(method = RequestMethod.GET, value = {"/reload"})
	public ResponseEntity<Boolean> reload(@PathVariable(name = "system",required = true) String systemId) {
		modelService.refreshDynamicModel(systemId);
		return ResponseEntity.ok(true);
	}


	@Value("${ibiz.enablePermissionValid:false}")
	boolean enablePermissionValid;  //是否开启权限校验

	@RequestMapping(method = RequestMethod.GET, value = {"/appdata"})
	public ResponseEntity<JSONObject> getAppData(@PathVariable(name = "system",required = true) String systemId) {

		JSONObject appData = new JSONObject() ;
		Set<String> appMenu = new HashSet();
		Set<String> uniRes = new HashSet();

		AuthenticationUser curUser = AuthenticationUser.getAuthenticationUser();
		if(enablePermissionValid){
			Collection<GrantedAuthority> authorities=curUser.getAuthorities();
			Iterator it = authorities.iterator();
			while(it.hasNext()) {
				GrantedAuthority authority = (GrantedAuthority)it.next();
				String strAuthority=authority.getAuthority();
				if(strAuthority.startsWith("UNIRES_"+systemId)) {
					uniRes.add(strAuthority.substring(systemId.length()+8));
				}
				else if(strAuthority.startsWith("APPMENU_"+systemId)){
					appMenu.add(strAuthority.substring(systemId.length()+9));
				}
			}
		}
		Map<String,Object> context = new HashMap<>();
		context.putAll(curUser.getSessionParams());
		context.put("srfusername",curUser.getPersonname());
		appData.put("context",context);
		appData.put("unires",uniRes);
		appData.put("appmenu",appMenu);
		appData.put("enablepermissionvalid",enablePermissionValid);
		if(curUser.getSuperuser()==1){
			appData.put("enablepermissionvalid",false);
		}
		else{
			appData.put("enablepermissionvalid",enablePermissionValid);
		}
		return ResponseEntity.status(HttpStatus.OK).body(appData);
	}
}

