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.IBIZTASK;
import cn.ibizlab.core.sample.service.IBIZTASKService;
import cn.ibizlab.core.sample.filter.IBIZTASKSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"任务" })
@RestController("demoapi-ibiztask")
@RequestMapping("${ibiz.rest.basePath.demoapi:/demoapi/}")
public class IBIZTASKResource {

    @Autowired
    public IBIZTASKService ibiztaskService;

    @Autowired
    @Lazy
    public IBIZTASKDTOMapping ibiztaskdtoMapping;


    @ApiOperation(value = "创建Create", tags = {"任务" },  notes = "IBIZTASK-Create")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZTASK-Create-all') or hasPermission(this.ibiztaskdtoMapping.toDomain(#dto),'DemoSys-IBIZTASK-Create')")
    @RequestMapping(method = RequestMethod.POST, value = "ibiztasks")
    public ResponseEntity<IBIZTASKDTO> create
            (@Validated @RequestBody IBIZTASKDTO dto) {
        IBIZTASK domain = ibiztaskdtoMapping.toDomain(dto);
        ibiztaskService.create(domain);
        IBIZTASK rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibiztaskdtoMapping.toDto(rt));
    }

    @ApiOperation(value = "获取Get", tags = {"任务" },  notes = "IBIZTASK-Get")
    @PostAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZTASK-Get-all') or hasPermission(this.ibiztaskdtoMapping.toDomain(returnObject.body),'DemoSys-IBIZTASK-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibiztasks/{ibiztaskid}")
    public ResponseEntity<IBIZTASKDTO> getByIbiztaskid
            (@PathVariable("ibiztaskid") String ibiztaskid) {
        IBIZTASK rt = ibiztaskService.get(ibiztaskid);
        return ResponseEntity.status(HttpStatus.OK).body(ibiztaskdtoMapping.toDto(rt));
    }

    @ApiOperation(value = "删除Remove", tags = {"任务" },  notes = "IBIZTASK-Remove")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZTASK-Remove-all') or hasPermission(this.ibiztaskService.get(#ibiztaskid),'DemoSys-IBIZTASK-Remove')")
    @RequestMapping(method = RequestMethod.DELETE, value = "ibiztasks/{ibiztaskid}")
    public ResponseEntity<Boolean> removeByIbiztaskid
            (@PathVariable("ibiztaskid") String ibiztaskid) {
        Boolean rt = ibiztaskService.remove(ibiztaskid);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "更新Update", tags = {"任务" },  notes = "IBIZTASK-Update")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZTASK-Update-all') or hasPermission(this.ibiztaskService.get(#ibiztaskid),'DemoSys-IBIZTASK-Update')")
    @VersionCheck(entity = "ibiztask" , versionfield = "updateDate")
    @RequestMapping(method = RequestMethod.PUT, value = "ibiztasks/{ibiztaskid}")
    public ResponseEntity<IBIZTASKDTO> updateByIbiztaskid
            (@PathVariable("ibiztaskid") String ibiztaskid, @Validated @RequestBody IBIZTASKDTO dto) {
        IBIZTASK domain = ibiztaskdtoMapping.toDomain(dto);
        domain.setIbiztaskid(ibiztaskid);
        ibiztaskService.update(domain);
        IBIZTASK rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibiztaskdtoMapping.toDto(rt));
    }

    @ApiOperation(value = "校验CheckKey", tags = {"任务" },  notes = "IBIZTASK-CheckKey")
    @RequestMapping(method = RequestMethod.POST, value = "ibiztasks/checkkey")
    public ResponseEntity<Integer> checkKey
            (@Validated @RequestBody IBIZTASKDTO dto) {
        IBIZTASK domain = ibiztaskdtoMapping.toDomain(dto);
        Integer rt = ibiztaskService.checkKey(domain);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "草稿GetDraft", tags = {"任务" },  notes = "IBIZTASK-GetDraft")
    @RequestMapping(method = RequestMethod.GET, value = "ibiztasks/getdraft")
    public ResponseEntity<IBIZTASKDTO> getDraft
            (IBIZTASKDTO dto) {
        IBIZTASK domain = ibiztaskdtoMapping.toDomain(dto);
        IBIZTASK rt = ibiztaskService.getDraft(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ibiztaskdtoMapping.toDto(rt));
    }

    @ApiOperation(value = "保存Save", tags = {"任务" },  notes = "IBIZTASK-Save")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZTASK-Save-all') or hasPermission(this.ibiztaskdtoMapping.toDomain(#dto),'DemoSys-IBIZTASK-Save')")
    @RequestMapping(method = RequestMethod.POST, value = "ibiztasks/save")
    public ResponseEntity<IBIZTASKDTO> save
            (@Validated @RequestBody IBIZTASKDTO dto) {
        IBIZTASK domain = ibiztaskdtoMapping.toDomain(dto);
        ibiztaskService.save(domain);
        IBIZTASK rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibiztaskdtoMapping.toDto(rt));
    }

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

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZTASK-Update-all')")
    @ApiOperation(value = "批量更新任务", tags = {"任务" },  notes = "批量更新任务")
	@RequestMapping(method = RequestMethod.PUT, value = "ibiztasks/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<IBIZTASKDTO> dtos) {
        ibiztaskService.updateBatch(ibiztaskdtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZTASK-Save-all')")
    @ApiOperation(value = "批量保存任务", tags = {"任务" },  notes = "批量保存任务")
	@RequestMapping(method = RequestMethod.POST, value = "ibiztasks/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<IBIZTASKDTO> dtos) {
        ibiztaskService.saveBatch(ibiztaskdtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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