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.IBIZCustomer;
import cn.ibizlab.core.sample.service.IBIZCustomerService;
import cn.ibizlab.core.sample.filter.IBIZCustomerSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

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

    @Autowired
    public IBIZCustomerService ibizCustomerService;

    @Autowired
    @Lazy
    public IBIZCustomerDTOMapping ibizCustomerDtoMapping;


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

    @ApiOperation(value = "获取Get", tags = {"客户" },  notes = "IBIZCustomer-Get")
    @PostAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZCustomer-Get-all') or hasPermission(this.ibizCustomerDtoMapping.toDomain(returnObject.body),'DemoSys-IBIZCustomer-Get')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizcustomers/{ibizCustomerId}")
    public ResponseEntity<IBIZCustomerDTO> getByIbizCustomerId
            (@PathVariable("ibizCustomerId") String ibizCustomerId) {
        IBIZCustomer rt = ibizCustomerService.get(ibizCustomerId);
        return ResponseEntity.status(HttpStatus.OK).body(ibizCustomerDtoMapping.toDto(rt));
    }

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

    @ApiOperation(value = "更新Update", tags = {"客户" },  notes = "IBIZCustomer-Update")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZCustomer-Update-all') or hasPermission(this.ibizCustomerService.get(#ibizCustomerId),'DemoSys-IBIZCustomer-Update')")
    @VersionCheck(entity = "ibizcustomer" , versionfield = "updateDate")
    @RequestMapping(method = RequestMethod.PUT, value = "ibizcustomers/{ibizCustomerId}")
    public ResponseEntity<IBIZCustomerDTO> updateByIbizCustomerId
            (@PathVariable("ibizCustomerId") String ibizCustomerId, @Validated @RequestBody IBIZCustomerDTO dto) {
        IBIZCustomer domain = ibizCustomerDtoMapping.toDomain(dto);
        domain.setIbizCustomerId(ibizCustomerId);
        ibizCustomerService.update(domain);
        IBIZCustomer rt = domain;
        return ResponseEntity.status(HttpStatus.OK).body(ibizCustomerDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "校验CheckKey", tags = {"客户" },  notes = "IBIZCustomer-CheckKey")
    @RequestMapping(method = RequestMethod.POST, value = "ibizcustomers/checkkey")
    public ResponseEntity<Integer> checkKey
            (@Validated @RequestBody IBIZCustomerDTO dto) {
        IBIZCustomer domain = ibizCustomerDtoMapping.toDomain(dto);
        Integer rt = ibizCustomerService.checkKey(domain);
        return ResponseEntity.status(HttpStatus.OK).body(rt);
    }

    @ApiOperation(value = "草稿GetDraft", tags = {"客户" },  notes = "IBIZCustomer-GetDraft")
    @RequestMapping(method = RequestMethod.GET, value = "ibizcustomers/getdraft")
    public ResponseEntity<IBIZCustomerDTO> getDraft
            (IBIZCustomerDTO dto) {
        IBIZCustomer domain = ibizCustomerDtoMapping.toDomain(dto);
        IBIZCustomer rt = ibizCustomerService.getDraft(domain);
        return ResponseEntity.status(HttpStatus.OK).body(ibizCustomerDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "GetDynaCarousel", tags = {"客户" },  notes = "IBIZCustomer-GetDynaCarousel")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZCustomer-GetDynaCarousel-all') or hasPermission(this.ibizCustomerService.get(#ibizCustomerId),'DemoSys-IBIZCustomer-GetDynaCarousel')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizcustomers/{ibizCustomerId}/getdynacarousel")
    public ResponseEntity<IBIZCustomerDTO> getDynaCarouselByIbizCustomerId
            (@PathVariable("ibizCustomerId") String ibizCustomerId) {
        IBIZCustomer rt = ibizCustomerService.getDynaCarousel(ibizCustomerId);
        return ResponseEntity.status(HttpStatus.OK).body(ibizCustomerDtoMapping.toDto(rt));
    }

    @ApiOperation(value = "GetDynaImg", tags = {"客户" },  notes = "IBIZCustomer-GetDynaImg")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','DemoSys-IBIZCustomer-GetDynaImg-all') or hasPermission(this.ibizCustomerService.get(#ibizCustomerId),'DemoSys-IBIZCustomer-GetDynaImg')")
    @RequestMapping(method = RequestMethod.GET, value = "ibizcustomers/{ibizCustomerId}/getdynaimg")
    public ResponseEntity<IBIZCustomerDTO> getDynaImgByIbizCustomerId
            (@PathVariable("ibizCustomerId") String ibizCustomerId) {
        IBIZCustomer rt = ibizCustomerService.getDynaImg(ibizCustomerId);
        return ResponseEntity.status(HttpStatus.OK).body(ibizCustomerDtoMapping.toDto(rt));
    }

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

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

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

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

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