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.RuleItem;
import cn.ibizlab.core.rule.service.IRuleItemService;
import cn.ibizlab.core.rule.filter.RuleItemSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"规则" })
@RestController("api-ruleitem")
@RequestMapping("")
public class RuleItemResource {

    @Autowired
    public IRuleItemService ruleitemService;

    @Autowired
    @Lazy
    public RuleItemMapping ruleitemMapping;

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleItem-Create-all')")
    @ApiOperation(value = "新建规则", tags = {"规则" },  notes = "新建规则")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleitems")
    public ResponseEntity<RuleItemDTO> create(@Validated @RequestBody RuleItemDTO ruleitemdto) {
        RuleItem domain = ruleitemMapping.toDomain(ruleitemdto);
		ruleitemService.create(domain);
        RuleItemDTO dto = ruleitemMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleItem-Create-all')")
    @ApiOperation(value = "批量新建规则", tags = {"规则" },  notes = "批量新建规则")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleitems/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<RuleItemDTO> ruleitemdtos) {
        ruleitemService.createBatch(ruleitemMapping.toDomain(ruleitemdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "ruleitem" , versionfield = "updatedate")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleItem-Update-all')")
    @ApiOperation(value = "更新规则", tags = {"规则" },  notes = "更新规则")
	@RequestMapping(method = RequestMethod.PUT, value = "/ruleitems/{ruleitem_id}")
    public ResponseEntity<RuleItemDTO> update(@PathVariable("ruleitem_id") String ruleitem_id, @RequestBody RuleItemDTO ruleitemdto) {
		RuleItem domain  = ruleitemMapping.toDomain(ruleitemdto);
        domain .setRuleId(ruleitem_id);
		ruleitemService.update(domain );
		RuleItemDTO dto = ruleitemMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleItem-Update-all')")
    @ApiOperation(value = "批量更新规则", tags = {"规则" },  notes = "批量更新规则")
	@RequestMapping(method = RequestMethod.PUT, value = "/ruleitems/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<RuleItemDTO> ruleitemdtos) {
        ruleitemService.updateBatch(ruleitemMapping.toDomain(ruleitemdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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

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

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleItem-Get-all')")
    @ApiOperation(value = "获取规则", tags = {"规则" },  notes = "获取规则")
	@RequestMapping(method = RequestMethod.GET, value = "/ruleitems/{ruleitem_id}")
    public ResponseEntity<RuleItemDTO> get(@PathVariable("ruleitem_id") String ruleitem_id) {
        RuleItem domain = ruleitemService.get(ruleitem_id);
        RuleItemDTO dto = ruleitemMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取规则草稿", tags = {"规则" },  notes = "获取规则草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/ruleitems/getdraft")
    public ResponseEntity<RuleItemDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(ruleitemMapping.toDto(ruleitemService.getDraft(new RuleItem())));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleItem-BuildRuleFile-all')")
    @ApiOperation(value = "生成规则文件", tags = {"规则" },  notes = "生成规则文件")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleitems/{ruleitem_id}/buildrulefile")
    public ResponseEntity<RuleItemDTO> buildRuleFile(@PathVariable("ruleitem_id") String ruleitem_id, @RequestBody RuleItemDTO ruleitemdto) {
        RuleItem domain = ruleitemMapping.toDomain(ruleitemdto);
        domain.setRuleId(ruleitem_id);
        domain = ruleitemService.buildRuleFile(domain);
        ruleitemdto = ruleitemMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ruleitemdto);
    }
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleItem-BuildRuleFile-all')")
    @ApiOperation(value = "批量处理[生成规则文件]", tags = {"规则" },  notes = "批量处理[生成规则文件]")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleitems/{ruleitem_id}/buildrulefilebatch")
    public ResponseEntity<Boolean> buildRuleFileBatch(@RequestBody List<RuleItemDTO> ruleitemdtos) {
        return ResponseEntity.status(HttpStatus.OK).body(ruleitemService.buildRuleFileBatch(ruleitemMapping.toDomain(ruleitemdtos)));
    }

    @ApiOperation(value = "检查规则", tags = {"规则" },  notes = "检查规则")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleitems/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody RuleItemDTO ruleitemdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(ruleitemService.checkKey(ruleitemMapping.toDomain(ruleitemdto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleItem-Modelchange-all')")
    @ApiOperation(value = "modelchange", tags = {"规则" },  notes = "modelchange")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleitems/{ruleitem_id}/modelchange")
    public ResponseEntity<RuleItemDTO> modelchange(@PathVariable("ruleitem_id") String ruleitem_id, @RequestBody RuleItemDTO ruleitemdto) {
        RuleItem domain = ruleitemMapping.toDomain(ruleitemdto);
        domain.setRuleId(ruleitem_id);
        domain = ruleitemService.modelchange(domain);
        ruleitemdto = ruleitemMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ruleitemdto);
    }
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleItem-Modelchange-all')")
    @ApiOperation(value = "批量处理[modelchange]", tags = {"规则" },  notes = "批量处理[modelchange]")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleitems/{ruleitem_id}/modelchangebatch")
    public ResponseEntity<Boolean> modelchangeBatch(@RequestBody List<RuleItemDTO> ruleitemdtos) {
        return ResponseEntity.status(HttpStatus.OK).body(ruleitemService.modelchangeBatch(ruleitemMapping.toDomain(ruleitemdtos)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleItem-Save-all')")
    @ApiOperation(value = "保存规则", tags = {"规则" },  notes = "保存规则")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleitems/save")
    public ResponseEntity<Boolean> save(@RequestBody RuleItemDTO ruleitemdto) {
        return ResponseEntity.status(HttpStatus.OK).body(ruleitemService.save(ruleitemMapping.toDomain(ruleitemdto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-RuleItem-Save-all')")
    @ApiOperation(value = "批量保存规则", tags = {"规则" },  notes = "批量保存规则")
	@RequestMapping(method = RequestMethod.POST, value = "/ruleitems/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<RuleItemDTO> ruleitemdtos) {
        ruleitemService.saveBatch(ruleitemMapping.toDomain(ruleitemdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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


}

