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.InvoiceDetail;
import cn.ibizlab.businesscentral.core.finance.service.IInvoiceDetailService;
import cn.ibizlab.businesscentral.core.finance.filter.InvoiceDetailSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"发票产品" })
@RestController("CentralApi-invoicedetail")
@RequestMapping("")
public class InvoiceDetailResource {

    @Autowired
    public IInvoiceDetailService invoicedetailService;

    @Autowired
    @Lazy
    public InvoiceDetailMapping invoicedetailMapping;

    @PreAuthorize("hasPermission(this.invoicedetailMapping.toDomain(#invoicedetaildto),'iBizBusinessCentral-InvoiceDetail-Create')")
    @ApiOperation(value = "新建发票产品", tags = {"发票产品" },  notes = "新建发票产品")
	@RequestMapping(method = RequestMethod.POST, value = "/invoicedetails")
    @Transactional
    public ResponseEntity<InvoiceDetailDTO> create(@RequestBody InvoiceDetailDTO invoicedetaildto) {
        InvoiceDetail domain = invoicedetailMapping.toDomain(invoicedetaildto);
		invoicedetailService.create(domain);
        InvoiceDetailDTO dto = invoicedetailMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.invoicedetailMapping.toDomain(#invoicedetaildtos),'iBizBusinessCentral-InvoiceDetail-Create')")
    @ApiOperation(value = "批量新建发票产品", tags = {"发票产品" },  notes = "批量新建发票产品")
	@RequestMapping(method = RequestMethod.POST, value = "/invoicedetails/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<InvoiceDetailDTO> invoicedetaildtos) {
        invoicedetailService.createBatch(invoicedetailMapping.toDomain(invoicedetaildtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "invoicedetail" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.invoicedetailService.get(#invoicedetail_id),'iBizBusinessCentral-InvoiceDetail-Update')")
    @ApiOperation(value = "更新发票产品", tags = {"发票产品" },  notes = "更新发票产品")
	@RequestMapping(method = RequestMethod.PUT, value = "/invoicedetails/{invoicedetail_id}")
    @Transactional
    public ResponseEntity<InvoiceDetailDTO> update(@PathVariable("invoicedetail_id") String invoicedetail_id, @RequestBody InvoiceDetailDTO invoicedetaildto) {
		InvoiceDetail domain  = invoicedetailMapping.toDomain(invoicedetaildto);
        domain .setInvoicedetailid(invoicedetail_id);
		invoicedetailService.update(domain );
		InvoiceDetailDTO dto = invoicedetailMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.invoicedetailService.getInvoicedetailByEntities(this.invoicedetailMapping.toDomain(#invoicedetaildtos)),'iBizBusinessCentral-InvoiceDetail-Update')")
    @ApiOperation(value = "批量更新发票产品", tags = {"发票产品" },  notes = "批量更新发票产品")
	@RequestMapping(method = RequestMethod.PUT, value = "/invoicedetails/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<InvoiceDetailDTO> invoicedetaildtos) {
        invoicedetailService.updateBatch(invoicedetailMapping.toDomain(invoicedetaildtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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

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

    @PostAuthorize("hasPermission(this.invoicedetailMapping.toDomain(returnObject.body),'iBizBusinessCentral-InvoiceDetail-Get')")
    @ApiOperation(value = "获取发票产品", tags = {"发票产品" },  notes = "获取发票产品")
	@RequestMapping(method = RequestMethod.GET, value = "/invoicedetails/{invoicedetail_id}")
    public ResponseEntity<InvoiceDetailDTO> get(@PathVariable("invoicedetail_id") String invoicedetail_id) {
        InvoiceDetail domain = invoicedetailService.get(invoicedetail_id);
        InvoiceDetailDTO dto = invoicedetailMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取发票产品草稿", tags = {"发票产品" },  notes = "获取发票产品草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/invoicedetails/getdraft")
    public ResponseEntity<InvoiceDetailDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(invoicedetailMapping.toDto(invoicedetailService.getDraft(new InvoiceDetail())));
    }

    @ApiOperation(value = "检查发票产品", tags = {"发票产品" },  notes = "检查发票产品")
	@RequestMapping(method = RequestMethod.POST, value = "/invoicedetails/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody InvoiceDetailDTO invoicedetaildto) {
        return  ResponseEntity.status(HttpStatus.OK).body(invoicedetailService.checkKey(invoicedetailMapping.toDomain(invoicedetaildto)));
    }

    @PreAuthorize("hasPermission(this.invoicedetailMapping.toDomain(#invoicedetaildto),'iBizBusinessCentral-InvoiceDetail-Save')")
    @ApiOperation(value = "保存发票产品", tags = {"发票产品" },  notes = "保存发票产品")
	@RequestMapping(method = RequestMethod.POST, value = "/invoicedetails/save")
    public ResponseEntity<Boolean> save(@RequestBody InvoiceDetailDTO invoicedetaildto) {
        return ResponseEntity.status(HttpStatus.OK).body(invoicedetailService.save(invoicedetailMapping.toDomain(invoicedetaildto)));
    }

    @PreAuthorize("hasPermission(this.invoicedetailMapping.toDomain(#invoicedetaildtos),'iBizBusinessCentral-InvoiceDetail-Save')")
    @ApiOperation(value = "批量保存发票产品", tags = {"发票产品" },  notes = "批量保存发票产品")
	@RequestMapping(method = RequestMethod.POST, value = "/invoicedetails/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<InvoiceDetailDTO> invoicedetaildtos) {
        invoicedetailService.saveBatch(invoicedetailMapping.toDomain(invoicedetaildtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-InvoiceDetail-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-InvoiceDetail-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"发票产品" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/invoicedetails/fetchdefault")
	public ResponseEntity<List<InvoiceDetailDTO>> fetchDefault(InvoiceDetailSearchContext context) {
        Page<InvoiceDetail> domains = invoicedetailService.searchDefault(context) ;
        List<InvoiceDetailDTO> list = invoicedetailMapping.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-InvoiceDetail-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-InvoiceDetail-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"发票产品" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/invoicedetails/searchdefault")
	public ResponseEntity<Page<InvoiceDetailDTO>> searchDefault(@RequestBody InvoiceDetailSearchContext context) {
        Page<InvoiceDetail> domains = invoicedetailService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(invoicedetailMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasPermission(this.invoicedetailMapping.toDomain(#invoicedetaildto),'iBizBusinessCentral-InvoiceDetail-Create')")
    @ApiOperation(value = "根据发票建立发票产品", tags = {"发票产品" },  notes = "根据发票建立发票产品")
	@RequestMapping(method = RequestMethod.POST, value = "/invoices/{invoice_id}/invoicedetails")
    @Transactional
    public ResponseEntity<InvoiceDetailDTO> createByInvoice(@PathVariable("invoice_id") String invoice_id, @RequestBody InvoiceDetailDTO invoicedetaildto) {
        InvoiceDetail domain = invoicedetailMapping.toDomain(invoicedetaildto);
        domain.setInvoiceid(invoice_id);
		invoicedetailService.create(domain);
        InvoiceDetailDTO dto = invoicedetailMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.invoicedetailMapping.toDomain(#invoicedetaildtos),'iBizBusinessCentral-InvoiceDetail-Create')")
    @ApiOperation(value = "根据发票批量建立发票产品", tags = {"发票产品" },  notes = "根据发票批量建立发票产品")
	@RequestMapping(method = RequestMethod.POST, value = "/invoices/{invoice_id}/invoicedetails/batch")
    public ResponseEntity<Boolean> createBatchByInvoice(@PathVariable("invoice_id") String invoice_id, @RequestBody List<InvoiceDetailDTO> invoicedetaildtos) {
        List<InvoiceDetail> domainlist=invoicedetailMapping.toDomain(invoicedetaildtos);
        for(InvoiceDetail domain:domainlist){
            domain.setInvoiceid(invoice_id);
        }
        invoicedetailService.createBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "invoicedetail" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.invoicedetailService.get(#invoicedetail_id),'iBizBusinessCentral-InvoiceDetail-Update')")
    @ApiOperation(value = "根据发票更新发票产品", tags = {"发票产品" },  notes = "根据发票更新发票产品")
	@RequestMapping(method = RequestMethod.PUT, value = "/invoices/{invoice_id}/invoicedetails/{invoicedetail_id}")
    @Transactional
    public ResponseEntity<InvoiceDetailDTO> updateByInvoice(@PathVariable("invoice_id") String invoice_id, @PathVariable("invoicedetail_id") String invoicedetail_id, @RequestBody InvoiceDetailDTO invoicedetaildto) {
        InvoiceDetail domain = invoicedetailMapping.toDomain(invoicedetaildto);
        domain.setInvoiceid(invoice_id);
        domain.setInvoicedetailid(invoicedetail_id);
		invoicedetailService.update(domain);
        InvoiceDetailDTO dto = invoicedetailMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.invoicedetailService.getInvoicedetailByEntities(this.invoicedetailMapping.toDomain(#invoicedetaildtos)),'iBizBusinessCentral-InvoiceDetail-Update')")
    @ApiOperation(value = "根据发票批量更新发票产品", tags = {"发票产品" },  notes = "根据发票批量更新发票产品")
	@RequestMapping(method = RequestMethod.PUT, value = "/invoices/{invoice_id}/invoicedetails/batch")
    public ResponseEntity<Boolean> updateBatchByInvoice(@PathVariable("invoice_id") String invoice_id, @RequestBody List<InvoiceDetailDTO> invoicedetaildtos) {
        List<InvoiceDetail> domainlist=invoicedetailMapping.toDomain(invoicedetaildtos);
        for(InvoiceDetail domain:domainlist){
            domain.setInvoiceid(invoice_id);
        }
        invoicedetailService.updateBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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

    @PreAuthorize("hasPermission(this.invoicedetailService.getInvoicedetailByIds(#ids),'iBizBusinessCentral-InvoiceDetail-Remove')")
    @ApiOperation(value = "根据发票批量删除发票产品", tags = {"发票产品" },  notes = "根据发票批量删除发票产品")
	@RequestMapping(method = RequestMethod.DELETE, value = "/invoices/{invoice_id}/invoicedetails/batch")
    public ResponseEntity<Boolean> removeBatchByInvoice(@RequestBody List<String> ids) {
        invoicedetailService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.invoicedetailMapping.toDomain(returnObject.body),'iBizBusinessCentral-InvoiceDetail-Get')")
    @ApiOperation(value = "根据发票获取发票产品", tags = {"发票产品" },  notes = "根据发票获取发票产品")
	@RequestMapping(method = RequestMethod.GET, value = "/invoices/{invoice_id}/invoicedetails/{invoicedetail_id}")
    public ResponseEntity<InvoiceDetailDTO> getByInvoice(@PathVariable("invoice_id") String invoice_id, @PathVariable("invoicedetail_id") String invoicedetail_id) {
        InvoiceDetail domain = invoicedetailService.get(invoicedetail_id);
        InvoiceDetailDTO dto = invoicedetailMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "根据发票获取发票产品草稿", tags = {"发票产品" },  notes = "根据发票获取发票产品草稿")
    @RequestMapping(method = RequestMethod.GET, value = "/invoices/{invoice_id}/invoicedetails/getdraft")
    public ResponseEntity<InvoiceDetailDTO> getDraftByInvoice(@PathVariable("invoice_id") String invoice_id) {
        InvoiceDetail domain = new InvoiceDetail();
        domain.setInvoiceid(invoice_id);
        return ResponseEntity.status(HttpStatus.OK).body(invoicedetailMapping.toDto(invoicedetailService.getDraft(domain)));
    }

    @ApiOperation(value = "根据发票检查发票产品", tags = {"发票产品" },  notes = "根据发票检查发票产品")
	@RequestMapping(method = RequestMethod.POST, value = "/invoices/{invoice_id}/invoicedetails/checkkey")
    public ResponseEntity<Boolean> checkKeyByInvoice(@PathVariable("invoice_id") String invoice_id, @RequestBody InvoiceDetailDTO invoicedetaildto) {
        return  ResponseEntity.status(HttpStatus.OK).body(invoicedetailService.checkKey(invoicedetailMapping.toDomain(invoicedetaildto)));
    }

    @PreAuthorize("hasPermission(this.invoicedetailMapping.toDomain(#invoicedetaildto),'iBizBusinessCentral-InvoiceDetail-Save')")
    @ApiOperation(value = "根据发票保存发票产品", tags = {"发票产品" },  notes = "根据发票保存发票产品")
	@RequestMapping(method = RequestMethod.POST, value = "/invoices/{invoice_id}/invoicedetails/save")
    public ResponseEntity<Boolean> saveByInvoice(@PathVariable("invoice_id") String invoice_id, @RequestBody InvoiceDetailDTO invoicedetaildto) {
        InvoiceDetail domain = invoicedetailMapping.toDomain(invoicedetaildto);
        domain.setInvoiceid(invoice_id);
        return ResponseEntity.status(HttpStatus.OK).body(invoicedetailService.save(domain));
    }

    @PreAuthorize("hasPermission(this.invoicedetailMapping.toDomain(#invoicedetaildtos),'iBizBusinessCentral-InvoiceDetail-Save')")
    @ApiOperation(value = "根据发票批量保存发票产品", tags = {"发票产品" },  notes = "根据发票批量保存发票产品")
	@RequestMapping(method = RequestMethod.POST, value = "/invoices/{invoice_id}/invoicedetails/savebatch")
    public ResponseEntity<Boolean> saveBatchByInvoice(@PathVariable("invoice_id") String invoice_id, @RequestBody List<InvoiceDetailDTO> invoicedetaildtos) {
        List<InvoiceDetail> domainlist=invoicedetailMapping.toDomain(invoicedetaildtos);
        for(InvoiceDetail domain:domainlist){
             domain.setInvoiceid(invoice_id);
        }
        invoicedetailService.saveBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-InvoiceDetail-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-InvoiceDetail-Get')")
	@ApiOperation(value = "根据发票获取DEFAULT", tags = {"发票产品" } ,notes = "根据发票获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/invoices/{invoice_id}/invoicedetails/fetchdefault")
	public ResponseEntity<List<InvoiceDetailDTO>> fetchInvoiceDetailDefaultByInvoice(@PathVariable("invoice_id") String invoice_id,InvoiceDetailSearchContext context) {
        context.setN_invoiceid_eq(invoice_id);
        Page<InvoiceDetail> domains = invoicedetailService.searchDefault(context) ;
        List<InvoiceDetailDTO> list = invoicedetailMapping.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-InvoiceDetail-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-InvoiceDetail-Get')")
	@ApiOperation(value = "根据发票查询DEFAULT", tags = {"发票产品" } ,notes = "根据发票查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/invoices/{invoice_id}/invoicedetails/searchdefault")
	public ResponseEntity<Page<InvoiceDetailDTO>> searchInvoiceDetailDefaultByInvoice(@PathVariable("invoice_id") String invoice_id, @RequestBody InvoiceDetailSearchContext context) {
        context.setN_invoiceid_eq(invoice_id);
        Page<InvoiceDetail> domains = invoicedetailService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(invoicedetailMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

