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.Quote;
import cn.ibizlab.businesscentral.core.sales.service.IQuoteService;
import cn.ibizlab.businesscentral.core.sales.filter.QuoteSearchContext;

@Slf4j
@Api(tags = {"报价单" })
@RestController("CentralApi-quote")
@RequestMapping("")
public class QuoteResource {

    @Autowired
    public IQuoteService quoteService;

    @Autowired
    @Lazy
    public QuoteMapping quoteMapping;

    @PreAuthorize("hasPermission(this.quoteMapping.toDomain(#quotedto),'iBizBusinessCentral-Quote-Create')")
    @ApiOperation(value = "新建报价单", tags = {"报价单" },  notes = "新建报价单")
	@RequestMapping(method = RequestMethod.POST, value = "/quotes")
    @Transactional
    public ResponseEntity<QuoteDTO> create(@RequestBody QuoteDTO quotedto) {
        Quote domain = quoteMapping.toDomain(quotedto);
		quoteService.create(domain);
        QuoteDTO dto = quoteMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.quoteMapping.toDomain(#quotedtos),'iBizBusinessCentral-Quote-Create')")
    @ApiOperation(value = "批量新建报价单", tags = {"报价单" },  notes = "批量新建报价单")
	@RequestMapping(method = RequestMethod.POST, value = "/quotes/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<QuoteDTO> quotedtos) {
        quoteService.createBatch(quoteMapping.toDomain(quotedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.quoteMapping.toDomain(#quotedto),'iBizBusinessCentral-Quote-Save')")
    @ApiOperation(value = "保存报价单", tags = {"报价单" },  notes = "保存报价单")
	@RequestMapping(method = RequestMethod.POST, value = "/quotes/save")
    public ResponseEntity<Boolean> save(@RequestBody QuoteDTO quotedto) {
        return ResponseEntity.status(HttpStatus.OK).body(quoteService.save(quoteMapping.toDomain(quotedto)));
    }

    @PreAuthorize("hasPermission(this.quoteMapping.toDomain(#quotedtos),'iBizBusinessCentral-Quote-Save')")
    @ApiOperation(value = "批量保存报价单", tags = {"报价单" },  notes = "批量保存报价单")
	@RequestMapping(method = RequestMethod.POST, value = "/quotes/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<QuoteDTO> quotedtos) {
        quoteService.saveBatch(quoteMapping.toDomain(quotedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.quoteService.get(#quote_id),'iBizBusinessCentral-Quote-Remove')")
    @ApiOperation(value = "删除报价单", tags = {"报价单" },  notes = "删除报价单")
	@RequestMapping(method = RequestMethod.DELETE, value = "/quotes/{quote_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("quote_id") String quote_id) {
         return ResponseEntity.status(HttpStatus.OK).body(quoteService.remove(quote_id));
    }

    @PreAuthorize("hasPermission(this.quoteService.getQuoteByIds(#ids),'iBizBusinessCentral-Quote-Remove')")
    @ApiOperation(value = "批量删除报价单", tags = {"报价单" },  notes = "批量删除报价单")
	@RequestMapping(method = RequestMethod.DELETE, value = "/quotes/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        quoteService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.quoteService.get(#quote_id),'iBizBusinessCentral-Quote-Update')")
    @ApiOperation(value = "更新报价单", tags = {"报价单" },  notes = "更新报价单")
	@RequestMapping(method = RequestMethod.PUT, value = "/quotes/{quote_id}")
    @Transactional
    public ResponseEntity<QuoteDTO> update(@PathVariable("quote_id") String quote_id, @RequestBody QuoteDTO quotedto) {
		Quote domain  = quoteMapping.toDomain(quotedto);
        domain .setQuoteid(quote_id);
		quoteService.update(domain );
		QuoteDTO dto = quoteMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.quoteService.getQuoteByEntities(this.quoteMapping.toDomain(#quotedtos)),'iBizBusinessCentral-Quote-Update')")
    @ApiOperation(value = "批量更新报价单", tags = {"报价单" },  notes = "批量更新报价单")
	@RequestMapping(method = RequestMethod.PUT, value = "/quotes/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<QuoteDTO> quotedtos) {
        quoteService.updateBatch(quoteMapping.toDomain(quotedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.quoteMapping.toDomain(returnObject.body),'iBizBusinessCentral-Quote-Get')")
    @ApiOperation(value = "获取报价单", tags = {"报价单" },  notes = "获取报价单")
	@RequestMapping(method = RequestMethod.GET, value = "/quotes/{quote_id}")
    public ResponseEntity<QuoteDTO> get(@PathVariable("quote_id") String quote_id) {
        Quote domain = quoteService.get(quote_id);
        QuoteDTO dto = quoteMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "检查报价单", tags = {"报价单" },  notes = "检查报价单")
	@RequestMapping(method = RequestMethod.POST, value = "/quotes/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody QuoteDTO quotedto) {
        return  ResponseEntity.status(HttpStatus.OK).body(quoteService.checkKey(quoteMapping.toDomain(quotedto)));
    }

    @ApiOperation(value = "获取报价单草稿", tags = {"报价单" },  notes = "获取报价单草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/quotes/getdraft")
    public ResponseEntity<QuoteDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(quoteMapping.toDto(quoteService.getDraft(new Quote())));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Quote-Default-all')")
	@ApiOperation(value = "获取DEFAULT", tags = {"报价单" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/quotes/fetchdefault")
	public ResponseEntity<List<QuoteDTO>> fetchDefault(QuoteSearchContext context) {
        Page<Quote> domains = quoteService.searchDefault(context) ;
        List<QuoteDTO> list = quoteMapping.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-Quote-Default-all')")
	@ApiOperation(value = "查询DEFAULT", tags = {"报价单" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/quotes/searchdefault")
	public ResponseEntity<Page<QuoteDTO>> searchDefault(@RequestBody QuoteSearchContext context) {
        Page<Quote> domains = quoteService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(quoteMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

