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.IBIZSupplier;
import cn.ibizlab.core.sample.service.IBIZSupplierService;
import cn.ibizlab.core.sample.filter.IBIZSupplierSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"供货商" })
@RestController("demoapi-ibizsupplier")
@RequestMapping("${ibiz.rest.basePath.demoapi:/demoapi/}")
public class IBIZSupplierResource {

    @Autowired
    public IBIZSupplierService ibizSupplierService;

    @Autowired
    @Lazy
    public IBIZSupplierDTOMapping ibizSupplierDtoMapping;


    @ApiOperation(value = "创建Create", tags = {"供货商" },  notes = "IBIZSupplier-Create")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZSupplier-Create-all') or hasPermission(this.ibizSupplierDtoMapping.toDomain(#dto),'DemoSys-IBIZSupplier-Create')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizsuppliers")
    public ResponseEntity<IBIZSupplierDTO> create
            (@Validated @RequestBody IBIZSupplierDTO dto) {
        IBIZSupplier domain = ibizSupplierDtoMapping.toDomain(dto);
        ibizSupplierService.create(domain);
        IBIZSupplier rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizSupplierDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "获取Get", tags = {"供货商" },  notes = "IBIZSupplier-Get")
    @PostAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZSupplier-Get-all') or hasPermission(this.ibizSupplierDtoMapping.toDomain(returnObject.body),'DemoSys-IBIZSupplier-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizsuppliers/{supplierId}")
    public ResponseEntity<IBIZSupplierDTO> getBySupplierId
            (@PathVariable("supplierId") String supplierId) {
        IBIZSupplier rt = ibizSupplierService.get(supplierId);
        return ResponseEntity.status(HttpStatus.OK).body(ibizSupplierDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "删除Remove", tags = {"供货商" },  notes = "IBIZSupplier-Remove")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZSupplier-Remove-all') or hasPermission(this.ibizSupplierService.get(#supplierId),'DemoSys-IBIZSupplier-Remove')")
    @RequestMapping(method = RequestMethod.DELETE, value = "ibizsuppliers/{supplierId}")
    public ResponseEntity<Boolean> removeBySupplierId
            (@PathVariable("supplierId") String supplierId) {
        Boolean rt = ibizSupplierService.remove(supplierId);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "更新Update", tags = {"供货商" },  notes = "IBIZSupplier-Update")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZSupplier-Update-all') or hasPermission(this.ibizSupplierService.get(#supplierId),'DemoSys-IBIZSupplier-Update')")
    @VersionCheck(entity = "ibizsupplier" , versionfield = "updateTime")
    @RequestMapping(method = RequestMethod.PUT, value = "ibizsuppliers/{supplierId}")
    public ResponseEntity<IBIZSupplierDTO> updateBySupplierId
            (@PathVariable("supplierId") String supplierId, @Validated @RequestBody IBIZSupplierDTO dto) {
        IBIZSupplier domain = ibizSupplierDtoMapping.toDomain(dto);
        domain.setSupplierId(supplierId);
        ibizSupplierService.update(domain);
        IBIZSupplier rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizSupplierDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "校验CheckKey", tags = {"供货商" },  notes = "IBIZSupplier-CheckKey")
    @RequestMapping(method = RequestMethod.POST, value = "ibizsuppliers/checkkey")
    public ResponseEntity<Integer> checkKey
            (@Validated @RequestBody IBIZSupplierDTO dto) {
        IBIZSupplier domain = ibizSupplierDtoMapping.toDomain(dto);
        Integer rt = ibizSupplierService.checkKey(domain);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "草稿GetDraft", tags = {"供货商" },  notes = "IBIZSupplier-GetDraft")
    @RequestMapping(method = RequestMethod.GET, value = "ibizsuppliers/getdraft")
    public ResponseEntity<IBIZSupplierDTO> getDraft
            (IBIZSupplierDTO dto) {
        IBIZSupplier domain = ibizSupplierDtoMapping.toDomain(dto);
        IBIZSupplier rt = ibizSupplierService.getDraft(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ibizSupplierDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "保存Save", tags = {"供货商" },  notes = "IBIZSupplier-Save")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZSupplier-Save-all') or hasPermission(this.ibizSupplierDtoMapping.toDomain(#dto),'DemoSys-IBIZSupplier-Save')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizsuppliers/save")
    public ResponseEntity<IBIZSupplierDTO> save
            (@Validated @RequestBody IBIZSupplierDTO dto) {
        IBIZSupplier domain = ibizSupplierDtoMapping.toDomain(dto);
        ibizSupplierService.save(domain);
        IBIZSupplier rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizSupplierDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "查询FetchDefault", tags = {"供货商" },  notes = "IBIZSupplier-FetchDefault")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZSupplier-searchDefault-all','DemoSys-IBIZSupplier-Get-all') or hasPermission(#dto,'DemoSys-IBIZSupplier-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizsuppliers/fetchdefault")
    public ResponseEntity<List<IBIZSupplierDTO>> fetchDefault
            (IBIZSupplierSearchContext dto) {
        Page<IBIZSupplier> domains = ibizSupplierService.searchDefault(dto) ;
        List<IBIZSupplierDTO> list = ibizSupplierDtoMapping.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-IBIZSupplier-Create-all')")
    @ApiOperation(value = "批量新建供货商", tags = {"供货商" },  notes = "批量新建供货商")
	@RequestMapping(method = RequestMethod.POST, value = "ibizsuppliers/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<IBIZSupplierDTO> dtos) {
        ibizSupplierService.createBatch(ibizSupplierDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZSupplier-Update-all')")
    @ApiOperation(value = "批量更新供货商", tags = {"供货商" },  notes = "批量更新供货商")
	@RequestMapping(method = RequestMethod.PUT, value = "ibizsuppliers/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<IBIZSupplierDTO> dtos) {
        ibizSupplierService.updateBatch(ibizSupplierDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZSupplier-Save-all')")
    @ApiOperation(value = "批量保存供货商", tags = {"供货商" },  notes = "批量保存供货商")
	@RequestMapping(method = RequestMethod.POST, value = "ibizsuppliers/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<IBIZSupplierDTO> dtos) {
        ibizSupplierService.saveBatch(ibizSupplierDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZSupplier-Save-all')")
    @ApiOperation(value = "批量导入供货商", tags = {"供货商" },  notes = "批量导入供货商")
	@RequestMapping(method = RequestMethod.POST, value = "ibizsuppliers/import")
    public ResponseEntity<Map> importData(@RequestParam(value = "config") String config ,@RequestBody List<IBIZSupplierDTO> 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<IBIZSupplier> list=ibizSupplierDtoMapping.toDomain(dtos);
            List<IBIZSupplier> rtList=new ArrayList();
            list.forEach(item->{
                if(ibizSupplierService.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-IBIZSupplier-Remove-all')")
    @ApiOperation(value = "批量删除供货商", tags = {"供货商" },  notes = "批量删除供货商")
	@RequestMapping(method = RequestMethod.DELETE, value = {"ibizsuppliers","/ibizsuppliers/batch"})
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        ibizSupplierService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }
}
