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.IBIZAccount;
import cn.ibizlab.core.sample.service.IBIZAccountService;
import cn.ibizlab.core.sample.filter.IBIZAccountSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"账户" })
@RestController("demoapi-ibizaccount")
@RequestMapping("${ibiz.rest.basePath.demoapi:/demoapi/}")
public class IBIZAccountResource {

    @Autowired
    public IBIZAccountService ibizAccountService;

    @Autowired
    @Lazy
    public IBIZAccountDTOMapping ibizAccountDtoMapping;


    @ApiOperation(value = "创建Create", tags = {"账户" },  notes = "IBIZAccount-Create")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZAccount-Create-all') or hasPermission(this.ibizAccountDtoMapping.toDomain(#dto),'DemoSys-IBIZAccount-Create')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizaccounts")
    public ResponseEntity<IBIZAccountDTO> create
            (@Validated @RequestBody IBIZAccountDTO dto) {
        IBIZAccount domain = ibizAccountDtoMapping.toDomain(dto);
        ibizAccountService.create(domain);
        IBIZAccount rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizAccountDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "获取Get", tags = {"账户" },  notes = "IBIZAccount-Get")
    @PostAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZAccount-Get-all') or hasPermission(this.ibizAccountDtoMapping.toDomain(returnObject.body),'DemoSys-IBIZAccount-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizaccounts/{ibizAccountId}")
    public ResponseEntity<IBIZAccountDTO> getByIbizAccountId
            (@PathVariable("ibizAccountId") String ibizAccountId) {
        IBIZAccount rt = ibizAccountService.get(ibizAccountId);
        return ResponseEntity.status(HttpStatus.OK).body(ibizAccountDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "删除Remove", tags = {"账户" },  notes = "IBIZAccount-Remove")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZAccount-Remove-all') or hasPermission(this.ibizAccountService.get(#ibizAccountId),'DemoSys-IBIZAccount-Remove')")
    @RequestMapping(method = RequestMethod.DELETE, value = "ibizaccounts/{ibizAccountId}")
    public ResponseEntity<Boolean> removeByIbizAccountId
            (@PathVariable("ibizAccountId") String ibizAccountId) {
        Boolean rt = ibizAccountService.remove(ibizAccountId);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "更新Update", tags = {"账户" },  notes = "IBIZAccount-Update")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZAccount-Update-all') or hasPermission(this.ibizAccountService.get(#ibizAccountId),'DemoSys-IBIZAccount-Update')")
    @VersionCheck(entity = "ibizaccount" , versionfield = "updateDate")
    @RequestMapping(method = RequestMethod.PUT, value = "ibizaccounts/{ibizAccountId}")
    public ResponseEntity<IBIZAccountDTO> updateByIbizAccountId
            (@PathVariable("ibizAccountId") String ibizAccountId, @Validated @RequestBody IBIZAccountDTO dto) {
        IBIZAccount domain = ibizAccountDtoMapping.toDomain(dto);
        domain.setIbizAccountId(ibizAccountId);
        ibizAccountService.update(domain);
        IBIZAccount rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizAccountDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "校验CheckKey", tags = {"账户" },  notes = "IBIZAccount-CheckKey")
    @RequestMapping(method = RequestMethod.POST, value = "ibizaccounts/checkkey")
    public ResponseEntity<Integer> checkKey
            (@Validated @RequestBody IBIZAccountDTO dto) {
        IBIZAccount domain = ibizAccountDtoMapping.toDomain(dto);
        Integer rt = ibizAccountService.checkKey(domain);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "草稿GetDraft", tags = {"账户" },  notes = "IBIZAccount-GetDraft")
    @RequestMapping(method = RequestMethod.GET, value = "ibizaccounts/getdraft")
    public ResponseEntity<IBIZAccountDTO> getDraft
            (IBIZAccountDTO dto) {
        IBIZAccount domain = ibizAccountDtoMapping.toDomain(dto);
        IBIZAccount rt = ibizAccountService.getDraft(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ibizAccountDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "保存Save", tags = {"账户" },  notes = "IBIZAccount-Save")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZAccount-Save-all') or hasPermission(this.ibizAccountDtoMapping.toDomain(#dto),'DemoSys-IBIZAccount-Save')")
    @RequestMapping(method = RequestMethod.POST, value = "ibizaccounts/save")
    public ResponseEntity<IBIZAccountDTO> save
            (@Validated @RequestBody IBIZAccountDTO dto) {
        IBIZAccount domain = ibizAccountDtoMapping.toDomain(dto);
        ibizAccountService.save(domain);
        IBIZAccount rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizAccountDtoMapping.toDto(rt));
    }

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

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZAccount-Update-all')")
    @ApiOperation(value = "批量更新账户", tags = {"账户" },  notes = "批量更新账户")
	@RequestMapping(method = RequestMethod.PUT, value = "ibizaccounts/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<IBIZAccountDTO> dtos) {
        ibizAccountService.updateBatch(ibizAccountDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','demo-IBIZAccount-Save-all')")
    @ApiOperation(value = "批量保存账户", tags = {"账户" },  notes = "批量保存账户")
	@RequestMapping(method = RequestMethod.POST, value = "ibizaccounts/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<IBIZAccountDTO> dtos) {
        ibizAccountService.saveBatch(ibizAccountDtoMapping.toDomain(dtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

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