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

import com.sw.mes.core.dto.mes.pc.yb.ProductionBindingTrayDto;
import com.sw.mes.core.enums.EnumValuesFactory;
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.yb.production.entity.LongCrystal;
import com.sw.mes.yb.production.service.LongCrystalService;
import com.sw.mes.yb.turnstore.dto.BindingCrystalDto;
import com.sw.mes.yb.turnstore.entity.ProductionBindingTray;
import com.sw.mes.yb.turnstore.service.ProductionBindingTrayService;
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.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/ProductionBindingTray")
@Slf4j
@Api(description = "托盘绑定接口")
public class ProductionBindingTrayController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private ProductionBindingTrayService productionBindingTrayService;

	@Autowired
	private LongCrystalService longCrystalService;

	@ApiOperation(value = "分页查询托盘绑定接口列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<ProductionBindingTrayDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<ProductionBindingTray> specification = DynamicSpecifications.bySearchFilter(request, ProductionBindingTray.class);
    	Page<ProductionBindingTray> page = productionBindingTrayService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<ProductionBindingTrayDto> 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<ProductionBindingTrayDto>> listAll(ServletRequest request) {
		Specification<ProductionBindingTray> specification = DynamicSpecifications.bySearchFilter(request, ProductionBindingTray.class);
		List<ProductionBindingTray> productionBindingTrays = productionBindingTrayService.findByExampleSort(specification, null);
		List<ProductionBindingTrayDto> productionBindingTrayDtos = productionBindingTrays.stream()
					.map(productionBindingTray -> toLazyDto(productionBindingTray))
					.collect(Collectors.toList());
		for(ProductionBindingTrayDto productionBindingTrayDto : productionBindingTrayDtos){
			//查询长棒产出表，获取长棒信息
			LongCrystal byCrystalNo = longCrystalService.findByCrystalNo(productionBindingTrayDto.getCrystalNo());
			if (byCrystalNo != null){
				productionBindingTrayDto.setLength(byCrystalNo.getLength());
				productionBindingTrayDto.setWindUp(byCrystalNo.getWindUp());
				productionBindingTrayDto.setTime(byCrystalNo.getGmtCreate());
			}
		}

		return ResultGenerator.success(productionBindingTrayDtos);
	}

	@ApiOperation(value = "托盘绑定接口详细信息")
	@GetMapping("/{id}")
	public Result<ProductionBindingTrayDto> get(@PathVariable @ApiParam(value="ProductionBindingTrayid") Long id) {
		ProductionBindingTray productionBindingTray = productionBindingTrayService.get(id);
		if (null == productionBindingTray) {
            return ResultGenerator.fail("该ProductionBindingTray不存在");
        }
		return ResultGenerator.success(toEagerDto(productionBindingTray));
	}

	@ApiOperation(value = "托盘绑定单晶接口")
		@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "ProductionBindingTray对象") ProductionBindingTrayDto productionBindingTrayDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}

		return this.productionBindingTrayService.bindingCrystal(productionBindingTrayDto);
	}

    @ApiOperation(value = "更新托盘绑定接口")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "ProductionBindingTray") ProductionBindingTrayDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
            ProductionBindingTray entity = productionBindingTrayService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            ProductionBindingTray entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			productionBindingTrayService.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) {
				productionBindingTrayService.delete(id);
		}
		return ResultGenerator.success();
	}


	@ApiOperation(value = "通过托盘号找到对应单晶")
	@PostMapping("/findCrystal")
	public Result findCrystalNo(@ApiParam(value = "托号", type = "query") @RequestParam String trayNo) {

//		List<String> crystalNoByTrayNo = this.productionBindingTrayService.findCrystalNoByTrayNo(trayNo);
		List<ProductionBindingTray> crystalNoByTrayNoV2 = this.productionBindingTrayService.findCrystalNoByTrayNoV2(trayNo);
		List<ProductionBindingTray> result = new ArrayList<>();
		Optional.ofNullable(crystalNoByTrayNoV2).orElse(new ArrayList<>()).forEach(productionBindingTray -> {
			if (StringUtils.isNotBlank(productionBindingTray.getCrystalNo())){
				LongCrystal byCrystalNo = longCrystalService.findByCrystalNo(productionBindingTray.getCrystalNo());
				if (null != byCrystalNo && byCrystalNo.getCrystalStatus() != EnumValuesFactory.CrystalStatus.已划线.getKey()){
					result.add(productionBindingTray);
				}
			}
		});

//		if(null != crystalNoByTrayNoV2 && crystalNoByTrayNoV2.size() > 0){
//			StringBuilder str = new StringBuilder("单晶【");
//
//			for (ProductionBindingTray productionBindingTray : crystalNoByTrayNoV2) {
//				LongCrystal byCrystalNo = longCrystalService.findByCrystalNo(productionBindingTray.getCrystalNo());
//				if(StringUtils.isEmpty(byCrystalNo.getSideLengthRange())){
//					str.append(" ");
//					str.append(byCrystalNo.getCrystalNo());
//				}
//			}
//			if(!StringUtils.isEmpty(str) && !str.toString().equals("单晶【")){
//				return ResultGenerator.fail(str + "】未匹配到订单不存在边距信息");
//			}
//		}
//		if (crystalNoByTrayNo.size() < 1 || crystalNoByTrayNo == null) {
//           // throw new RuntimeException("该托盘无绑定单晶信息");
//
//			return ResultGenerator.success(crystalNoByTrayNo);
//        }
		// 前端需要配置返回一个空集合 不返回报错信息
		return ResultGenerator.success(crystalNoByTrayNoV2);
	}

	//@ApiOperation(value = "通过托盘号找到对应单晶")
	//@GetMapping("/getCrystal/{trayNo}")
	//public Result getCrystalNo(@PathVariable@ApiParam(value = "trayNo") String trayNo) {
	//					//get(@PathVariable @ApiParam(value="ProductionBindingTrayid") Long id) {
	//	List<String> crystalNoByTrayNo = this.productionBindingTrayService.findCrystalNoByTrayNo(trayNo);
	//	return ResultGenerator.success(crystalNoByTrayNo);
	//}

	@ApiOperation(value = "托盘解绑单晶接口")
	@PostMapping("/unbinding")
	public Result unBinding(@RequestBody @Valid @ApiParam(value = "解绑参数对象") BindingCrystalDto dto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}

		return this.productionBindingTrayService.unbundlingCrystal(dto);
	}



	public ProductionBindingTrayDto toLazyDto(ProductionBindingTray entity) {
		return modelMapper.map(entity, ProductionBindingTrayDto.class);
	}

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

	public ProductionBindingTray fromDto(ProductionBindingTrayDto dto) {
		return modelMapper.map(dto, ProductionBindingTray.class);
	}


}
