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

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.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
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.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
import com.sw.mes.yb.production.entity.LoadingTaskLog;
import com.sw.mes.yb.production.dto.LoadingTask.LoadingTaskLogDto;
import com.sw.mes.yb.production.service.LoadingTaskLogService;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/loadingTaskLog")
@Slf4j
@Api(description = "装料任务记录接口")
public class LoadingTaskLogController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private LoadingTaskLogService loadingTaskLogService;

	@ApiOperation(value = "分页查询装料任务记录接口列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "search_EQ_rawStatus", value = "状态", dataType = "Long", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_equipmentCode", value = "设备号", dataType = "String", paramType = "query"),
		@ApiImplicitParam(name = "search_GTE_recipeTime", value = "配料开始时间（yyyy-MM-dd HH:mm:ss）", dataType = "String", paramType = "query"),
		@ApiImplicitParam(name = "search_LTE_recipeTime", value = "配料结束时间（yyyy-MM-dd HH:mm:ss）", dataType = "String", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<LoadingTaskLogDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<LoadingTaskLog> specification = DynamicSpecifications.bySearchFilter(request, LoadingTaskLog.class);
    	Page<LoadingTaskLog> page = loadingTaskLogService.findByExample(specification, PageUtil.createPageable(requestPage,new String[]{"operationTime DESC"}));
		List<LoadingTaskLogDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}

	@ApiOperation(value = "获取所有装料任务记录接口")
	@GetMapping("/listAll")
	public Result<List<LoadingTaskLogDto>> listAll(ServletRequest request) {
		Specification<LoadingTaskLog> specification = DynamicSpecifications.bySearchFilter(request, LoadingTaskLog.class);
		List<LoadingTaskLog> loadingTaskLogs = loadingTaskLogService.findByExampleSort(specification, null);
		List<LoadingTaskLogDto> loadingTaskLogDtos = loadingTaskLogs.stream()
					.map(loadingTaskLog -> toLazyDto(loadingTaskLog))
					.collect(Collectors.toList());
		return ResultGenerator.success(loadingTaskLogDtos);
	}

	@ApiOperation(value = "装料任务记录详细信息")
	@GetMapping("/{id}")
	public Result<LoadingTaskLogDto> get(@PathVariable @ApiParam(value="LoadingTaskLogid") Long id) {
		LoadingTaskLog loadingTaskLog = loadingTaskLogService.get(id);
		if (null == loadingTaskLog)
			return ResultGenerator.fail("该LoadingTaskLog不存在");
		return ResultGenerator.success(toEagerDto(loadingTaskLog));
	}

	@ApiOperation(value = "创建装料任务记录接口")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "LoadingTaskLog对象") LoadingTaskLogDto loadingTaskLogDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		LoadingTaskLog loadingTaskLog = fromDto(loadingTaskLogDto);
		loadingTaskLogService.saveOrUpdate(loadingTaskLog);
		return ResultGenerator.success();
	}

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

	@ApiOperation(value = "删除装料任务记录接口")
	@PostMapping("/delete")
	public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
		for (Integer id : ids) {
				loadingTaskLogService.delete(id);
		}
		return ResultGenerator.success();
	}

	public LoadingTaskLogDto toLazyDto(LoadingTaskLog entity) {
		return modelMapper.map(entity, LoadingTaskLogDto.class);
	}

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

	public LoadingTaskLog fromDto(LoadingTaskLogDto dto) {
		return modelMapper.map(dto, LoadingTaskLog.class);
	}

	@ApiOperation(value = "导出装料任务记录接口")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "search_EQ_rawStatus", value = "状态1-生产;2-已取消;3-自动完工;4-人工完工;5-退料", dataType = "Long", paramType = "query"),
			@ApiImplicitParam(name = "search_LIKE_equipmentCode", value = "设备号", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "search_GTE_recipeTime", value = "配料开始时间（yyyy-MM-dd HH:mm:ss）", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "search_LTE_recipeTime", value = "配料结束时间（yyyy-MM-dd HH:mm:ss）", dataType = "String", paramType = "query"),
	})
	@GetMapping("/exportExcel")
	public void export(HttpServletRequest request, HttpServletResponse response) {
		try {
			loadingTaskLogService.exportExcel(request,response);
		} catch (Exception e) {
			throw new RuntimeException("导出装料任务记录表失败，错误信息：" + e.getMessage());
		}
	}


}
