package cn.ibizlab.businesscentral.centralapi.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 javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.transaction.annotation.Transactional;
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.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.base.domain.Account;
import cn.ibizlab.businesscentral.core.base.service.IAccountService;
import cn.ibizlab.businesscentral.core.base.filter.AccountSearchContext;

@Slf4j
@Api(tags = {"客户" })
@RestController("CentralApi-account")
@RequestMapping("")
public class AccountResource {

    @Autowired
    public IAccountService accountService;

    @Autowired
    @Lazy
    public AccountMapping accountMapping;

    @PreAuthorize("hasPermission(this.accountMapping.toDomain(#accountdto),'iBizBusinessCentral-Account-Create')")
    @ApiOperation(value = "新建客户", tags = {"客户" },  notes = "新建客户")
	@RequestMapping(method = RequestMethod.POST, value = "/accounts")
    @Transactional
    public ResponseEntity<AccountDTO> create(@RequestBody AccountDTO accountdto) {
        Account domain = accountMapping.toDomain(accountdto);
		accountService.create(domain);
        AccountDTO dto = accountMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.accountMapping.toDomain(#accountdtos),'iBizBusinessCentral-Account-Create')")
    @ApiOperation(value = "批量新建客户", tags = {"客户" },  notes = "批量新建客户")
	@RequestMapping(method = RequestMethod.POST, value = "/accounts/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<AccountDTO> accountdtos) {
        accountService.createBatch(accountMapping.toDomain(accountdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.accountService.get(#account_id),'iBizBusinessCentral-Account-Update')")
    @ApiOperation(value = "更新客户", tags = {"客户" },  notes = "更新客户")
	@RequestMapping(method = RequestMethod.PUT, value = "/accounts/{account_id}")
    @Transactional
    public ResponseEntity<AccountDTO> update(@PathVariable("account_id") String account_id, @RequestBody AccountDTO accountdto) {
		Account domain  = accountMapping.toDomain(accountdto);
        domain .setAccountid(account_id);
		accountService.update(domain );
		AccountDTO dto = accountMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.accountService.getAccountByEntities(this.accountMapping.toDomain(#accountdtos)),'iBizBusinessCentral-Account-Update')")
    @ApiOperation(value = "批量更新客户", tags = {"客户" },  notes = "批量更新客户")
	@RequestMapping(method = RequestMethod.PUT, value = "/accounts/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<AccountDTO> accountdtos) {
        accountService.updateBatch(accountMapping.toDomain(accountdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.accountService.get(#account_id),'iBizBusinessCentral-Account-Remove')")
    @ApiOperation(value = "删除客户", tags = {"客户" },  notes = "删除客户")
	@RequestMapping(method = RequestMethod.DELETE, value = "/accounts/{account_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("account_id") String account_id) {
         return ResponseEntity.status(HttpStatus.OK).body(accountService.remove(account_id));
    }

    @PreAuthorize("hasPermission(this.accountService.getAccountByIds(#ids),'iBizBusinessCentral-Account-Remove')")
    @ApiOperation(value = "批量删除客户", tags = {"客户" },  notes = "批量删除客户")
	@RequestMapping(method = RequestMethod.DELETE, value = "/accounts/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        accountService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.accountMapping.toDomain(#accountdto),'iBizBusinessCentral-Account-Save')")
    @ApiOperation(value = "保存客户", tags = {"客户" },  notes = "保存客户")
	@RequestMapping(method = RequestMethod.POST, value = "/accounts/save")
    public ResponseEntity<Boolean> save(@RequestBody AccountDTO accountdto) {
        return ResponseEntity.status(HttpStatus.OK).body(accountService.save(accountMapping.toDomain(accountdto)));
    }

    @PreAuthorize("hasPermission(this.accountMapping.toDomain(#accountdtos),'iBizBusinessCentral-Account-Save')")
    @ApiOperation(value = "批量保存客户", tags = {"客户" },  notes = "批量保存客户")
	@RequestMapping(method = RequestMethod.POST, value = "/accounts/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<AccountDTO> accountdtos) {
        accountService.saveBatch(accountMapping.toDomain(accountdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "检查客户", tags = {"客户" },  notes = "检查客户")
	@RequestMapping(method = RequestMethod.POST, value = "/accounts/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody AccountDTO accountdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(accountService.checkKey(accountMapping.toDomain(accountdto)));
    }

    @PostAuthorize("hasPermission(this.accountMapping.toDomain(returnObject.body),'iBizBusinessCentral-Account-Get')")
    @ApiOperation(value = "获取客户", tags = {"客户" },  notes = "获取客户")
	@RequestMapping(method = RequestMethod.GET, value = "/accounts/{account_id}")
    public ResponseEntity<AccountDTO> get(@PathVariable("account_id") String account_id) {
        Account domain = accountService.get(account_id);
        AccountDTO dto = accountMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取客户草稿", tags = {"客户" },  notes = "获取客户草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/accounts/getdraft")
    public ResponseEntity<AccountDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(accountMapping.toDto(accountService.getDraft(new Account())));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-Default-all')")
	@ApiOperation(value = "获取DEFAULT", tags = {"客户" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/accounts/fetchdefault")
	public ResponseEntity<List<AccountDTO>> fetchDefault(AccountSearchContext context) {
        Page<Account> domains = accountService.searchDefault(context) ;
        List<AccountDTO> list = accountMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Account-Default-all')")
	@ApiOperation(value = "查询DEFAULT", tags = {"客户" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/accounts/searchdefault")
	public ResponseEntity<Page<AccountDTO>> searchDefault(@RequestBody AccountSearchContext context) {
        Page<Account> domains = accountService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(accountMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

