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.sales.domain.Goal;
import cn.ibizlab.businesscentral.core.sales.service.IGoalService;
import cn.ibizlab.businesscentral.core.sales.filter.GoalSearchContext;

@Slf4j
@Api(tags = {"目标" })
@RestController("CentralApi-goal")
@RequestMapping("")
public class GoalResource {

    @Autowired
    public IGoalService goalService;

    @Autowired
    @Lazy
    public GoalMapping goalMapping;

    @PreAuthorize("hasPermission(this.goalService.get(#goal_id),'iBizBusinessCentral-Goal-Remove')")
    @ApiOperation(value = "删除目标", tags = {"目标" },  notes = "删除目标")
	@RequestMapping(method = RequestMethod.DELETE, value = "/goals/{goal_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("goal_id") String goal_id) {
         return ResponseEntity.status(HttpStatus.OK).body(goalService.remove(goal_id));
    }

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

    @PostAuthorize("hasPermission(this.goalMapping.toDomain(returnObject.body),'iBizBusinessCentral-Goal-Get')")
    @ApiOperation(value = "获取目标", tags = {"目标" },  notes = "获取目标")
	@RequestMapping(method = RequestMethod.GET, value = "/goals/{goal_id}")
    public ResponseEntity<GoalDTO> get(@PathVariable("goal_id") String goal_id) {
        Goal domain = goalService.get(goal_id);
        GoalDTO dto = goalMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.goalMapping.toDomain(#goaldto),'iBizBusinessCentral-Goal-Save')")
    @ApiOperation(value = "保存目标", tags = {"目标" },  notes = "保存目标")
	@RequestMapping(method = RequestMethod.POST, value = "/goals/save")
    public ResponseEntity<Boolean> save(@RequestBody GoalDTO goaldto) {
        return ResponseEntity.status(HttpStatus.OK).body(goalService.save(goalMapping.toDomain(goaldto)));
    }

    @PreAuthorize("hasPermission(this.goalMapping.toDomain(#goaldtos),'iBizBusinessCentral-Goal-Save')")
    @ApiOperation(value = "批量保存目标", tags = {"目标" },  notes = "批量保存目标")
	@RequestMapping(method = RequestMethod.POST, value = "/goals/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<GoalDTO> goaldtos) {
        goalService.saveBatch(goalMapping.toDomain(goaldtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.goalMapping.toDomain(#goaldto),'iBizBusinessCentral-Goal-Create')")
    @ApiOperation(value = "新建目标", tags = {"目标" },  notes = "新建目标")
	@RequestMapping(method = RequestMethod.POST, value = "/goals")
    @Transactional
    public ResponseEntity<GoalDTO> create(@RequestBody GoalDTO goaldto) {
        Goal domain = goalMapping.toDomain(goaldto);
		goalService.create(domain);
        GoalDTO dto = goalMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.goalMapping.toDomain(#goaldtos),'iBizBusinessCentral-Goal-Create')")
    @ApiOperation(value = "批量新建目标", tags = {"目标" },  notes = "批量新建目标")
	@RequestMapping(method = RequestMethod.POST, value = "/goals/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<GoalDTO> goaldtos) {
        goalService.createBatch(goalMapping.toDomain(goaldtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.goalService.get(#goal_id),'iBizBusinessCentral-Goal-Update')")
    @ApiOperation(value = "更新目标", tags = {"目标" },  notes = "更新目标")
	@RequestMapping(method = RequestMethod.PUT, value = "/goals/{goal_id}")
    @Transactional
    public ResponseEntity<GoalDTO> update(@PathVariable("goal_id") String goal_id, @RequestBody GoalDTO goaldto) {
		Goal domain  = goalMapping.toDomain(goaldto);
        domain .setGoalid(goal_id);
		goalService.update(domain );
		GoalDTO dto = goalMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.goalService.getGoalByEntities(this.goalMapping.toDomain(#goaldtos)),'iBizBusinessCentral-Goal-Update')")
    @ApiOperation(value = "批量更新目标", tags = {"目标" },  notes = "批量更新目标")
	@RequestMapping(method = RequestMethod.PUT, value = "/goals/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<GoalDTO> goaldtos) {
        goalService.updateBatch(goalMapping.toDomain(goaldtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "检查目标", tags = {"目标" },  notes = "检查目标")
	@RequestMapping(method = RequestMethod.POST, value = "/goals/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody GoalDTO goaldto) {
        return  ResponseEntity.status(HttpStatus.OK).body(goalService.checkKey(goalMapping.toDomain(goaldto)));
    }

    @ApiOperation(value = "获取目标草稿", tags = {"目标" },  notes = "获取目标草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/goals/getdraft")
    public ResponseEntity<GoalDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(goalMapping.toDto(goalService.getDraft(new Goal())));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Goal-Default-all')")
	@ApiOperation(value = "获取DEFAULT", tags = {"目标" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/goals/fetchdefault")
	public ResponseEntity<List<GoalDTO>> fetchDefault(GoalSearchContext context) {
        Page<Goal> domains = goalService.searchDefault(context) ;
        List<GoalDTO> list = goalMapping.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-Goal-Default-all')")
	@ApiOperation(value = "查询DEFAULT", tags = {"目标" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/goals/searchdefault")
	public ResponseEntity<Page<GoalDTO>> searchDefault(@RequestBody GoalSearchContext context) {
        Page<Goal> domains = goalService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(goalMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

