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.service.domain.Entitlement;
import cn.ibizlab.businesscentral.core.service.service.IEntitlementService;
import cn.ibizlab.businesscentral.core.service.filter.EntitlementSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"权利" })
@RestController("CentralApi-entitlement")
@RequestMapping("")
public class EntitlementResource {

    @Autowired
    public IEntitlementService entitlementService;

    @Autowired
    @Lazy
    public EntitlementMapping entitlementMapping;

    @PreAuthorize("hasPermission(this.entitlementMapping.toDomain(#entitlementdto),'iBizBusinessCentral-Entitlement-Create')")
    @ApiOperation(value = "新建权利", tags = {"权利" },  notes = "新建权利")
	@RequestMapping(method = RequestMethod.POST, value = "/entitlements")
    @Transactional
    public ResponseEntity<EntitlementDTO> create(@RequestBody EntitlementDTO entitlementdto) {
        Entitlement domain = entitlementMapping.toDomain(entitlementdto);
		entitlementService.create(domain);
        EntitlementDTO dto = entitlementMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.entitlementMapping.toDomain(#entitlementdtos),'iBizBusinessCentral-Entitlement-Create')")
    @ApiOperation(value = "批量新建权利", tags = {"权利" },  notes = "批量新建权利")
	@RequestMapping(method = RequestMethod.POST, value = "/entitlements/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<EntitlementDTO> entitlementdtos) {
        entitlementService.createBatch(entitlementMapping.toDomain(entitlementdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "entitlement" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.entitlementService.get(#entitlement_id),'iBizBusinessCentral-Entitlement-Update')")
    @ApiOperation(value = "更新权利", tags = {"权利" },  notes = "更新权利")
	@RequestMapping(method = RequestMethod.PUT, value = "/entitlements/{entitlement_id}")
    @Transactional
    public ResponseEntity<EntitlementDTO> update(@PathVariable("entitlement_id") String entitlement_id, @RequestBody EntitlementDTO entitlementdto) {
		Entitlement domain  = entitlementMapping.toDomain(entitlementdto);
        domain .setEntitlementid(entitlement_id);
		entitlementService.update(domain );
		EntitlementDTO dto = entitlementMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.entitlementService.getEntitlementByEntities(this.entitlementMapping.toDomain(#entitlementdtos)),'iBizBusinessCentral-Entitlement-Update')")
    @ApiOperation(value = "批量更新权利", tags = {"权利" },  notes = "批量更新权利")
	@RequestMapping(method = RequestMethod.PUT, value = "/entitlements/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<EntitlementDTO> entitlementdtos) {
        entitlementService.updateBatch(entitlementMapping.toDomain(entitlementdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.entitlementService.get(#entitlement_id),'iBizBusinessCentral-Entitlement-Remove')")
    @ApiOperation(value = "删除权利", tags = {"权利" },  notes = "删除权利")
	@RequestMapping(method = RequestMethod.DELETE, value = "/entitlements/{entitlement_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("entitlement_id") String entitlement_id) {
         return ResponseEntity.status(HttpStatus.OK).body(entitlementService.remove(entitlement_id));
    }

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

    @PostAuthorize("hasPermission(this.entitlementMapping.toDomain(returnObject.body),'iBizBusinessCentral-Entitlement-Get')")
    @ApiOperation(value = "获取权利", tags = {"权利" },  notes = "获取权利")
	@RequestMapping(method = RequestMethod.GET, value = "/entitlements/{entitlement_id}")
    public ResponseEntity<EntitlementDTO> get(@PathVariable("entitlement_id") String entitlement_id) {
        Entitlement domain = entitlementService.get(entitlement_id);
        EntitlementDTO dto = entitlementMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取权利草稿", tags = {"权利" },  notes = "获取权利草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/entitlements/getdraft")
    public ResponseEntity<EntitlementDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(entitlementMapping.toDto(entitlementService.getDraft(new Entitlement())));
    }

    @ApiOperation(value = "检查权利", tags = {"权利" },  notes = "检查权利")
	@RequestMapping(method = RequestMethod.POST, value = "/entitlements/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody EntitlementDTO entitlementdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(entitlementService.checkKey(entitlementMapping.toDomain(entitlementdto)));
    }

    @PreAuthorize("hasPermission(this.entitlementMapping.toDomain(#entitlementdto),'iBizBusinessCentral-Entitlement-Save')")
    @ApiOperation(value = "保存权利", tags = {"权利" },  notes = "保存权利")
	@RequestMapping(method = RequestMethod.POST, value = "/entitlements/save")
    public ResponseEntity<Boolean> save(@RequestBody EntitlementDTO entitlementdto) {
        return ResponseEntity.status(HttpStatus.OK).body(entitlementService.save(entitlementMapping.toDomain(entitlementdto)));
    }

    @PreAuthorize("hasPermission(this.entitlementMapping.toDomain(#entitlementdtos),'iBizBusinessCentral-Entitlement-Save')")
    @ApiOperation(value = "批量保存权利", tags = {"权利" },  notes = "批量保存权利")
	@RequestMapping(method = RequestMethod.POST, value = "/entitlements/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<EntitlementDTO> entitlementdtos) {
        entitlementService.saveBatch(entitlementMapping.toDomain(entitlementdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Entitlement-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Entitlement-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"权利" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/entitlements/fetchdefault")
	public ResponseEntity<List<EntitlementDTO>> fetchDefault(EntitlementSearchContext context) {
        Page<Entitlement> domains = entitlementService.searchDefault(context) ;
        List<EntitlementDTO> list = entitlementMapping.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-Entitlement-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Entitlement-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"权利" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/entitlements/searchdefault")
	public ResponseEntity<Page<EntitlementDTO>> searchDefault(@RequestBody EntitlementSearchContext context) {
        Page<Entitlement> domains = entitlementService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(entitlementMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

