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.finance.domain.Invoice;
import cn.ibizlab.businesscentral.core.finance.service.IInvoiceService;
import cn.ibizlab.businesscentral.core.finance.filter.InvoiceSearchContext;

@Slf4j
@Api(tags = {"发票" })
@RestController("CentralApi-invoice")
@RequestMapping("")
public class InvoiceResource {

    @Autowired
    public IInvoiceService invoiceService;

    @Autowired
    @Lazy
    public InvoiceMapping invoiceMapping;

    @PreAuthorize("hasPermission(this.invoiceMapping.toDomain(#invoicedto),'iBizBusinessCentral-Invoice-Create')")
    @ApiOperation(value = "新建发票", tags = {"发票" },  notes = "新建发票")
	@RequestMapping(method = RequestMethod.POST, value = "/invoices")
    @Transactional
    public ResponseEntity<InvoiceDTO> create(@RequestBody InvoiceDTO invoicedto) {
        Invoice domain = invoiceMapping.toDomain(invoicedto);
		invoiceService.create(domain);
        InvoiceDTO dto = invoiceMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.invoiceMapping.toDomain(#invoicedtos),'iBizBusinessCentral-Invoice-Create')")
    @ApiOperation(value = "批量新建发票", tags = {"发票" },  notes = "批量新建发票")
	@RequestMapping(method = RequestMethod.POST, value = "/invoices/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<InvoiceDTO> invoicedtos) {
        invoiceService.createBatch(invoiceMapping.toDomain(invoicedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "获取发票草稿", tags = {"发票" },  notes = "获取发票草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/invoices/getdraft")
    public ResponseEntity<InvoiceDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(invoiceMapping.toDto(invoiceService.getDraft(new Invoice())));
    }

    @PreAuthorize("hasPermission(this.invoiceService.get(#invoice_id),'iBizBusinessCentral-Invoice-Update')")
    @ApiOperation(value = "更新发票", tags = {"发票" },  notes = "更新发票")
	@RequestMapping(method = RequestMethod.PUT, value = "/invoices/{invoice_id}")
    @Transactional
    public ResponseEntity<InvoiceDTO> update(@PathVariable("invoice_id") String invoice_id, @RequestBody InvoiceDTO invoicedto) {
		Invoice domain  = invoiceMapping.toDomain(invoicedto);
        domain .setInvoiceid(invoice_id);
		invoiceService.update(domain );
		InvoiceDTO dto = invoiceMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.invoiceService.getInvoiceByEntities(this.invoiceMapping.toDomain(#invoicedtos)),'iBizBusinessCentral-Invoice-Update')")
    @ApiOperation(value = "批量更新发票", tags = {"发票" },  notes = "批量更新发票")
	@RequestMapping(method = RequestMethod.PUT, value = "/invoices/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<InvoiceDTO> invoicedtos) {
        invoiceService.updateBatch(invoiceMapping.toDomain(invoicedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.invoiceService.get(#invoice_id),'iBizBusinessCentral-Invoice-Remove')")
    @ApiOperation(value = "删除发票", tags = {"发票" },  notes = "删除发票")
	@RequestMapping(method = RequestMethod.DELETE, value = "/invoices/{invoice_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("invoice_id") String invoice_id) {
         return ResponseEntity.status(HttpStatus.OK).body(invoiceService.remove(invoice_id));
    }

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

    @ApiOperation(value = "检查发票", tags = {"发票" },  notes = "检查发票")
	@RequestMapping(method = RequestMethod.POST, value = "/invoices/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody InvoiceDTO invoicedto) {
        return  ResponseEntity.status(HttpStatus.OK).body(invoiceService.checkKey(invoiceMapping.toDomain(invoicedto)));
    }

    @PreAuthorize("hasPermission(this.invoiceMapping.toDomain(#invoicedto),'iBizBusinessCentral-Invoice-Save')")
    @ApiOperation(value = "保存发票", tags = {"发票" },  notes = "保存发票")
	@RequestMapping(method = RequestMethod.POST, value = "/invoices/save")
    public ResponseEntity<Boolean> save(@RequestBody InvoiceDTO invoicedto) {
        return ResponseEntity.status(HttpStatus.OK).body(invoiceService.save(invoiceMapping.toDomain(invoicedto)));
    }

    @PreAuthorize("hasPermission(this.invoiceMapping.toDomain(#invoicedtos),'iBizBusinessCentral-Invoice-Save')")
    @ApiOperation(value = "批量保存发票", tags = {"发票" },  notes = "批量保存发票")
	@RequestMapping(method = RequestMethod.POST, value = "/invoices/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<InvoiceDTO> invoicedtos) {
        invoiceService.saveBatch(invoiceMapping.toDomain(invoicedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.invoiceMapping.toDomain(returnObject.body),'iBizBusinessCentral-Invoice-Get')")
    @ApiOperation(value = "获取发票", tags = {"发票" },  notes = "获取发票")
	@RequestMapping(method = RequestMethod.GET, value = "/invoices/{invoice_id}")
    public ResponseEntity<InvoiceDTO> get(@PathVariable("invoice_id") String invoice_id) {
        Invoice domain = invoiceService.get(invoice_id);
        InvoiceDTO dto = invoiceMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Invoice-Default-all')")
	@ApiOperation(value = "获取DEFAULT", tags = {"发票" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/invoices/fetchdefault")
	public ResponseEntity<List<InvoiceDTO>> fetchDefault(InvoiceSearchContext context) {
        Page<Invoice> domains = invoiceService.searchDefault(context) ;
        List<InvoiceDTO> list = invoiceMapping.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-Invoice-Default-all')")
	@ApiOperation(value = "查询DEFAULT", tags = {"发票" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/invoices/searchdefault")
	public ResponseEntity<Page<InvoiceDTO>> searchDefault(@RequestBody InvoiceSearchContext context) {
        Page<Invoice> domains = invoiceService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(invoiceMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

