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.SalesOrder;
import cn.ibizlab.businesscentral.core.sales.service.ISalesOrderService;
import cn.ibizlab.businesscentral.core.sales.filter.SalesOrderSearchContext;

@Slf4j
@Api(tags = {"订单" })
@RestController("CentralApi-salesorder")
@RequestMapping("")
public class SalesOrderResource {

    @Autowired
    public ISalesOrderService salesorderService;

    @Autowired
    @Lazy
    public SalesOrderMapping salesorderMapping;

    @ApiOperation(value = "检查订单", tags = {"订单" },  notes = "检查订单")
	@RequestMapping(method = RequestMethod.POST, value = "/salesorders/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody SalesOrderDTO salesorderdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(salesorderService.checkKey(salesorderMapping.toDomain(salesorderdto)));
    }

    @ApiOperation(value = "获取订单草稿", tags = {"订单" },  notes = "获取订单草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/salesorders/getdraft")
    public ResponseEntity<SalesOrderDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(salesorderMapping.toDto(salesorderService.getDraft(new SalesOrder())));
    }

    @PostAuthorize("hasPermission(this.salesorderMapping.toDomain(returnObject.body),'iBizBusinessCentral-SalesOrder-Get')")
    @ApiOperation(value = "获取订单", tags = {"订单" },  notes = "获取订单")
	@RequestMapping(method = RequestMethod.GET, value = "/salesorders/{salesorder_id}")
    public ResponseEntity<SalesOrderDTO> get(@PathVariable("salesorder_id") String salesorder_id) {
        SalesOrder domain = salesorderService.get(salesorder_id);
        SalesOrderDTO dto = salesorderMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.salesorderMapping.toDomain(#salesorderdto),'iBizBusinessCentral-SalesOrder-Save')")
    @ApiOperation(value = "保存订单", tags = {"订单" },  notes = "保存订单")
	@RequestMapping(method = RequestMethod.POST, value = "/salesorders/save")
    public ResponseEntity<Boolean> save(@RequestBody SalesOrderDTO salesorderdto) {
        return ResponseEntity.status(HttpStatus.OK).body(salesorderService.save(salesorderMapping.toDomain(salesorderdto)));
    }

    @PreAuthorize("hasPermission(this.salesorderMapping.toDomain(#salesorderdtos),'iBizBusinessCentral-SalesOrder-Save')")
    @ApiOperation(value = "批量保存订单", tags = {"订单" },  notes = "批量保存订单")
	@RequestMapping(method = RequestMethod.POST, value = "/salesorders/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<SalesOrderDTO> salesorderdtos) {
        salesorderService.saveBatch(salesorderMapping.toDomain(salesorderdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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

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

    @PreAuthorize("hasPermission(this.salesorderService.get(#salesorder_id),'iBizBusinessCentral-SalesOrder-Update')")
    @ApiOperation(value = "更新订单", tags = {"订单" },  notes = "更新订单")
	@RequestMapping(method = RequestMethod.PUT, value = "/salesorders/{salesorder_id}")
    @Transactional
    public ResponseEntity<SalesOrderDTO> update(@PathVariable("salesorder_id") String salesorder_id, @RequestBody SalesOrderDTO salesorderdto) {
		SalesOrder domain  = salesorderMapping.toDomain(salesorderdto);
        domain .setSalesorderid(salesorder_id);
		salesorderService.update(domain );
		SalesOrderDTO dto = salesorderMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.salesorderService.getSalesorderByEntities(this.salesorderMapping.toDomain(#salesorderdtos)),'iBizBusinessCentral-SalesOrder-Update')")
    @ApiOperation(value = "批量更新订单", tags = {"订单" },  notes = "批量更新订单")
	@RequestMapping(method = RequestMethod.PUT, value = "/salesorders/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<SalesOrderDTO> salesorderdtos) {
        salesorderService.updateBatch(salesorderMapping.toDomain(salesorderdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.salesorderMapping.toDomain(#salesorderdto),'iBizBusinessCentral-SalesOrder-Create')")
    @ApiOperation(value = "新建订单", tags = {"订单" },  notes = "新建订单")
	@RequestMapping(method = RequestMethod.POST, value = "/salesorders")
    @Transactional
    public ResponseEntity<SalesOrderDTO> create(@RequestBody SalesOrderDTO salesorderdto) {
        SalesOrder domain = salesorderMapping.toDomain(salesorderdto);
		salesorderService.create(domain);
        SalesOrderDTO dto = salesorderMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.salesorderMapping.toDomain(#salesorderdtos),'iBizBusinessCentral-SalesOrder-Create')")
    @ApiOperation(value = "批量新建订单", tags = {"订单" },  notes = "批量新建订单")
	@RequestMapping(method = RequestMethod.POST, value = "/salesorders/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<SalesOrderDTO> salesorderdtos) {
        salesorderService.createBatch(salesorderMapping.toDomain(salesorderdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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

