package com.sw.mes.yb.fls.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.fls.dto.KfReturnMaterialDto;
import com.sw.mes.yb.fls.dto.KfReturnMaterialStatusDto;
import com.sw.mes.yb.fls.entity.KfReturnMaterial;
import com.sw.mes.yb.fls.service.KfReturnMaterialService;
import com.sw.mes.yb.fls.service.MesToFlsService;
import com.sw.mes.yb.fls.utils.ResultDto;
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.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/kfReturnMaterial")
@Slf4j
@Api(description = "开方退料接口")
public class KfReturnMaterialController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private KfReturnMaterialService kfReturnMaterialService;

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

	@ApiOperation(value = "获取所有KfReturnMaterial")
	@GetMapping("/listAll")
	public Result<List<KfReturnMaterialDto>> listAll(ServletRequest request) {
		Specification<KfReturnMaterial> specification = DynamicSpecifications.bySearchFilter(request, KfReturnMaterial.class);
		List<KfReturnMaterial> kfReturnMaterials = kfReturnMaterialService.findByExampleSort(specification, null);
		List<KfReturnMaterialDto> kfReturnMaterialDtos = kfReturnMaterials.stream()
					.map(kfReturnMaterial -> toLazyDto(kfReturnMaterial))
					.collect(Collectors.toList());
		return ResultGenerator.success(kfReturnMaterialDtos);
	}

	@ApiOperation(value = "KfReturnMaterial详细信息")
	@GetMapping("/{id}")
	public Result<KfReturnMaterialDto> get(@PathVariable @ApiParam(value="KfReturnMaterialid") Long id) {
		KfReturnMaterial kfReturnMaterial = kfReturnMaterialService.get(id);
		if (null == kfReturnMaterial)
			return ResultGenerator.fail("该KfReturnMaterial不存在");
		return ResultGenerator.success(toEagerDto(kfReturnMaterial));
	}

	@ApiOperation(value = "创建KfReturnMaterial")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "KfReturnMaterial对象") KfReturnMaterialDto kfReturnMaterialDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		KfReturnMaterial kfReturnMaterial = fromDto(kfReturnMaterialDto);
		kfReturnMaterialService.saveOrUpdate(kfReturnMaterial);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新KfReturnMaterial")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "KfReturnMaterial") KfReturnMaterialDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            KfReturnMaterial entity = kfReturnMaterialService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            KfReturnMaterial entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			entity.setUpdateTime(new Date());
			//通知fls,取消退料任务
			if ("2".equals(entity.getStatus())){
				KfReturnMaterialStatusDto kfReturnMaterialStatusDto = new KfReturnMaterialStatusDto();
				kfReturnMaterialStatusDto.setPort(entity.getPort());
				kfReturnMaterialStatusDto.setResult(entity.getStatus());
				kfReturnMaterialStatusDto.setRobotCode(entity.getRobotCode());
				ResultDto resultDto = mesToFlsService.kfReturnMaterialStatusOut(kfReturnMaterialStatusDto);
				if (resultDto == null || resultDto.getStatus() == null || resultDto.getStatus() != 100){
					throw new RuntimeException("通知smcs下料确认信息失败！" + resultDto.getMessage());
				}
			}
			kfReturnMaterialService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

	@ApiOperation(value = "删除KfReturnMaterial")
	@PostMapping("/delete")
	public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
		for (Integer id : ids) {
				kfReturnMaterialService.delete(id);
		}
		return ResultGenerator.success();
	}
	@ApiOperation(value = "开方退料确认")
	@PostMapping("/confirm")
	public Result confirm(@RequestBody @Valid @ApiParam(value = "KfReturnMaterial对象") KfReturnMaterialDto kfReturnMaterialDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		KfReturnMaterial kfReturnMaterial = kfReturnMaterialService.get(kfReturnMaterialDto.getId());
		if (kfReturnMaterial==null){
			return ResultGenerator.fail("开方退料记录不存在");
		}
		if (!kfReturnMaterial.getStatus().equals("0")){
			return ResultGenerator.fail("开方退料记录非待确认状态");
		}
		try{
			kfReturnMaterialService.confirm(kfReturnMaterial);
			return ResultGenerator.success();
		}catch(Exception e){
			return ResultGenerator.fail(e.getMessage());
		}
	}
	public KfReturnMaterialDto toLazyDto(KfReturnMaterial entity) {
		return modelMapper.map(entity, KfReturnMaterialDto.class);
	}

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

	public KfReturnMaterial fromDto(KfReturnMaterialDto dto) {
		return modelMapper.map(dto, KfReturnMaterial.class);
	}


}
