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

import com.alibaba.fastjson.JSONObject;
import com.sw.mes.core.enums.EnumValues;
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.utils.StringUtils;
import com.sw.mes.yb.pc.dto.TrayBindingRecordDto;
import com.sw.mes.yb.pc.dto.TrayUnbindingDto;
import com.sw.mes.yb.pc.entity.TrayBindingRecord;
import com.sw.mes.yb.pc.service.TrayBindingRecordService;
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("/trayBindingRecord")
@Slf4j
@Api(description = "托盘绑定详情接口")
public class TrayBindingRecordController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private TrayBindingRecordService trayBindingRecordService;

	@ApiOperation(value = "托盘绑定配置详情列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<TrayBindingRecordDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<TrayBindingRecord> specification = DynamicSpecifications.bySearchFilter(request, TrayBindingRecord.class);
    	Page<TrayBindingRecord> page = trayBindingRecordService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<TrayBindingRecordDto> 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<TrayBindingRecordDto>> listAll(ServletRequest request) {
		Specification<TrayBindingRecord> specification = DynamicSpecifications.bySearchFilter(request, TrayBindingRecord.class);
		List<TrayBindingRecord> trayBindingRecords = trayBindingRecordService.findByExampleSort(specification, null);
		List<TrayBindingRecordDto> trayBindingRecordDtos = trayBindingRecords.stream()
					.map(trayBindingRecord -> toLazyDto(trayBindingRecord))
					.collect(Collectors.toList());
		return ResultGenerator.success(trayBindingRecordDtos);
	}

	@ApiOperation(value = "托盘绑定详情详细信息")
	@GetMapping("/{id}")
	public Result<TrayBindingRecordDto> get(@PathVariable @ApiParam(value="托盘绑定详情id") Integer id) {
		TrayBindingRecord trayBindingRecord = trayBindingRecordService.get(id);
		if (null == trayBindingRecord) {
            return ResultGenerator.fail("该托盘绑定详情不存在");
        }
		return ResultGenerator.success(toEagerDto(trayBindingRecord));
	}

	@ApiOperation(value = "创建托盘绑定详情")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "托盘绑定详情对象") TrayBindingRecordDto trayBindingRecordDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		TrayBindingRecord trayBindingRecord = fromDto(trayBindingRecordDto);
		trayBindingRecordService.saveOrUpdate(trayBindingRecord);
		return ResultGenerator.success();
	}

	@ApiOperation(value = "托盘绑定")
	@PostMapping("/trayBinding")
	public Result trayBinding(@RequestBody @Valid @ApiParam(value = "托盘绑定详情对象") TrayBindingRecordDto trayBindingRecordDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		TrayBindingRecord trayBindingRecord = fromDto(trayBindingRecordDto);
		//判断托盘是否存在绑定记录
		List<TrayBindingRecord> byCodeAndStatus = trayBindingRecordService.findByCodeAndStatus(trayBindingRecord.getCode(), trayBindingRecord.getStatus());
		if (null != byCodeAndStatus && byCodeAndStatus.size() != 0){
			return ResultGenerator.fail("该托盘存在绑定单晶！");
		}

		//判断单晶是否存在绑定记录
		List<TrayBindingRecord> bySectionNoStatus = trayBindingRecordService.findBySectionNoAndStatus(trayBindingRecord.getSectionNo(), trayBindingRecord.getStatus());
		if (null != bySectionNoStatus && bySectionNoStatus.size() != 0){
			return ResultGenerator.fail("该单晶已绑定！");
		}
		//查询单晶数据

		trayBindingRecord.setStatus(EnumValues.trayBindingRecordStatus.BUNDLING.getKey());
		trayBindingRecordService.saveOrUpdate(trayBindingRecord);
		return ResultGenerator.success();
	}

	@ApiOperation(value = "托盘解绑")
	@PostMapping("/trayUnbinding")
	public Result trayUnbinding(@RequestBody @Valid @ApiParam(value = "托盘绑定详情对象") TrayUnbindingDto trayBindingRecordDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		try {
			trayBindingRecordService.trayUnbinding(trayBindingRecordDto);
			return ResultGenerator.success();
		}catch (Exception e){
			return ResultGenerator.fail(e.getMessage());
		}
	}

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

	public TrayBindingRecordDto toLazyDto(TrayBindingRecord entity) {
		return modelMapper.map(entity, TrayBindingRecordDto.class);
	}

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

	public TrayBindingRecord fromDto(TrayBindingRecordDto dto) {
		return modelMapper.map(dto, TrayBindingRecord.class);
	}


}
