package com.sw.mes.yb.agv.controller;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.ServletRequest;
import javax.validation.Valid;

import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.BeanUtil;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.yb.agv.dto.AgvDispatchDeployRecordDto;
import com.sw.mes.yb.agv.entity.AgvDispatchDeployRecord;
import com.sw.mes.yb.agv.service.AgvDispatchDeployRecordService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/AgvDispatchDeployRecord")
@Slf4j
@Api(description = "AGV调度记录接口")
public class AgvDispatchDeployRecordController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private AgvDispatchDeployRecordService agvDispatchDeployRecordService;

	@ApiOperation(value = "分页查询AGV调度记录列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<AgvDispatchDeployRecordDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<AgvDispatchDeployRecord> specification = DynamicSpecifications.bySearchFilter(request, AgvDispatchDeployRecord.class);
    	Page<AgvDispatchDeployRecord> page = agvDispatchDeployRecordService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<AgvDispatchDeployRecordDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}

	@ApiOperation(value = "获取所有AGV调度记录")
	@GetMapping("/listAll")
	public Result<List<AgvDispatchDeployRecordDto>> listAll(ServletRequest request) {
		Specification<AgvDispatchDeployRecord> specification = DynamicSpecifications.bySearchFilter(request, AgvDispatchDeployRecord.class);
		List<AgvDispatchDeployRecord> agvDispatchDeployRecords = agvDispatchDeployRecordService.findByExampleSort(specification, null);
		List<AgvDispatchDeployRecordDto> agvDispatchDeployRecordDtos = agvDispatchDeployRecords.stream()
					.map(agvDispatchDeployRecord -> toLazyDto(agvDispatchDeployRecord))
					.collect(Collectors.toList());
		return ResultGenerator.success(agvDispatchDeployRecordDtos);
	}

	@ApiOperation(value = "AGV调度记录详细信息")
	@GetMapping("/{id}")
	public Result<AgvDispatchDeployRecordDto> get(@PathVariable @ApiParam(value="AGV调度记录id") Long id) {
		AgvDispatchDeployRecord agvDispatchDeployRecord = agvDispatchDeployRecordService.get(id);
		if (null == agvDispatchDeployRecord)
			return ResultGenerator.fail("该AGV调度记录不存在");
		return ResultGenerator.success(toEagerDto(agvDispatchDeployRecord));
	}

	@ApiOperation(value = "创建AGV调度记录")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "AGV调度记录对象") AgvDispatchDeployRecordDto agvDispatchDeployRecordDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		AgvDispatchDeployRecord agvDispatchDeployRecord = fromDto(agvDispatchDeployRecordDto);
		agvDispatchDeployRecordService.saveOrUpdate(agvDispatchDeployRecord);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新AGV调度记录")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "AGV调度记录") AgvDispatchDeployRecordDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            AgvDispatchDeployRecord entity = agvDispatchDeployRecordService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            AgvDispatchDeployRecord entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			agvDispatchDeployRecordService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

	@ApiOperation(value = "删除AGV调度记录")
	@PostMapping("/delete")
	public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
		for (Long id : ids) {
				agvDispatchDeployRecordService.delete(id);
		}
		return ResultGenerator.success();
	}


	@ApiOperation(value = "回调接口示例")
	@PostMapping("/callBack")
	public Result callBack(@RequestBody Map<String,Object> params) {
		//业务逻辑处理
		//1. 参数未确定，根据文档中自行与胡小胖沟通后自行确定参数名称
		//2.要求参数中必须包含 (taskCode)任务编号用于AGV任务对照
		return ResultGenerator.success();
	}


	public AgvDispatchDeployRecordDto toLazyDto(AgvDispatchDeployRecord entity) {
		return modelMapper.map(entity, AgvDispatchDeployRecordDto.class);
	}

	public AgvDispatchDeployRecordDto toEagerDto(AgvDispatchDeployRecord entity) {
		AgvDispatchDeployRecordDto dto = modelMapper.map(entity, AgvDispatchDeployRecordDto.class);
		return dto;
	}

	public AgvDispatchDeployRecord fromDto(AgvDispatchDeployRecordDto dto) {
		return modelMapper.map(dto, AgvDispatchDeployRecord.class);
	}


}
