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.Email;
import cn.ibizlab.businesscentral.core.base.service.IEmailService;
import cn.ibizlab.businesscentral.core.base.filter.EmailSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"电子邮件" })
@RestController("CentralApi-email")
@RequestMapping("")
public class EmailResource {

    @Autowired
    public IEmailService emailService;

    @Autowired
    @Lazy
    public EmailMapping emailMapping;

    @PreAuthorize("hasPermission(this.emailMapping.toDomain(#emaildto),'iBizBusinessCentral-Email-Create')")
    @ApiOperation(value = "新建电子邮件", tags = {"电子邮件" },  notes = "新建电子邮件")
	@RequestMapping(method = RequestMethod.POST, value = "/emails")
    @Transactional
    public ResponseEntity<EmailDTO> create(@RequestBody EmailDTO emaildto) {
        Email domain = emailMapping.toDomain(emaildto);
		emailService.create(domain);
        EmailDTO dto = emailMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.emailMapping.toDomain(#emaildtos),'iBizBusinessCentral-Email-Create')")
    @ApiOperation(value = "批量新建电子邮件", tags = {"电子邮件" },  notes = "批量新建电子邮件")
	@RequestMapping(method = RequestMethod.POST, value = "/emails/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<EmailDTO> emaildtos) {
        emailService.createBatch(emailMapping.toDomain(emaildtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "email" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.emailService.get(#email_id),'iBizBusinessCentral-Email-Update')")
    @ApiOperation(value = "更新电子邮件", tags = {"电子邮件" },  notes = "更新电子邮件")
	@RequestMapping(method = RequestMethod.PUT, value = "/emails/{email_id}")
    @Transactional
    public ResponseEntity<EmailDTO> update(@PathVariable("email_id") String email_id, @RequestBody EmailDTO emaildto) {
		Email domain  = emailMapping.toDomain(emaildto);
        domain .setActivityid(email_id);
		emailService.update(domain );
		EmailDTO dto = emailMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.emailService.getEmailByEntities(this.emailMapping.toDomain(#emaildtos)),'iBizBusinessCentral-Email-Update')")
    @ApiOperation(value = "批量更新电子邮件", tags = {"电子邮件" },  notes = "批量更新电子邮件")
	@RequestMapping(method = RequestMethod.PUT, value = "/emails/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<EmailDTO> emaildtos) {
        emailService.updateBatch(emailMapping.toDomain(emaildtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.emailService.get(#email_id),'iBizBusinessCentral-Email-Remove')")
    @ApiOperation(value = "删除电子邮件", tags = {"电子邮件" },  notes = "删除电子邮件")
	@RequestMapping(method = RequestMethod.DELETE, value = "/emails/{email_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("email_id") String email_id) {
         return ResponseEntity.status(HttpStatus.OK).body(emailService.remove(email_id));
    }

    @PreAuthorize("hasPermission(this.emailService.getEmailByIds(#ids),'iBizBusinessCentral-Email-Remove')")
    @ApiOperation(value = "批量删除电子邮件", tags = {"电子邮件" },  notes = "批量删除电子邮件")
	@RequestMapping(method = RequestMethod.DELETE, value = "/emails/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        emailService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.emailMapping.toDomain(returnObject.body),'iBizBusinessCentral-Email-Get')")
    @ApiOperation(value = "获取电子邮件", tags = {"电子邮件" },  notes = "获取电子邮件")
	@RequestMapping(method = RequestMethod.GET, value = "/emails/{email_id}")
    public ResponseEntity<EmailDTO> get(@PathVariable("email_id") String email_id) {
        Email domain = emailService.get(email_id);
        EmailDTO dto = emailMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取电子邮件草稿", tags = {"电子邮件" },  notes = "获取电子邮件草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/emails/getdraft")
    public ResponseEntity<EmailDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(emailMapping.toDto(emailService.getDraft(new Email())));
    }

    @ApiOperation(value = "检查电子邮件", tags = {"电子邮件" },  notes = "检查电子邮件")
	@RequestMapping(method = RequestMethod.POST, value = "/emails/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody EmailDTO emaildto) {
        return  ResponseEntity.status(HttpStatus.OK).body(emailService.checkKey(emailMapping.toDomain(emaildto)));
    }

    @PreAuthorize("hasPermission(this.emailMapping.toDomain(#emaildto),'iBizBusinessCentral-Email-Save')")
    @ApiOperation(value = "保存电子邮件", tags = {"电子邮件" },  notes = "保存电子邮件")
	@RequestMapping(method = RequestMethod.POST, value = "/emails/save")
    public ResponseEntity<Boolean> save(@RequestBody EmailDTO emaildto) {
        return ResponseEntity.status(HttpStatus.OK).body(emailService.save(emailMapping.toDomain(emaildto)));
    }

    @PreAuthorize("hasPermission(this.emailMapping.toDomain(#emaildtos),'iBizBusinessCentral-Email-Save')")
    @ApiOperation(value = "批量保存电子邮件", tags = {"电子邮件" },  notes = "批量保存电子邮件")
	@RequestMapping(method = RequestMethod.POST, value = "/emails/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<EmailDTO> emaildtos) {
        emailService.saveBatch(emailMapping.toDomain(emaildtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Email-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Email-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"电子邮件" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/emails/fetchdefault")
	public ResponseEntity<List<EmailDTO>> fetchDefault(EmailSearchContext context) {
        Page<Email> domains = emailService.searchDefault(context) ;
        List<EmailDTO> list = emailMapping.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-Email-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Email-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"电子邮件" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/emails/searchdefault")
	public ResponseEntity<Page<EmailDTO>> searchDefault(@RequestBody EmailSearchContext context) {
        Page<Email> domains = emailService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(emailMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

