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.Contact;
import cn.ibizlab.businesscentral.core.base.service.IContactService;
import cn.ibizlab.businesscentral.core.base.filter.ContactSearchContext;

@Slf4j
@Api(tags = {"联系人" })
@RestController("CentralApi-contact")
@RequestMapping("")
public class ContactResource {

    @Autowired
    public IContactService contactService;

    @Autowired
    @Lazy
    public ContactMapping contactMapping;

    @ApiOperation(value = "检查联系人", tags = {"联系人" },  notes = "检查联系人")
	@RequestMapping(method = RequestMethod.POST, value = "/contacts/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody ContactDTO contactdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(contactService.checkKey(contactMapping.toDomain(contactdto)));
    }

    @PreAuthorize("hasPermission(this.contactService.get(#contact_id),'iBizBusinessCentral-Contact-Remove')")
    @ApiOperation(value = "删除联系人", tags = {"联系人" },  notes = "删除联系人")
	@RequestMapping(method = RequestMethod.DELETE, value = "/contacts/{contact_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("contact_id") String contact_id) {
         return ResponseEntity.status(HttpStatus.OK).body(contactService.remove(contact_id));
    }

    @PreAuthorize("hasPermission(this.contactService.getContactByIds(#ids),'iBizBusinessCentral-Contact-Remove')")
    @ApiOperation(value = "批量删除联系人", tags = {"联系人" },  notes = "批量删除联系人")
	@RequestMapping(method = RequestMethod.DELETE, value = "/contacts/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        contactService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.contactMapping.toDomain(returnObject.body),'iBizBusinessCentral-Contact-Get')")
    @ApiOperation(value = "获取联系人", tags = {"联系人" },  notes = "获取联系人")
	@RequestMapping(method = RequestMethod.GET, value = "/contacts/{contact_id}")
    public ResponseEntity<ContactDTO> get(@PathVariable("contact_id") String contact_id) {
        Contact domain = contactService.get(contact_id);
        ContactDTO dto = contactMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.contactMapping.toDomain(#contactdto),'iBizBusinessCentral-Contact-Save')")
    @ApiOperation(value = "保存联系人", tags = {"联系人" },  notes = "保存联系人")
	@RequestMapping(method = RequestMethod.POST, value = "/contacts/save")
    public ResponseEntity<Boolean> save(@RequestBody ContactDTO contactdto) {
        return ResponseEntity.status(HttpStatus.OK).body(contactService.save(contactMapping.toDomain(contactdto)));
    }

    @PreAuthorize("hasPermission(this.contactMapping.toDomain(#contactdtos),'iBizBusinessCentral-Contact-Save')")
    @ApiOperation(value = "批量保存联系人", tags = {"联系人" },  notes = "批量保存联系人")
	@RequestMapping(method = RequestMethod.POST, value = "/contacts/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<ContactDTO> contactdtos) {
        contactService.saveBatch(contactMapping.toDomain(contactdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.contactService.get(#contact_id),'iBizBusinessCentral-Contact-Update')")
    @ApiOperation(value = "更新联系人", tags = {"联系人" },  notes = "更新联系人")
	@RequestMapping(method = RequestMethod.PUT, value = "/contacts/{contact_id}")
    @Transactional
    public ResponseEntity<ContactDTO> update(@PathVariable("contact_id") String contact_id, @RequestBody ContactDTO contactdto) {
		Contact domain  = contactMapping.toDomain(contactdto);
        domain .setContactid(contact_id);
		contactService.update(domain );
		ContactDTO dto = contactMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.contactService.getContactByEntities(this.contactMapping.toDomain(#contactdtos)),'iBizBusinessCentral-Contact-Update')")
    @ApiOperation(value = "批量更新联系人", tags = {"联系人" },  notes = "批量更新联系人")
	@RequestMapping(method = RequestMethod.PUT, value = "/contacts/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<ContactDTO> contactdtos) {
        contactService.updateBatch(contactMapping.toDomain(contactdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "获取联系人草稿", tags = {"联系人" },  notes = "获取联系人草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/contacts/getdraft")
    public ResponseEntity<ContactDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(contactMapping.toDto(contactService.getDraft(new Contact())));
    }

    @PreAuthorize("hasPermission(this.contactMapping.toDomain(#contactdto),'iBizBusinessCentral-Contact-Create')")
    @ApiOperation(value = "新建联系人", tags = {"联系人" },  notes = "新建联系人")
	@RequestMapping(method = RequestMethod.POST, value = "/contacts")
    @Transactional
    public ResponseEntity<ContactDTO> create(@RequestBody ContactDTO contactdto) {
        Contact domain = contactMapping.toDomain(contactdto);
		contactService.create(domain);
        ContactDTO dto = contactMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.contactMapping.toDomain(#contactdtos),'iBizBusinessCentral-Contact-Create')")
    @ApiOperation(value = "批量新建联系人", tags = {"联系人" },  notes = "批量新建联系人")
	@RequestMapping(method = RequestMethod.POST, value = "/contacts/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<ContactDTO> contactdtos) {
        contactService.createBatch(contactMapping.toDomain(contactdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Contact-Default-all')")
	@ApiOperation(value = "获取DEFAULT", tags = {"联系人" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/contacts/fetchdefault")
	public ResponseEntity<List<ContactDTO>> fetchDefault(ContactSearchContext context) {
        Page<Contact> domains = contactService.searchDefault(context) ;
        List<ContactDTO> list = contactMapping.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-Contact-Default-all')")
	@ApiOperation(value = "查询DEFAULT", tags = {"联系人" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/contacts/searchdefault")
	public ResponseEntity<Page<ContactDTO>> searchDefault(@RequestBody ContactSearchContext context) {
        Page<Contact> domains = contactService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(contactMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

