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.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.production.dto.BatchOperationDto;
import com.sw.mes.yb.production.dto.CrystalBatchInfoDto;
import com.sw.mes.yb.production.dto.CrystalBatchOperationCreateDto;
import com.sw.mes.yb.production.dto.CrystalBatchOperationDto;
import com.sw.mes.yb.production.entity.CrystalBatchOperation;
import com.sw.mes.yb.production.service.CrystalBatchOperationService;
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.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/crystalBatchOperation")
@Slf4j
@Api(description = "批次操作接口")
public class CrystalBatchOperationController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private CrystalBatchOperationService crystalBatchOperationService;

	@ApiOperation(value = "分页查询批次操作列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<CrystalBatchOperationDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<CrystalBatchOperation> specification = DynamicSpecifications.bySearchFilter(request, CrystalBatchOperation.class);
    	Page<CrystalBatchOperation> page = crystalBatchOperationService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<CrystalBatchOperationDto> 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<CrystalBatchOperationDto>> listAll(ServletRequest request) {
		Specification<CrystalBatchOperation> specification = DynamicSpecifications.bySearchFilter(request, CrystalBatchOperation.class);
		List<CrystalBatchOperation> crystalBatchOperations = crystalBatchOperationService.findByExampleSort(specification, null);
		List<CrystalBatchOperationDto> crystalBatchOperationDtos = crystalBatchOperations.stream()
					.map(crystalBatchOperation -> toLazyDto(crystalBatchOperation))
					.collect(Collectors.toList());
		return ResultGenerator.success(crystalBatchOperationDtos);
	}

	@ApiOperation(value = "批次操作详细信息")
	@GetMapping("/{id}")
	public Result<CrystalBatchOperationDto> get(@PathVariable @ApiParam(value="批次操作id") Long id) {
		CrystalBatchOperation crystalBatchOperation = crystalBatchOperationService.get(id);
		if (null == crystalBatchOperation)
			return ResultGenerator.fail("该批次操作不存在");
		return ResultGenerator.success(toEagerDto(crystalBatchOperation));
	}

	@ApiOperation(value = "创建批次操作")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "批次操作对象") CrystalBatchOperationDto crystalBatchOperationDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		CrystalBatchOperation crystalBatchOperation = fromDto(crystalBatchOperationDto);
		crystalBatchOperationService.saveOrUpdate(crystalBatchOperation);
		return ResultGenerator.success();
	}

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

	@ApiOperation(value = "批量批次操作")
	@PostMapping("/batchOperate")
	public Result batchOperate(@RequestBody @Valid @ApiParam(value = "批次操作对象") BatchOperationDto batchOperationDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		try {
			crystalBatchOperationService.batchOperateCrystalBatchOperation(batchOperationDto);
			return ResultGenerator.success();
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}

	@ApiOperation(value = "获取单晶信息")
	@GetMapping("getInfoBySectionNo")
	public Result<List<CrystalBatchInfoDto>> getInfoBySectionNo(@RequestParam String sectionNo) {
		return ResultGenerator.success( crystalBatchOperationService.getInfoBySectionNo(sectionNo));
	}

	@ApiOperation(value = "批量创建批次操作")
	@PostMapping("/batchCreate")
	public Result batchCreate(@RequestBody @Valid @ApiParam(value = "批次操作对象") CrystalBatchOperationCreateDto crystalBatchOperationCreateDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		try {
			crystalBatchOperationService.batchCreateCrystalBatchOperation(crystalBatchOperationCreateDto);
			return ResultGenerator.success();
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}

	@ApiOperation(value = "批次号判断是否锁定")
	@GetMapping("/judgeCrystalNoIsLock")
	public Result judgeCrystalNoIsLock(@RequestParam(required = false) String crystalNo,@RequestParam(required = false) String sectionNo,@RequestParam Boolean isCrystalBar) {

		try {
			crystalBatchOperationService.judgeCrystalNoIsLock(crystalNo, sectionNo,isCrystalBar);
			return ResultGenerator.success();
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}


	public CrystalBatchOperationDto toLazyDto(CrystalBatchOperation entity) {
		return modelMapper.map(entity, CrystalBatchOperationDto.class);
	}

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

	public CrystalBatchOperation fromDto(CrystalBatchOperationDto dto) {
		return modelMapper.map(dto, CrystalBatchOperation.class);
	}


}
