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

import com.sw.mes.base.workinprocess.dto.ProcessLogDto;
import com.sw.mes.base.workinprocess.entity.ProcessLog;
import com.sw.mes.core.context.BaseContextHandler;
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.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import com.sw.mes.yb.production.entity.ProcessPath;
import com.sw.mes.yb.production.dto.ProcessPathDto;
import com.sw.mes.yb.production.service.ProcessPathService;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/processPath")
@Slf4j
@Api(description = "ProcessPath接口")
public class ProcessPathController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private ProcessPathService processPathService;

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

	@ApiOperation(value = "获取所有ProcessPath")
	@GetMapping("/listAll")
	public Result<List<ProcessPathDto>> listAll(ServletRequest request) {
		Specification<ProcessPath> specification = DynamicSpecifications.bySearchFilter(request, ProcessPath.class);
		List<ProcessPath> processPaths = processPathService.findByExampleSort(specification, null);
		List<ProcessPathDto> processPathDtos = processPaths.stream()
					.map(processPath -> toLazyDto(processPath))
					.collect(Collectors.toList());
		return ResultGenerator.success(processPathDtos);
	}

	@ApiOperation(value = "ProcessPath详细信息")
	@GetMapping("/{id}")
	public Result<ProcessPathDto> get(@PathVariable @ApiParam(value="ProcessPathid") Long id) {
		ProcessPath processPath = processPathService.get(id);
		if (null == processPath)
			return ResultGenerator.fail("该ProcessPath不存在");
		return ResultGenerator.success(toEagerDto(processPath));
	}

	@ApiOperation(value = "创建ProcessPath")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "ProcessPath对象") ProcessPathDto processPathDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		ProcessPath processPath = fromDto(processPathDto);
		processPathService.saveOrUpdate(processPath);
		return ResultGenerator.success();
	}

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

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

	@ApiOperation(value = "导出炉次工艺步骤列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "search_LIKE_equipmentCode", value = "设备号", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search_LIKE_lotNo", value = "炉次号", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search_LIKE_stepName", value = "工艺名称", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search_GTE_startTime", value = "工步发生时间", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search_LTE_startTime", value = "工步发生时间", dataType = "string", paramType = "query"),
	})
	@GetMapping("/export")
	public void export(ServletRequest request, HttpServletResponse response) {
		try {
			Specification<ProcessPath> specification = DynamicSpecifications.bySearchFilter(request, ProcessPath.class);
			List<ProcessPath> byExampleSort = processPathService.findByExampleSort(specification, null);
			List<ProcessPathDto> dtos = byExampleSort.stream()
					.map(entity -> toLazyDto(entity))
					.collect(Collectors.toList());
			EasyExcelUtils.write(response, ProcessPathDto.class, "导出单晶炉工步运行情况", "导出单晶炉工步运行情况", dtos);
		} catch (IOException e) {
			throw new RuntimeException("炉次工艺步骤导出失败，错误信息：" + e.getMessage());
		}
	}

	public ProcessPathDto toLazyDto(ProcessPath entity) {
		return modelMapper.map(entity, ProcessPathDto.class);
	}

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

	public ProcessPath fromDto(ProcessPathDto dto) {
		return modelMapper.map(dto, ProcessPath.class);
	}


}
