package cn.ibizlab.assetmanagement.assetapi.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.assetmanagement.assetapi.dto.*;
import cn.ibizlab.assetmanagement.assetapi.mapping.*;
import cn.ibizlab.assetmanagement.core.workorder.domain.EAMWorkOrder;
import cn.ibizlab.assetmanagement.core.workorder.service.IEAMWorkOrderService;
import cn.ibizlab.assetmanagement.core.workorder.filter.EAMWorkOrderSearchContext;
import cn.ibizlab.assetmanagement.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"工单" })
@RestController("AssetApi-eamworkorder")
@RequestMapping("")
public class EAMWorkOrderResource {

    @Autowired
    public IEAMWorkOrderService eamworkorderService;

    @Autowired
    @Lazy
    public EAMWorkOrderMapping eamworkorderMapping;

    @PreAuthorize("hasPermission(this.eamworkorderMapping.toDomain(#eamworkorderdto),'iBizAssetManagement-EAMWorkOrder-Create')")
    @ApiOperation(value = "新建工单", tags = {"工单" },  notes = "新建工单")
	@RequestMapping(method = RequestMethod.POST, value = "/eamworkorders")
    @Transactional
    public ResponseEntity<EAMWorkOrderDTO> create(@RequestBody EAMWorkOrderDTO eamworkorderdto) {
        EAMWorkOrder domain = eamworkorderMapping.toDomain(eamworkorderdto);
		eamworkorderService.create(domain);
        EAMWorkOrderDTO dto = eamworkorderMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.eamworkorderMapping.toDomain(#eamworkorderdtos),'iBizAssetManagement-EAMWorkOrder-Create')")
    @ApiOperation(value = "批量新建工单", tags = {"工单" },  notes = "批量新建工单")
	@RequestMapping(method = RequestMethod.POST, value = "/eamworkorders/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<EAMWorkOrderDTO> eamworkorderdtos) {
        eamworkorderService.createBatch(eamworkorderMapping.toDomain(eamworkorderdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "eamworkorder" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.eamworkorderService.get(#eamworkorder_id),'iBizAssetManagement-EAMWorkOrder-Update')")
    @ApiOperation(value = "更新工单", tags = {"工单" },  notes = "更新工单")
	@RequestMapping(method = RequestMethod.PUT, value = "/eamworkorders/{eamworkorder_id}")
    @Transactional
    public ResponseEntity<EAMWorkOrderDTO> update(@PathVariable("eamworkorder_id") String eamworkorder_id, @RequestBody EAMWorkOrderDTO eamworkorderdto) {
		EAMWorkOrder domain  = eamworkorderMapping.toDomain(eamworkorderdto);
        domain .setWorkorderid(eamworkorder_id);
		eamworkorderService.update(domain );
		EAMWorkOrderDTO dto = eamworkorderMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.eamworkorderService.getEamworkorderByEntities(this.eamworkorderMapping.toDomain(#eamworkorderdtos)),'iBizAssetManagement-EAMWorkOrder-Update')")
    @ApiOperation(value = "批量更新工单", tags = {"工单" },  notes = "批量更新工单")
	@RequestMapping(method = RequestMethod.PUT, value = "/eamworkorders/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<EAMWorkOrderDTO> eamworkorderdtos) {
        eamworkorderService.updateBatch(eamworkorderMapping.toDomain(eamworkorderdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.eamworkorderService.get(#eamworkorder_id),'iBizAssetManagement-EAMWorkOrder-Remove')")
    @ApiOperation(value = "删除工单", tags = {"工单" },  notes = "删除工单")
	@RequestMapping(method = RequestMethod.DELETE, value = "/eamworkorders/{eamworkorder_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("eamworkorder_id") String eamworkorder_id) {
         return ResponseEntity.status(HttpStatus.OK).body(eamworkorderService.remove(eamworkorder_id));
    }

    @PreAuthorize("hasPermission(this.eamworkorderService.getEamworkorderByIds(#ids),'iBizAssetManagement-EAMWorkOrder-Remove')")
    @ApiOperation(value = "批量删除工单", tags = {"工单" },  notes = "批量删除工单")
	@RequestMapping(method = RequestMethod.DELETE, value = "/eamworkorders/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        eamworkorderService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.eamworkorderMapping.toDomain(returnObject.body),'iBizAssetManagement-EAMWorkOrder-Get')")
    @ApiOperation(value = "获取工单", tags = {"工单" },  notes = "获取工单")
	@RequestMapping(method = RequestMethod.GET, value = "/eamworkorders/{eamworkorder_id}")
    public ResponseEntity<EAMWorkOrderDTO> get(@PathVariable("eamworkorder_id") String eamworkorder_id) {
        EAMWorkOrder domain = eamworkorderService.get(eamworkorder_id);
        EAMWorkOrderDTO dto = eamworkorderMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取工单草稿", tags = {"工单" },  notes = "获取工单草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/eamworkorders/getdraft")
    public ResponseEntity<EAMWorkOrderDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(eamworkorderMapping.toDto(eamworkorderService.getDraft(new EAMWorkOrder())));
    }

    @ApiOperation(value = "检查工单", tags = {"工单" },  notes = "检查工单")
	@RequestMapping(method = RequestMethod.POST, value = "/eamworkorders/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody EAMWorkOrderDTO eamworkorderdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(eamworkorderService.checkKey(eamworkorderMapping.toDomain(eamworkorderdto)));
    }

    @PreAuthorize("hasPermission(this.eamworkorderMapping.toDomain(#eamworkorderdto),'iBizAssetManagement-EAMWorkOrder-Save')")
    @ApiOperation(value = "保存工单", tags = {"工单" },  notes = "保存工单")
	@RequestMapping(method = RequestMethod.POST, value = "/eamworkorders/save")
    public ResponseEntity<Boolean> save(@RequestBody EAMWorkOrderDTO eamworkorderdto) {
        return ResponseEntity.status(HttpStatus.OK).body(eamworkorderService.save(eamworkorderMapping.toDomain(eamworkorderdto)));
    }

    @PreAuthorize("hasPermission(this.eamworkorderMapping.toDomain(#eamworkorderdtos),'iBizAssetManagement-EAMWorkOrder-Save')")
    @ApiOperation(value = "批量保存工单", tags = {"工单" },  notes = "批量保存工单")
	@RequestMapping(method = RequestMethod.POST, value = "/eamworkorders/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<EAMWorkOrderDTO> eamworkorderdtos) {
        eamworkorderService.saveBatch(eamworkorderMapping.toDomain(eamworkorderdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizAssetManagement-EAMWorkOrder-searchDefault-all') and hasPermission(#context,'iBizAssetManagement-EAMWorkOrder-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"工单" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/eamworkorders/fetchdefault")
	public ResponseEntity<List<EAMWorkOrderDTO>> fetchDefault(EAMWorkOrderSearchContext context) {
        Page<EAMWorkOrder> domains = eamworkorderService.searchDefault(context) ;
        List<EAMWorkOrderDTO> list = eamworkorderMapping.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','iBizAssetManagement-EAMWorkOrder-searchDefault-all') and hasPermission(#context,'iBizAssetManagement-EAMWorkOrder-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"工单" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/eamworkorders/searchdefault")
	public ResponseEntity<Page<EAMWorkOrderDTO>> searchDefault(@RequestBody EAMWorkOrderSearchContext context) {
        Page<EAMWorkOrder> domains = eamworkorderService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(eamworkorderMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasPermission(this.eamworkorderMapping.toDomain(#eamworkorderdto),'iBizAssetManagement-EAMWorkOrder-Create')")
    @ApiOperation(value = "根据维护申请建立工单", tags = {"工单" },  notes = "根据维护申请建立工单")
	@RequestMapping(method = RequestMethod.POST, value = "/eamapplies/{eamapply_id}/eamworkorders")
    @Transactional
    public ResponseEntity<EAMWorkOrderDTO> createByEAMApply(@PathVariable("eamapply_id") String eamapply_id, @RequestBody EAMWorkOrderDTO eamworkorderdto) {
        EAMWorkOrder domain = eamworkorderMapping.toDomain(eamworkorderdto);
        domain.setWooriginid(eamapply_id);
		eamworkorderService.create(domain);
        EAMWorkOrderDTO dto = eamworkorderMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.eamworkorderMapping.toDomain(#eamworkorderdtos),'iBizAssetManagement-EAMWorkOrder-Create')")
    @ApiOperation(value = "根据维护申请批量建立工单", tags = {"工单" },  notes = "根据维护申请批量建立工单")
	@RequestMapping(method = RequestMethod.POST, value = "/eamapplies/{eamapply_id}/eamworkorders/batch")
    public ResponseEntity<Boolean> createBatchByEAMApply(@PathVariable("eamapply_id") String eamapply_id, @RequestBody List<EAMWorkOrderDTO> eamworkorderdtos) {
        List<EAMWorkOrder> domainlist=eamworkorderMapping.toDomain(eamworkorderdtos);
        for(EAMWorkOrder domain:domainlist){
            domain.setWooriginid(eamapply_id);
        }
        eamworkorderService.createBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "eamworkorder" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.eamworkorderService.get(#eamworkorder_id),'iBizAssetManagement-EAMWorkOrder-Update')")
    @ApiOperation(value = "根据维护申请更新工单", tags = {"工单" },  notes = "根据维护申请更新工单")
	@RequestMapping(method = RequestMethod.PUT, value = "/eamapplies/{eamapply_id}/eamworkorders/{eamworkorder_id}")
    @Transactional
    public ResponseEntity<EAMWorkOrderDTO> updateByEAMApply(@PathVariable("eamapply_id") String eamapply_id, @PathVariable("eamworkorder_id") String eamworkorder_id, @RequestBody EAMWorkOrderDTO eamworkorderdto) {
        EAMWorkOrder domain = eamworkorderMapping.toDomain(eamworkorderdto);
        domain.setWooriginid(eamapply_id);
        domain.setWorkorderid(eamworkorder_id);
		eamworkorderService.update(domain);
        EAMWorkOrderDTO dto = eamworkorderMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.eamworkorderService.getEamworkorderByEntities(this.eamworkorderMapping.toDomain(#eamworkorderdtos)),'iBizAssetManagement-EAMWorkOrder-Update')")
    @ApiOperation(value = "根据维护申请批量更新工单", tags = {"工单" },  notes = "根据维护申请批量更新工单")
	@RequestMapping(method = RequestMethod.PUT, value = "/eamapplies/{eamapply_id}/eamworkorders/batch")
    public ResponseEntity<Boolean> updateBatchByEAMApply(@PathVariable("eamapply_id") String eamapply_id, @RequestBody List<EAMWorkOrderDTO> eamworkorderdtos) {
        List<EAMWorkOrder> domainlist=eamworkorderMapping.toDomain(eamworkorderdtos);
        for(EAMWorkOrder domain:domainlist){
            domain.setWooriginid(eamapply_id);
        }
        eamworkorderService.updateBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.eamworkorderService.get(#eamworkorder_id),'iBizAssetManagement-EAMWorkOrder-Remove')")
    @ApiOperation(value = "根据维护申请删除工单", tags = {"工单" },  notes = "根据维护申请删除工单")
	@RequestMapping(method = RequestMethod.DELETE, value = "/eamapplies/{eamapply_id}/eamworkorders/{eamworkorder_id}")
    @Transactional
    public ResponseEntity<Boolean> removeByEAMApply(@PathVariable("eamapply_id") String eamapply_id, @PathVariable("eamworkorder_id") String eamworkorder_id) {
		return ResponseEntity.status(HttpStatus.OK).body(eamworkorderService.remove(eamworkorder_id));
    }

    @PreAuthorize("hasPermission(this.eamworkorderService.getEamworkorderByIds(#ids),'iBizAssetManagement-EAMWorkOrder-Remove')")
    @ApiOperation(value = "根据维护申请批量删除工单", tags = {"工单" },  notes = "根据维护申请批量删除工单")
	@RequestMapping(method = RequestMethod.DELETE, value = "/eamapplies/{eamapply_id}/eamworkorders/batch")
    public ResponseEntity<Boolean> removeBatchByEAMApply(@RequestBody List<String> ids) {
        eamworkorderService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.eamworkorderMapping.toDomain(returnObject.body),'iBizAssetManagement-EAMWorkOrder-Get')")
    @ApiOperation(value = "根据维护申请获取工单", tags = {"工单" },  notes = "根据维护申请获取工单")
	@RequestMapping(method = RequestMethod.GET, value = "/eamapplies/{eamapply_id}/eamworkorders/{eamworkorder_id}")
    public ResponseEntity<EAMWorkOrderDTO> getByEAMApply(@PathVariable("eamapply_id") String eamapply_id, @PathVariable("eamworkorder_id") String eamworkorder_id) {
        EAMWorkOrder domain = eamworkorderService.get(eamworkorder_id);
        EAMWorkOrderDTO dto = eamworkorderMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "根据维护申请获取工单草稿", tags = {"工单" },  notes = "根据维护申请获取工单草稿")
    @RequestMapping(method = RequestMethod.GET, value = "/eamapplies/{eamapply_id}/eamworkorders/getdraft")
    public ResponseEntity<EAMWorkOrderDTO> getDraftByEAMApply(@PathVariable("eamapply_id") String eamapply_id) {
        EAMWorkOrder domain = new EAMWorkOrder();
        domain.setWooriginid(eamapply_id);
        return ResponseEntity.status(HttpStatus.OK).body(eamworkorderMapping.toDto(eamworkorderService.getDraft(domain)));
    }

    @ApiOperation(value = "根据维护申请检查工单", tags = {"工单" },  notes = "根据维护申请检查工单")
	@RequestMapping(method = RequestMethod.POST, value = "/eamapplies/{eamapply_id}/eamworkorders/checkkey")
    public ResponseEntity<Boolean> checkKeyByEAMApply(@PathVariable("eamapply_id") String eamapply_id, @RequestBody EAMWorkOrderDTO eamworkorderdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(eamworkorderService.checkKey(eamworkorderMapping.toDomain(eamworkorderdto)));
    }

    @PreAuthorize("hasPermission(this.eamworkorderMapping.toDomain(#eamworkorderdto),'iBizAssetManagement-EAMWorkOrder-Save')")
    @ApiOperation(value = "根据维护申请保存工单", tags = {"工单" },  notes = "根据维护申请保存工单")
	@RequestMapping(method = RequestMethod.POST, value = "/eamapplies/{eamapply_id}/eamworkorders/save")
    public ResponseEntity<Boolean> saveByEAMApply(@PathVariable("eamapply_id") String eamapply_id, @RequestBody EAMWorkOrderDTO eamworkorderdto) {
        EAMWorkOrder domain = eamworkorderMapping.toDomain(eamworkorderdto);
        domain.setWooriginid(eamapply_id);
        return ResponseEntity.status(HttpStatus.OK).body(eamworkorderService.save(domain));
    }

    @PreAuthorize("hasPermission(this.eamworkorderMapping.toDomain(#eamworkorderdtos),'iBizAssetManagement-EAMWorkOrder-Save')")
    @ApiOperation(value = "根据维护申请批量保存工单", tags = {"工单" },  notes = "根据维护申请批量保存工单")
	@RequestMapping(method = RequestMethod.POST, value = "/eamapplies/{eamapply_id}/eamworkorders/savebatch")
    public ResponseEntity<Boolean> saveBatchByEAMApply(@PathVariable("eamapply_id") String eamapply_id, @RequestBody List<EAMWorkOrderDTO> eamworkorderdtos) {
        List<EAMWorkOrder> domainlist=eamworkorderMapping.toDomain(eamworkorderdtos);
        for(EAMWorkOrder domain:domainlist){
             domain.setWooriginid(eamapply_id);
        }
        eamworkorderService.saveBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizAssetManagement-EAMWorkOrder-searchDefault-all') and hasPermission(#context,'iBizAssetManagement-EAMWorkOrder-Get')")
	@ApiOperation(value = "根据维护申请获取DEFAULT", tags = {"工单" } ,notes = "根据维护申请获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/eamapplies/{eamapply_id}/eamworkorders/fetchdefault")
	public ResponseEntity<List<EAMWorkOrderDTO>> fetchEAMWorkOrderDefaultByEAMApply(@PathVariable("eamapply_id") String eamapply_id,EAMWorkOrderSearchContext context) {
        context.setN_eamwooriginid_eq(eamapply_id);
        Page<EAMWorkOrder> domains = eamworkorderService.searchDefault(context) ;
        List<EAMWorkOrderDTO> list = eamworkorderMapping.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','iBizAssetManagement-EAMWorkOrder-searchDefault-all') and hasPermission(#context,'iBizAssetManagement-EAMWorkOrder-Get')")
	@ApiOperation(value = "根据维护申请查询DEFAULT", tags = {"工单" } ,notes = "根据维护申请查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/eamapplies/{eamapply_id}/eamworkorders/searchdefault")
	public ResponseEntity<Page<EAMWorkOrderDTO>> searchEAMWorkOrderDefaultByEAMApply(@PathVariable("eamapply_id") String eamapply_id, @RequestBody EAMWorkOrderSearchContext context) {
        context.setN_eamwooriginid_eq(eamapply_id);
        Page<EAMWorkOrder> domains = eamworkorderService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(eamworkorderMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

