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.product.domain.Product;
import cn.ibizlab.businesscentral.core.product.service.IProductService;
import cn.ibizlab.businesscentral.core.product.filter.ProductSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"产品" })
@RestController("CentralApi-product")
@RequestMapping("")
public class ProductResource {

    @Autowired
    public IProductService productService;

    @Autowired
    @Lazy
    public ProductMapping productMapping;

    @PreAuthorize("hasPermission(this.productMapping.toDomain(#productdto),'iBizBusinessCentral-Product-Create')")
    @ApiOperation(value = "新建产品", tags = {"产品" },  notes = "新建产品")
	@RequestMapping(method = RequestMethod.POST, value = "/products")
    @Transactional
    public ResponseEntity<ProductDTO> create(@RequestBody ProductDTO productdto) {
        Product domain = productMapping.toDomain(productdto);
		productService.create(domain);
        ProductDTO dto = productMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.productMapping.toDomain(#productdtos),'iBizBusinessCentral-Product-Create')")
    @ApiOperation(value = "批量新建产品", tags = {"产品" },  notes = "批量新建产品")
	@RequestMapping(method = RequestMethod.POST, value = "/products/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<ProductDTO> productdtos) {
        productService.createBatch(productMapping.toDomain(productdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "product" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.productService.get(#product_id),'iBizBusinessCentral-Product-Update')")
    @ApiOperation(value = "更新产品", tags = {"产品" },  notes = "更新产品")
	@RequestMapping(method = RequestMethod.PUT, value = "/products/{product_id}")
    @Transactional
    public ResponseEntity<ProductDTO> update(@PathVariable("product_id") String product_id, @RequestBody ProductDTO productdto) {
		Product domain  = productMapping.toDomain(productdto);
        domain .setProductid(product_id);
		productService.update(domain );
		ProductDTO dto = productMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.productService.getProductByEntities(this.productMapping.toDomain(#productdtos)),'iBizBusinessCentral-Product-Update')")
    @ApiOperation(value = "批量更新产品", tags = {"产品" },  notes = "批量更新产品")
	@RequestMapping(method = RequestMethod.PUT, value = "/products/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<ProductDTO> productdtos) {
        productService.updateBatch(productMapping.toDomain(productdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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

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

    @PostAuthorize("hasPermission(this.productMapping.toDomain(returnObject.body),'iBizBusinessCentral-Product-Get')")
    @ApiOperation(value = "获取产品", tags = {"产品" },  notes = "获取产品")
	@RequestMapping(method = RequestMethod.GET, value = "/products/{product_id}")
    public ResponseEntity<ProductDTO> get(@PathVariable("product_id") String product_id) {
        Product domain = productService.get(product_id);
        ProductDTO dto = productMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取产品草稿", tags = {"产品" },  notes = "获取产品草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/products/getdraft")
    public ResponseEntity<ProductDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(productMapping.toDto(productService.getDraft(new Product())));
    }

    @ApiOperation(value = "检查产品", tags = {"产品" },  notes = "检查产品")
	@RequestMapping(method = RequestMethod.POST, value = "/products/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody ProductDTO productdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(productService.checkKey(productMapping.toDomain(productdto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Product-Publish-all')")
    @ApiOperation(value = "发布", tags = {"产品" },  notes = "发布")
	@RequestMapping(method = RequestMethod.POST, value = "/products/{product_id}/publish")
    @Transactional
    public ResponseEntity<ProductDTO> publish(@PathVariable("product_id") String product_id, @RequestBody ProductDTO productdto) {
        Product domain = productMapping.toDomain(productdto);
domain.setProductid(product_id);
        domain = productService.publish(domain);
        productdto = productMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(productdto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Product-Revise-all')")
    @ApiOperation(value = "修订", tags = {"产品" },  notes = "修订")
	@RequestMapping(method = RequestMethod.POST, value = "/products/{product_id}/revise")
    @Transactional
    public ResponseEntity<ProductDTO> revise(@PathVariable("product_id") String product_id, @RequestBody ProductDTO productdto) {
        Product domain = productMapping.toDomain(productdto);
domain.setProductid(product_id);
        domain = productService.revise(domain);
        productdto = productMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(productdto);
    }

    @PreAuthorize("hasPermission(this.productMapping.toDomain(#productdto),'iBizBusinessCentral-Product-Save')")
    @ApiOperation(value = "保存产品", tags = {"产品" },  notes = "保存产品")
	@RequestMapping(method = RequestMethod.POST, value = "/products/save")
    public ResponseEntity<Boolean> save(@RequestBody ProductDTO productdto) {
        return ResponseEntity.status(HttpStatus.OK).body(productService.save(productMapping.toDomain(productdto)));
    }

    @PreAuthorize("hasPermission(this.productMapping.toDomain(#productdtos),'iBizBusinessCentral-Product-Save')")
    @ApiOperation(value = "批量保存产品", tags = {"产品" },  notes = "批量保存产品")
	@RequestMapping(method = RequestMethod.POST, value = "/products/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<ProductDTO> productdtos) {
        productService.saveBatch(productMapping.toDomain(productdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Product-Stop-all')")
    @ApiOperation(value = "停用", tags = {"产品" },  notes = "停用")
	@RequestMapping(method = RequestMethod.POST, value = "/products/{product_id}/stop")
    @Transactional
    public ResponseEntity<ProductDTO> stop(@PathVariable("product_id") String product_id, @RequestBody ProductDTO productdto) {
        Product domain = productMapping.toDomain(productdto);
domain.setProductid(product_id);
        domain = productService.stop(domain);
        productdto = productMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(productdto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Product-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Product-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"产品" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/products/fetchdefault")
	public ResponseEntity<List<ProductDTO>> fetchDefault(ProductSearchContext context) {
        Page<Product> domains = productService.searchDefault(context) ;
        List<ProductDTO> list = productMapping.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-Product-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Product-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"产品" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/products/searchdefault")
	public ResponseEntity<Page<ProductDTO>> searchDefault(@RequestBody ProductSearchContext context) {
        Page<Product> domains = productService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(productMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Product-searchEffective-all') and hasPermission(#context,'iBizBusinessCentral-Product-Get')")
	@ApiOperation(value = "获取有效", tags = {"产品" } ,notes = "获取有效")
    @RequestMapping(method= RequestMethod.GET , value="/products/fetcheffective")
	public ResponseEntity<List<ProductDTO>> fetchEffective(ProductSearchContext context) {
        Page<Product> domains = productService.searchEffective(context) ;
        List<ProductDTO> list = productMapping.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-Product-searchEffective-all') and hasPermission(#context,'iBizBusinessCentral-Product-Get')")
	@ApiOperation(value = "查询有效", tags = {"产品" } ,notes = "查询有效")
    @RequestMapping(method= RequestMethod.POST , value="/products/searcheffective")
	public ResponseEntity<Page<ProductDTO>> searchEffective(@RequestBody ProductSearchContext context) {
        Page<Product> domains = productService.searchEffective(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(productMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Product-searchRevise-all') and hasPermission(#context,'iBizBusinessCentral-Product-Get')")
	@ApiOperation(value = "获取正在修订", tags = {"产品" } ,notes = "获取正在修订")
    @RequestMapping(method= RequestMethod.GET , value="/products/fetchrevise")
	public ResponseEntity<List<ProductDTO>> fetchRevise(ProductSearchContext context) {
        Page<Product> domains = productService.searchRevise(context) ;
        List<ProductDTO> list = productMapping.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-Product-searchRevise-all') and hasPermission(#context,'iBizBusinessCentral-Product-Get')")
	@ApiOperation(value = "查询正在修订", tags = {"产品" } ,notes = "查询正在修订")
    @RequestMapping(method= RequestMethod.POST , value="/products/searchrevise")
	public ResponseEntity<Page<ProductDTO>> searchRevise(@RequestBody ProductSearchContext context) {
        Page<Product> domains = productService.searchRevise(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(productMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Product-searchStop-all') and hasPermission(#context,'iBizBusinessCentral-Product-Get')")
	@ApiOperation(value = "获取已停用", tags = {"产品" } ,notes = "获取已停用")
    @RequestMapping(method= RequestMethod.GET , value="/products/fetchstop")
	public ResponseEntity<List<ProductDTO>> fetchStop(ProductSearchContext context) {
        Page<Product> domains = productService.searchStop(context) ;
        List<ProductDTO> list = productMapping.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-Product-searchStop-all') and hasPermission(#context,'iBizBusinessCentral-Product-Get')")
	@ApiOperation(value = "查询已停用", tags = {"产品" } ,notes = "查询已停用")
    @RequestMapping(method= RequestMethod.POST , value="/products/searchstop")
	public ResponseEntity<Page<ProductDTO>> searchStop(@RequestBody ProductSearchContext context) {
        Page<Product> domains = productService.searchStop(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(productMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

