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.Appointment;
import cn.ibizlab.businesscentral.core.base.service.IAppointmentService;
import cn.ibizlab.businesscentral.core.base.filter.AppointmentSearchContext;

@Slf4j
@Api(tags = {"约会" })
@RestController("CentralApi-appointment")
@RequestMapping("")
public class AppointmentResource {

    @Autowired
    public IAppointmentService appointmentService;

    @Autowired
    @Lazy
    public AppointmentMapping appointmentMapping;

    @PreAuthorize("hasPermission(this.appointmentMapping.toDomain(#appointmentdto),'iBizBusinessCentral-Appointment-Create')")
    @ApiOperation(value = "新建约会", tags = {"约会" },  notes = "新建约会")
	@RequestMapping(method = RequestMethod.POST, value = "/appointments")
    @Transactional
    public ResponseEntity<AppointmentDTO> create(@RequestBody AppointmentDTO appointmentdto) {
        Appointment domain = appointmentMapping.toDomain(appointmentdto);
		appointmentService.create(domain);
        AppointmentDTO dto = appointmentMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.appointmentMapping.toDomain(#appointmentdtos),'iBizBusinessCentral-Appointment-Create')")
    @ApiOperation(value = "批量新建约会", tags = {"约会" },  notes = "批量新建约会")
	@RequestMapping(method = RequestMethod.POST, value = "/appointments/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<AppointmentDTO> appointmentdtos) {
        appointmentService.createBatch(appointmentMapping.toDomain(appointmentdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "获取约会草稿", tags = {"约会" },  notes = "获取约会草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/appointments/getdraft")
    public ResponseEntity<AppointmentDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(appointmentMapping.toDto(appointmentService.getDraft(new Appointment())));
    }

    @PreAuthorize("hasPermission(this.appointmentService.get(#appointment_id),'iBizBusinessCentral-Appointment-Remove')")
    @ApiOperation(value = "删除约会", tags = {"约会" },  notes = "删除约会")
	@RequestMapping(method = RequestMethod.DELETE, value = "/appointments/{appointment_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("appointment_id") String appointment_id) {
         return ResponseEntity.status(HttpStatus.OK).body(appointmentService.remove(appointment_id));
    }

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

    @PostAuthorize("hasPermission(this.appointmentMapping.toDomain(returnObject.body),'iBizBusinessCentral-Appointment-Get')")
    @ApiOperation(value = "获取约会", tags = {"约会" },  notes = "获取约会")
	@RequestMapping(method = RequestMethod.GET, value = "/appointments/{appointment_id}")
    public ResponseEntity<AppointmentDTO> get(@PathVariable("appointment_id") String appointment_id) {
        Appointment domain = appointmentService.get(appointment_id);
        AppointmentDTO dto = appointmentMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "检查约会", tags = {"约会" },  notes = "检查约会")
	@RequestMapping(method = RequestMethod.POST, value = "/appointments/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody AppointmentDTO appointmentdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(appointmentService.checkKey(appointmentMapping.toDomain(appointmentdto)));
    }

    @PreAuthorize("hasPermission(this.appointmentMapping.toDomain(#appointmentdto),'iBizBusinessCentral-Appointment-Save')")
    @ApiOperation(value = "保存约会", tags = {"约会" },  notes = "保存约会")
	@RequestMapping(method = RequestMethod.POST, value = "/appointments/save")
    public ResponseEntity<Boolean> save(@RequestBody AppointmentDTO appointmentdto) {
        return ResponseEntity.status(HttpStatus.OK).body(appointmentService.save(appointmentMapping.toDomain(appointmentdto)));
    }

    @PreAuthorize("hasPermission(this.appointmentMapping.toDomain(#appointmentdtos),'iBizBusinessCentral-Appointment-Save')")
    @ApiOperation(value = "批量保存约会", tags = {"约会" },  notes = "批量保存约会")
	@RequestMapping(method = RequestMethod.POST, value = "/appointments/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<AppointmentDTO> appointmentdtos) {
        appointmentService.saveBatch(appointmentMapping.toDomain(appointmentdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.appointmentService.get(#appointment_id),'iBizBusinessCentral-Appointment-Update')")
    @ApiOperation(value = "更新约会", tags = {"约会" },  notes = "更新约会")
	@RequestMapping(method = RequestMethod.PUT, value = "/appointments/{appointment_id}")
    @Transactional
    public ResponseEntity<AppointmentDTO> update(@PathVariable("appointment_id") String appointment_id, @RequestBody AppointmentDTO appointmentdto) {
		Appointment domain  = appointmentMapping.toDomain(appointmentdto);
        domain .setActivityid(appointment_id);
		appointmentService.update(domain );
		AppointmentDTO dto = appointmentMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.appointmentService.getAppointmentByEntities(this.appointmentMapping.toDomain(#appointmentdtos)),'iBizBusinessCentral-Appointment-Update')")
    @ApiOperation(value = "批量更新约会", tags = {"约会" },  notes = "批量更新约会")
	@RequestMapping(method = RequestMethod.PUT, value = "/appointments/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<AppointmentDTO> appointmentdtos) {
        appointmentService.updateBatch(appointmentMapping.toDomain(appointmentdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Appointment-Default-all')")
	@ApiOperation(value = "获取DEFAULT", tags = {"约会" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/appointments/fetchdefault")
	public ResponseEntity<List<AppointmentDTO>> fetchDefault(AppointmentSearchContext context) {
        Page<Appointment> domains = appointmentService.searchDefault(context) ;
        List<AppointmentDTO> list = appointmentMapping.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-Appointment-Default-all')")
	@ApiOperation(value = "查询DEFAULT", tags = {"约会" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/appointments/searchdefault")
	public ResponseEntity<Page<AppointmentDTO>> searchDefault(@RequestBody AppointmentSearchContext context) {
        Page<Appointment> domains = appointmentService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(appointmentMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

