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

import com.sw.mes.base.factory.inspect.dto.BatchOutgoMarkOperateInfoDto;
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.BatchOutgoMarkOperateDto;
import com.sw.mes.yb.production.dto.CrystalBatchInfoDto;
import com.sw.mes.yb.production.dto.OutgoMarkOperateDto;
import com.sw.mes.yb.production.entity.OutgoMarkOperate;
import com.sw.mes.yb.production.service.CrystalBatchOperationService;
import com.sw.mes.yb.production.service.OutgoMarkOperateService;
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("/outgoMarkOperate")
@Slf4j
@Api(description = "外发标识操作接口")
public class OutgoMarkOperateController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private OutgoMarkOperateService outgoMarkOperateService;


	@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<OutgoMarkOperateDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<OutgoMarkOperate> specification = DynamicSpecifications.bySearchFilter(request, OutgoMarkOperate.class);
    	Page<OutgoMarkOperate> page = outgoMarkOperateService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<OutgoMarkOperateDto> 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<OutgoMarkOperateDto>> listAll(ServletRequest request) {
		Specification<OutgoMarkOperate> specification = DynamicSpecifications.bySearchFilter(request, OutgoMarkOperate.class);
		List<OutgoMarkOperate> outgoMarkOperates = outgoMarkOperateService.findByExampleSort(specification, null);
		List<OutgoMarkOperateDto> outgoMarkOperateDtos = outgoMarkOperates.stream()
					.map(outgoMarkOperate -> toLazyDto(outgoMarkOperate))
					.collect(Collectors.toList());
		return ResultGenerator.success(outgoMarkOperateDtos);
	}

	@ApiOperation(value = "外发标识操作详细信息")
	@GetMapping("/{id}")
	public Result<OutgoMarkOperateDto> get(@PathVariable @ApiParam(value="外发标识操作id") Long id) {
		OutgoMarkOperate outgoMarkOperate = outgoMarkOperateService.get(id);
		if (null == outgoMarkOperate)
			return ResultGenerator.fail("该外发标识操作不存在");
		return ResultGenerator.success(toEagerDto(outgoMarkOperate));
	}

	@ApiOperation(value = "创建外发标识操作")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "外发标识操作对象") OutgoMarkOperateDto outgoMarkOperateDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		OutgoMarkOperate outgoMarkOperate = fromDto(outgoMarkOperateDto);
		outgoMarkOperateService.saveOrUpdate(outgoMarkOperate);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新外发标识操作")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "外发标识操作") OutgoMarkOperateDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            OutgoMarkOperate entity = outgoMarkOperateService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            OutgoMarkOperate entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			outgoMarkOperateService.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 Long[] ids) {
		for (Long id : ids) {
				outgoMarkOperateService.delete(id);
		}
		return ResultGenerator.success();
	}

	@ApiOperation(value = "批量外发标识操作")
	@PostMapping("/batchCreate")
	public Result batchCreate(@RequestBody @Valid @ApiParam(value = "批次操作对象") BatchOutgoMarkOperateDto batchOutgoMarkOperateDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		try {
			outgoMarkOperateService.batchCreateOutgoMarkOperate(batchOutgoMarkOperateDto);
			return ResultGenerator.success();
		} catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}

	@ApiOperation(value = "批量外发标识")
	@PostMapping("/batchOperate")
	public Result batchOperate(@RequestBody @Valid @ApiParam(value = "批次操作对象") BatchOutgoMarkOperateInfoDto batchOperationDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		try {
			outgoMarkOperateService.batchOutgoMarkOperate(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 = "单晶是否是外发单晶")
	@GetMapping("/judgeCrystalNoIsOutgo")
	public Result<OutgoMarkOperateDto> judgeCrystalNoIsOutgo(@RequestParam String sectionNo) {

		try {
			return ResultGenerator.success(outgoMarkOperateService.judgeCrystalNoIsOutgo(sectionNo));
		}catch (Exception e){
			return ResultGenerator.fail(e.getMessage());
		}
	}


	public OutgoMarkOperateDto toLazyDto(OutgoMarkOperate entity) {
		return modelMapper.map(entity, OutgoMarkOperateDto.class);
	}

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

	public OutgoMarkOperate fromDto(OutgoMarkOperateDto dto) {
		return modelMapper.map(dto, OutgoMarkOperate.class);
	}


}
