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.MicroComponent;
import cn.ibizlab.core.sample.service.MicroComponentService;
import cn.ibizlab.core.sample.filter.MicroComponentSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"微组件" })
@RestController("demoapi-microcomponent")
@RequestMapping("${ibiz.rest.basePath.demoapi:/demoapi/}")
public class MicroComponentResource {

    @Autowired
    public MicroComponentService microComponentService;

    @Autowired
    @Lazy
    public MicroComponentDTOMapping microComponentDtoMapping;


    @ApiOperation(value = "创建Create", tags = {"微组件" },  notes = "MicroComponent-Create")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-MicroComponent-Create-all') or hasPermission(this.microComponentDtoMapping.toDomain(#dto),'DemoSys-MicroComponent-Create')")
    @RequestMapping(method = RequestMethod.POST, value = "microcomponents")
    public ResponseEntity<MicroComponentDTO> create
            (@Validated @RequestBody MicroComponentDTO dto) {
        MicroComponent domain = microComponentDtoMapping.toDomain(dto);
        microComponentService.create(domain);
        MicroComponent rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(microComponentDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "获取Get", tags = {"微组件" },  notes = "MicroComponent-Get")
    @PostAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-MicroComponent-Get-all') or hasPermission(this.microComponentDtoMapping.toDomain(returnObject.body),'DemoSys-MicroComponent-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "microcomponents/{microComponentId}")
    public ResponseEntity<MicroComponentDTO> getByMicroComponentId
            (@PathVariable("microComponentId") String microComponentId) {
        MicroComponent rt = microComponentService.get(microComponentId);
        return ResponseEntity.status(HttpStatus.OK).body(microComponentDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "删除Remove", tags = {"微组件" },  notes = "MicroComponent-Remove")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-MicroComponent-Remove-all') or hasPermission(this.microComponentService.get(#microComponentId),'DemoSys-MicroComponent-Remove')")
    @RequestMapping(method = RequestMethod.DELETE, value = "microcomponents/{microComponentId}")
    public ResponseEntity<Boolean> removeByMicroComponentId
            (@PathVariable("microComponentId") String microComponentId) {
        Boolean rt = microComponentService.remove(microComponentId);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "更新Update", tags = {"微组件" },  notes = "MicroComponent-Update")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-MicroComponent-Update-all') or hasPermission(this.microComponentService.get(#microComponentId),'DemoSys-MicroComponent-Update')")
    @VersionCheck(entity = "microcomponent" , versionfield = "updateDate")
    @RequestMapping(method = RequestMethod.PUT, value = "microcomponents/{microComponentId}")
    public ResponseEntity<MicroComponentDTO> updateByMicroComponentId
            (@PathVariable("microComponentId") String microComponentId, @Validated @RequestBody MicroComponentDTO dto) {
        MicroComponent domain = microComponentDtoMapping.toDomain(dto);
        domain.setMicroComponentId(microComponentId);
        microComponentService.update(domain);
        MicroComponent rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(microComponentDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "校验CheckKey", tags = {"微组件" },  notes = "MicroComponent-CheckKey")
    @RequestMapping(method = RequestMethod.POST, value = "microcomponents/checkkey")
    public ResponseEntity<Integer> checkKey
            (@Validated @RequestBody MicroComponentDTO dto) {
        MicroComponent domain = microComponentDtoMapping.toDomain(dto);
        Integer rt = microComponentService.checkKey(domain);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "草稿GetDraft", tags = {"微组件" },  notes = "MicroComponent-GetDraft")
    @RequestMapping(method = RequestMethod.GET, value = "microcomponents/getdraft")
    public ResponseEntity<MicroComponentDTO> getDraft
            (MicroComponentDTO dto) {
        MicroComponent domain = microComponentDtoMapping.toDomain(dto);
        MicroComponent rt = microComponentService.getDraft(domain);
        return ResponseEntity.status(HttpStatus.OK).body(microComponentDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "保存Save", tags = {"微组件" },  notes = "MicroComponent-Save")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-MicroComponent-Save-all') or hasPermission(this.microComponentDtoMapping.toDomain(#dto),'DemoSys-MicroComponent-Save')")
    @RequestMapping(method = RequestMethod.POST, value = "microcomponents/save")
    public ResponseEntity<MicroComponentDTO> save
            (@Validated @RequestBody MicroComponentDTO dto) {
        MicroComponent domain = microComponentDtoMapping.toDomain(dto);
        microComponentService.save(domain);
        MicroComponent rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(microComponentDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "查询FetchDefault", tags = {"微组件" },  notes = "MicroComponent-FetchDefault")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-MicroComponent-searchDefault-all','DemoSys-MicroComponent-Get-all') or hasPermission(#dto,'DemoSys-MicroComponent-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "microcomponents/fetchdefault")
    public ResponseEntity<List<MicroComponentDTO>> fetchDefault
            (MicroComponentSearchContext dto) {
        Page<MicroComponent> domains = microComponentService.searchDefault(dto) ;
        List<MicroComponentDTO> list = microComponentDtoMapping.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-MicroComponent-Create-all')")
    @ApiOperation(value = "批量新建微组件", tags = {"微组件" },  notes = "批量新建微组件")
	@RequestMapping(method = RequestMethod.POST, value = "microcomponents/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<MicroComponentDTO> dtos) {
        microComponentService.createBatch(microComponentDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-MicroComponent-Update-all')")
    @ApiOperation(value = "批量更新微组件", tags = {"微组件" },  notes = "批量更新微组件")
	@RequestMapping(method = RequestMethod.PUT, value = "microcomponents/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<MicroComponentDTO> dtos) {
        microComponentService.updateBatch(microComponentDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-MicroComponent-Save-all')")
    @ApiOperation(value = "批量保存微组件", tags = {"微组件" },  notes = "批量保存微组件")
	@RequestMapping(method = RequestMethod.POST, value = "microcomponents/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<MicroComponentDTO> dtos) {
        microComponentService.saveBatch(microComponentDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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