package cn.ibizlab.demoapi.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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
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.util.ObjectUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.validation.annotation.Validated;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.demoapi.dto.*;
import cn.ibizlab.demoapi.mapping.*;
import cn.ibizlab.core.sample.domain.IBIZUNIProduct;
import cn.ibizlab.core.sample.service.IBIZUNIProductService;
import cn.ibizlab.core.sample.filter.IBIZUNIProductSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"统一产品（索引主实体）" })
@RestController("demoapi-ibizuniproduct")
@RequestMapping("${ibiz.rest.basePath.demoapi:/demoapi/}")
public class IBIZUNIProductResource {

    @Autowired
    public IBIZUNIProductService ibizuniProductService;

    @Autowired
    @Lazy
    public IBIZUNIProductDTOMapping ibizuniProductDtoMapping;


    @ApiOperation(value = "创建Create", tags = {"统一产品（索引主实体）" },  notes = "IBIZUNIProduct-Create")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZUNIProduct-Create-all') or hasPermission(this.ibizuniProductDtoMapping.toDomain(#dto),'DemoSys-IBIZUNIProduct-Create')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizuniproducts")
    public ResponseEntity<IBIZUNIProductDTO> create
            (@Validated @RequestBody IBIZUNIProductDTO dto) {
        IBIZUNIProduct domain = ibizuniProductDtoMapping.toDomain(dto);
        ibizuniProductService.create(domain);
        IBIZUNIProduct rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizuniProductDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "获取Get", tags = {"统一产品（索引主实体）" },  notes = "IBIZUNIProduct-Get")
    @PostAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZUNIProduct-Get-all') or hasPermission(this.ibizuniProductDtoMapping.toDomain(returnObject.body),'DemoSys-IBIZUNIProduct-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizuniproducts/{ibizuniProductId}")
    public ResponseEntity<IBIZUNIProductDTO> getByIbizuniProductId
            (@PathVariable("ibizuniProductId") String ibizuniProductId) {
        IBIZUNIProduct rt = ibizuniProductService.get(ibizuniProductId);
        return ResponseEntity.status(HttpStatus.OK).body(ibizuniProductDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "删除Remove", tags = {"统一产品（索引主实体）" },  notes = "IBIZUNIProduct-Remove")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZUNIProduct-Remove-all') or hasPermission(this.ibizuniProductService.get(#ibizuniProductId),'DemoSys-IBIZUNIProduct-Remove')")
    @RequestMapping(method = RequestMethod.DELETE, value = "ibizuniproducts/{ibizuniProductId}")
    public ResponseEntity<Boolean> removeByIbizuniProductId
            (@PathVariable("ibizuniProductId") String ibizuniProductId) {
        Boolean rt = ibizuniProductService.remove(ibizuniProductId);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "更新Update", tags = {"统一产品（索引主实体）" },  notes = "IBIZUNIProduct-Update")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZUNIProduct-Update-all') or hasPermission(this.ibizuniProductService.get(#ibizuniProductId),'DemoSys-IBIZUNIProduct-Update')")
    @VersionCheck(entity = "ibizuniproduct" , versionfield = "updateDate")
    @RequestMapping(method = RequestMethod.PUT, value = "ibizuniproducts/{ibizuniProductId}")
    public ResponseEntity<IBIZUNIProductDTO> updateByIbizuniProductId
            (@PathVariable("ibizuniProductId") String ibizuniProductId, @Validated @RequestBody IBIZUNIProductDTO dto) {
        IBIZUNIProduct domain = ibizuniProductDtoMapping.toDomain(dto);
        domain.setIbizuniProductId(ibizuniProductId);
        ibizuniProductService.update(domain);
        IBIZUNIProduct rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizuniProductDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "校验CheckKey", tags = {"统一产品（索引主实体）" },  notes = "IBIZUNIProduct-CheckKey")
    @RequestMapping(method = RequestMethod.POST, value = "ibizuniproducts/checkkey")
    public ResponseEntity<Integer> checkKey
            (@Validated @RequestBody IBIZUNIProductDTO dto) {
        IBIZUNIProduct domain = ibizuniProductDtoMapping.toDomain(dto);
        Integer rt = ibizuniProductService.checkKey(domain);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "草稿GetDraft", tags = {"统一产品（索引主实体）" },  notes = "IBIZUNIProduct-GetDraft")
    @RequestMapping(method = RequestMethod.GET, value = "ibizuniproducts/getdraft")
    public ResponseEntity<IBIZUNIProductDTO> getDraft
            (IBIZUNIProductDTO dto) {
        IBIZUNIProduct domain = ibizuniProductDtoMapping.toDomain(dto);
        IBIZUNIProduct rt = ibizuniProductService.getDraft(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ibizuniProductDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "保存Save", tags = {"统一产品（索引主实体）" },  notes = "IBIZUNIProduct-Save")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZUNIProduct-Save-all') or hasPermission(this.ibizuniProductDtoMapping.toDomain(#dto),'DemoSys-IBIZUNIProduct-Save')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizuniproducts/save")
    public ResponseEntity<IBIZUNIProductDTO> save
            (@Validated @RequestBody IBIZUNIProductDTO dto) {
        IBIZUNIProduct domain = ibizuniProductDtoMapping.toDomain(dto);
        ibizuniProductService.save(domain);
        IBIZUNIProduct rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizuniProductDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "查询FetchDefault", tags = {"统一产品（索引主实体）" },  notes = "IBIZUNIProduct-FetchDefault")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZUNIProduct-searchDefault-all','DemoSys-IBIZUNIProduct-Get-all') or hasPermission(#dto,'DemoSys-IBIZUNIProduct-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizuniproducts/fetchdefault")
    public ResponseEntity<List<IBIZUNIProductDTO>> fetchDefault
            (IBIZUNIProductSearchContext dto) {
        Page<IBIZUNIProduct> domains = ibizuniProductService.searchDefault(dto) ;
        List<IBIZUNIProductDTO> list = ibizuniProductDtoMapping.toDto(domains.getContent());
            return ResponseEntity.status(HttpStatus.OK)
            .header("x-page", String.valueOf(dto.getPageable().getPageNumber()))
            .header("x-per-page", String.valueOf(dto.getPageable().getPageSize()))
            .header("x-total", String.valueOf(domains.getTotalElements()))
            .body(list);
    }


    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZUNIProduct-Create-all')")
    @ApiOperation(value = "批量新建统一产品（索引主实体）", tags = {"统一产品（索引主实体）" },  notes = "批量新建统一产品（索引主实体）")
	@RequestMapping(method = RequestMethod.POST, value = "ibizuniproducts/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<IBIZUNIProductDTO> dtos) {
        ibizuniProductService.createBatch(ibizuniProductDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZUNIProduct-Update-all')")
    @ApiOperation(value = "批量更新统一产品（索引主实体）", tags = {"统一产品（索引主实体）" },  notes = "批量更新统一产品（索引主实体）")
	@RequestMapping(method = RequestMethod.PUT, value = "ibizuniproducts/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<IBIZUNIProductDTO> dtos) {
        ibizuniProductService.updateBatch(ibizuniProductDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZUNIProduct-Save-all')")
    @ApiOperation(value = "批量保存统一产品（索引主实体）", tags = {"统一产品（索引主实体）" },  notes = "批量保存统一产品（索引主实体）")
	@RequestMapping(method = RequestMethod.POST, value = "ibizuniproducts/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<IBIZUNIProductDTO> dtos) {
        ibizuniProductService.saveBatch(ibizuniProductDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZUNIProduct-Save-all')")
    @ApiOperation(value = "批量导入统一产品（索引主实体）", tags = {"统一产品（索引主实体）" },  notes = "批量导入统一产品（索引主实体）")
	@RequestMapping(method = RequestMethod.POST, value = "ibizuniproducts/import")
    public ResponseEntity<Map> importData(@RequestParam(value = "config") String config ,@RequestBody List<IBIZUNIProductDTO> dtos) {
        Map rs=new HashMap();
        if(ObjectUtils.isEmpty(dtos)){
            rs.put("rst", 1);
            rs.put("msg", "未传入内容");
            return ResponseEntity.status(HttpStatus.NO_CONTENT).body(rs);
        }
        else{
            List<IBIZUNIProduct> list=ibizuniProductDtoMapping.toDomain(dtos);
            List<IBIZUNIProduct> rtList=new ArrayList();
            list.forEach(item->{
                if(ibizuniProductService.save(item))
                    rtList.add(item);
            });
            rs.put("rst", 0);
            rs.put("data",rtList);
        }
        return  ResponseEntity.status(HttpStatus.OK).body(rs);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZUNIProduct-Remove-all')")
    @ApiOperation(value = "批量删除统一产品（索引主实体）", tags = {"统一产品（索引主实体）" },  notes = "批量删除统一产品（索引主实体）")
	@RequestMapping(method = RequestMethod.DELETE, value = {"ibizuniproducts","/ibizuniproducts/batch"})
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        ibizuniProductService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }
}
