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.rule.domain.RuleEngine;
import cn.ibizlab.core.rule.service.IRuleEngineService;
import cn.ibizlab.core.rule.filter.RuleEngineSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"规则引擎" })
@RestController("api-ruleengine")
@RequestMapping("")
public class RuleEngineResource {

    @Autowired
    public IRuleEngineService ruleengineService;

    @Autowired
    @Lazy
    public RuleEngineMapping ruleengineMapping;

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleEngine-Create-all')")
    @ApiOperation(value = "新建规则引擎", tags = {"规则引擎" },  notes = "新建规则引擎")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleengines")
    public ResponseEntity<RuleEngineDTO> create(@Validated @RequestBody RuleEngineDTO ruleenginedto) {
        RuleEngine domain = ruleengineMapping.toDomain(ruleenginedto);
		ruleengineService.create(domain);
        RuleEngineDTO dto = ruleengineMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleEngine-Create-all')")
    @ApiOperation(value = "批量新建规则引擎", tags = {"规则引擎" },  notes = "批量新建规则引擎")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleengines/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<RuleEngineDTO> ruleenginedtos) {
        ruleengineService.createBatch(ruleengineMapping.toDomain(ruleenginedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleEngine-Update-all')")
    @ApiOperation(value = "更新规则引擎", tags = {"规则引擎" },  notes = "更新规则引擎")
	@RequestMapping(method = RequestMethod.PUT, value = "/ruleengines/{ruleengine_id}")
    public ResponseEntity<RuleEngineDTO> update(@PathVariable("ruleengine_id") String ruleengine_id, @RequestBody RuleEngineDTO ruleenginedto) {
		RuleEngine domain  = ruleengineMapping.toDomain(ruleenginedto);
        domain .setEngineId(ruleengine_id);
		ruleengineService.update(domain );
		RuleEngineDTO dto = ruleengineMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleEngine-Update-all')")
    @ApiOperation(value = "批量更新规则引擎", tags = {"规则引擎" },  notes = "批量更新规则引擎")
	@RequestMapping(method = RequestMethod.PUT, value = "/ruleengines/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<RuleEngineDTO> ruleenginedtos) {
        ruleengineService.updateBatch(ruleengineMapping.toDomain(ruleenginedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleEngine-Remove-all')")
    @ApiOperation(value = "删除规则引擎", tags = {"规则引擎" },  notes = "删除规则引擎")
	@RequestMapping(method = RequestMethod.DELETE, value = "/ruleengines/{ruleengine_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("ruleengine_id") String ruleengine_id) {
         return ResponseEntity.status(HttpStatus.OK).body(ruleengineService.remove(ruleengine_id));
    }

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

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleEngine-Get-all')")
    @ApiOperation(value = "获取规则引擎", tags = {"规则引擎" },  notes = "获取规则引擎")
	@RequestMapping(method = RequestMethod.GET, value = "/ruleengines/{ruleengine_id}")
    public ResponseEntity<RuleEngineDTO> get(@PathVariable("ruleengine_id") String ruleengine_id) {
        RuleEngine domain = ruleengineService.get(ruleengine_id);
        RuleEngineDTO dto = ruleengineMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取规则引擎草稿", tags = {"规则引擎" },  notes = "获取规则引擎草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/ruleengines/getdraft")
    public ResponseEntity<RuleEngineDTO> getDraft(RuleEngineDTO dto) {
        RuleEngine domain = ruleengineMapping.toDomain(dto);
        return ResponseEntity.status(HttpStatus.OK).body(ruleengineMapping.toDto(ruleengineService.getDraft(domain)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleEngine-Check-all')")
    @ApiOperation(value = "校验", tags = {"规则引擎" },  notes = "校验")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleengines/{ruleengine_id}/check")
    public ResponseEntity<RuleEngineDTO> check(@PathVariable("ruleengine_id") String ruleengine_id, @RequestBody RuleEngineDTO ruleenginedto) {
        RuleEngine domain = ruleengineMapping.toDomain(ruleenginedto);
        domain.setEngineId(ruleengine_id);
        domain = ruleengineService.check(domain);
        ruleenginedto = ruleengineMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ruleenginedto);
    }
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleEngine-Check-all')")
    @ApiOperation(value = "批量处理[校验]", tags = {"规则引擎" },  notes = "批量处理[校验]")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleengines/checkbatch")
    public ResponseEntity<Boolean> checkBatch(@RequestBody List<RuleEngineDTO> ruleenginedtos) {
        List<RuleEngine> domains = ruleengineMapping.toDomain(ruleenginedtos);
        boolean result = ruleengineService.checkBatch(domains);
        return ResponseEntity.status(HttpStatus.OK).body(result);
    }

    @ApiOperation(value = "检查规则引擎", tags = {"规则引擎" },  notes = "检查规则引擎")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleengines/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody RuleEngineDTO ruleenginedto) {
        return  ResponseEntity.status(HttpStatus.OK).body(ruleengineService.checkKey(ruleengineMapping.toDomain(ruleenginedto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleEngine-Run-all')")
    @ApiOperation(value = "运行", tags = {"规则引擎" },  notes = "运行")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleengines/{ruleengine_id}/run")
    public ResponseEntity<RuleEngineDTO> run(@PathVariable("ruleengine_id") String ruleengine_id, @RequestBody RuleEngineDTO ruleenginedto) {
        RuleEngine domain = ruleengineMapping.toDomain(ruleenginedto);
        domain.setEngineId(ruleengine_id);
        domain = ruleengineService.run(domain);
        ruleenginedto = ruleengineMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ruleenginedto);
    }
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleEngine-Run-all')")
    @ApiOperation(value = "批量处理[运行]", tags = {"规则引擎" },  notes = "批量处理[运行]")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleengines/runbatch")
    public ResponseEntity<Boolean> runBatch(@RequestBody List<RuleEngineDTO> ruleenginedtos) {
        List<RuleEngine> domains = ruleengineMapping.toDomain(ruleenginedtos);
        boolean result = ruleengineService.runBatch(domains);
        return ResponseEntity.status(HttpStatus.OK).body(result);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleEngine-Save-all')")
    @ApiOperation(value = "保存规则引擎", tags = {"规则引擎" },  notes = "保存规则引擎")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleengines/save")
    public ResponseEntity<Boolean> save(@RequestBody RuleEngineDTO ruleenginedto) {
        return ResponseEntity.status(HttpStatus.OK).body(ruleengineService.save(ruleengineMapping.toDomain(ruleenginedto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleEngine-Save-all')")
    @ApiOperation(value = "批量保存规则引擎", tags = {"规则引擎" },  notes = "批量保存规则引擎")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleengines/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<RuleEngineDTO> ruleenginedtos) {
        ruleengineService.saveBatch(ruleengineMapping.toDomain(ruleenginedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleEngine-searchDefault-all')")
	@ApiOperation(value = "获取数据集", tags = {"规则引擎" } ,notes = "获取数据集")
    @RequestMapping(method= RequestMethod.GET , value="/ruleengines/fetchdefault")
	public ResponseEntity<List<RuleEngineDTO>> fetchDefault(RuleEngineSearchContext context) {
        Page<RuleEngine> domains = ruleengineService.searchDefault(context) ;
        List<RuleEngineDTO> list = ruleengineMapping.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-RuleEngine-searchDefault-all')")
	@ApiOperation(value = "查询数据集", tags = {"规则引擎" } ,notes = "查询数据集")
    @RequestMapping(method= RequestMethod.POST , value="/ruleengines/searchdefault")
	public ResponseEntity<Page<RuleEngineDTO>> searchDefault(@RequestBody RuleEngineSearchContext context) {
        Page<RuleEngine> domains = ruleengineService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(ruleengineMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}


}

