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

import cn.hutool.core.exceptions.ExceptionUtil;
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.yb.accessory.dto.AccessoryReturnDto;
import com.sw.mes.yb.accessory.dto.ReturnCreateDto;
import com.sw.mes.yb.accessory.entity.AccessoryReturn;
import com.sw.mes.yb.accessory.service.AccessoryReturnService;
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("/accessoryReturn")
@Slf4j
@Api(description = "辅料退库记录接口")
public class AccessoryReturnController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private AccessoryReturnService accessoryReturnService;

	@ApiOperation(value = "分页查询辅料退库记录列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_material.codes", value = "料号", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_goodsCode", value = "热场条码", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_orderNum", value = "退料单号", dataType = "string", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<AccessoryReturnDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<AccessoryReturn> specification = DynamicSpecifications.bySearchFilter(request, AccessoryReturn.class);
    	Page<AccessoryReturn> page = accessoryReturnService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<AccessoryReturnDto> 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<AccessoryReturnDto>> listAll(ServletRequest request) {
		Specification<AccessoryReturn> specification = DynamicSpecifications.bySearchFilter(request, AccessoryReturn.class);
		List<AccessoryReturn> accessoryReturns = accessoryReturnService.findByExampleSort(specification, null);
		List<AccessoryReturnDto> accessoryReturnDtos = accessoryReturns.stream()
					.map(accessoryReturn -> toLazyDto(accessoryReturn))
					.collect(Collectors.toList());
		return ResultGenerator.success(accessoryReturnDtos);
	}

	@ApiOperation(value = "辅料退库记录详细信息")
	@GetMapping("/{id}")
	public Result<AccessoryReturnDto> get(@PathVariable @ApiParam(value="辅料退库记录id") Integer id) {
		AccessoryReturn accessoryReturn = accessoryReturnService.get(id);
		if (null == accessoryReturn) {
            return ResultGenerator.fail("该辅料退库记录不存在");
        }
		return ResultGenerator.success(toEagerDto(accessoryReturn));
	}

	@ApiOperation(value = "创建辅料退库记录")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "辅料退库记录对象") ReturnCreateDto accessoryReturnDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
        try {
            accessoryReturnService.accessoryReturn(accessoryReturnDto);
            return ResultGenerator.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(ExceptionUtil.stacktraceToString(e));
            return ResultGenerator.fail(e.getMessage());
        }
	}

    @ApiOperation(value = "更新辅料退库记录")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "辅料退库记录") AccessoryReturnDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
            AccessoryReturn entity = accessoryReturnService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            AccessoryReturn entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			accessoryReturnService.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) {
				accessoryReturnService.delete(id);
		}
		return ResultGenerator.success();
	}

	public AccessoryReturnDto toLazyDto(AccessoryReturn entity) {
        AccessoryReturnDto accessoryReturnDto = modelMapper.map(entity, AccessoryReturnDto.class);
        if (entity.getState() != null) {
            accessoryReturnDto.setState(EnumValues.AccessoryReturnStatus.valueOf(entity.getState()).getValue());
        }
        if (entity.getUseTime() != null){
            accessoryReturnDto.setEquipmentAccessoryUseTime(Double.parseDouble(entity.getUseTime().toString()));
        }
        return accessoryReturnDto;
    }

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

	public AccessoryReturn fromDto(AccessoryReturnDto dto) {
		return modelMapper.map(dto, AccessoryReturn.class);
	}


}
