package com.sw.mes.fb.productChangeRecord.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 com.sw.mes.fb.productChangeRecord.dto.ProductChangeBatchDto;
import com.sw.mes.fb.productChangeRecord.dto.ProductChangeRecordDto;
import com.sw.mes.fb.productChangeRecord.entity.ProductChangeRecord;
import com.sw.mes.fb.productChangeRecord.service.ProductChangeRecordService;
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.domain.Sort;
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.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/productChangeRecord")
@Slf4j
@Api(description = "产品变更记录接口")
public class ProductChangeRecordController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private ProductChangeRecordService productChangeRecordService;

	@ApiOperation(value = "分页查询产品变更记录列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<ProductChangeRecordDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<ProductChangeRecord> specification = DynamicSpecifications.bySearchFilter(request, ProductChangeRecord.class);
    	Page<ProductChangeRecord> page = productChangeRecordService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<ProductChangeRecordDto> 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<ProductChangeRecordDto>> listAll(ServletRequest request) {
		Specification<ProductChangeRecord> specification = DynamicSpecifications.bySearchFilter(request, ProductChangeRecord.class);
		List<ProductChangeRecord> productChangeRecords = productChangeRecordService.findByExampleSort(specification, null);
		List<ProductChangeRecordDto> productChangeRecordDtos = productChangeRecords.stream()
					.map(productChangeRecord -> toLazyDto(productChangeRecord))
					.collect(Collectors.toList());
		return ResultGenerator.success(productChangeRecordDtos);
	}

	@ApiOperation(value = "产品变更记录详细信息")
	@GetMapping("/{id}")
	public Result<ProductChangeRecordDto> get(@PathVariable @ApiParam(value="产品变更记录id") Long id) {
		ProductChangeRecord productChangeRecord = productChangeRecordService.get(id);
		if (null == productChangeRecord)
			return ResultGenerator.fail("该产品变更记录不存在");
		return ResultGenerator.success(toEagerDto(productChangeRecord));
	}

	@ApiOperation(value = "创建产品变更记录")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "产品变更记录对象") ProductChangeRecordDto productChangeRecordDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		ProductChangeRecord productChangeRecord = fromDto(productChangeRecordDto);
		productChangeRecordService.saveOrUpdate(productChangeRecord);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新产品变更记录")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "产品变更记录") ProductChangeRecordDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            ProductChangeRecord entity = productChangeRecordService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            ProductChangeRecord entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			productChangeRecordService.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) {
			productChangeRecordService.delete(id);
		}
		return ResultGenerator.success();
	}

	@ApiOperation(value = "批量获取单晶信息")
	@GetMapping("/getBatchInfo")
	public Result<ProductChangeBatchDto> getBatchInfo(@RequestParam String sectionNoList) {

		try {
			return ResultGenerator.success(productChangeRecordService.getBatchInfo(sectionNoList));
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}

	}

	@ApiOperation(value = "批量产品变更")
	@PostMapping("/batchCreate")
	public Result batchCreate(@RequestBody ProductChangeBatchDto productChangeBatchDto) {

		try {
			productChangeRecordService.batchCreate(productChangeBatchDto);
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success();
	}

	@ApiOperation(value = "导出产品变更记录")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "search_LIKE_preSectionNo", value = "晶段编号(前)", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search_LIKE_sectionNo", value = "晶段编号(后)", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search_LIKE_orderNo", value = "工单号", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search_LIKE_materialCode", value = "物料号", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search_GTE_createTime", value = "操作时间(开始时间)", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "search_LT_createTime", value = "操作时间(结束时间)", dataType = "string", paramType = "query"),
	})
	@GetMapping("/export")
	public void export(ServletRequest request, @ApiIgnore RequestPage requestPage, HttpServletResponse response) {
		try {
			Specification<ProductChangeRecord> specification = DynamicSpecifications.bySearchFilter(request, ProductChangeRecord.class);
			List<ProductChangeRecord> list = productChangeRecordService.findByExampleSort(specification, Sort.by(Sort.Direction.DESC,"id"));
			List<ProductChangeRecordDto> dtos = list.stream().map(entity -> toLazyDto(entity)).collect(Collectors.toList());

			EasyExcelUtils.write(response, ProductChangeRecordDto.class, "产品变更记录", "产品变更记录", dtos);
		} catch (Exception e) {
			throw new RuntimeException("导出产品变更记录，错误信息：" + e.getMessage());
		}
	}
	public ProductChangeRecordDto toLazyDto(ProductChangeRecord entity) {
		return modelMapper.map(entity, ProductChangeRecordDto.class);
	}

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

	public ProductChangeRecord fromDto(ProductChangeRecordDto dto) {
		return modelMapper.map(dto, ProductChangeRecord.class);
	}


}
