package com.sw.mes.fb.checkout.controller;

import com.alibaba.fastjson.JSON;
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.fb.checkout.dto.LossEntryRecordDto;
import com.sw.mes.fb.checkout.dto.LossRecordInfoDto;
import com.sw.mes.fb.checkout.dto.PdaLossRecordDto;
import com.sw.mes.fb.checkout.entity.LossEntryRecord;
import com.sw.mes.fb.checkout.service.LossEntryRecordService;
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("/lossEntryRecord")
@Slf4j
@Api(description = "损耗记录接口")
public class LossEntryRecordController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private LossEntryRecordService lossEntryRecordService;

	@ApiOperation(value = "分页查询损耗记录列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<LossEntryRecordDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<LossEntryRecord> specification = DynamicSpecifications.bySearchFilter(request, LossEntryRecord.class);
    	Page<LossEntryRecord> page = lossEntryRecordService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<LossEntryRecordDto> 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<LossEntryRecordDto>> listAll(ServletRequest request) {
		Specification<LossEntryRecord> specification = DynamicSpecifications.bySearchFilter(request, LossEntryRecord.class);
		List<LossEntryRecord> lossEntryRecords = lossEntryRecordService.findByExampleSort(specification, null);
		List<LossEntryRecordDto> lossEntryRecordDtos = lossEntryRecords.stream()
					.map(lossEntryRecord -> toLazyDto(lossEntryRecord))
					.collect(Collectors.toList());
		return ResultGenerator.success(lossEntryRecordDtos);
	}

	@ApiOperation(value = "损耗记录详细信息")
	@GetMapping("/{id}")
	public Result<LossEntryRecordDto> get(@PathVariable @ApiParam(value="损耗记录id") Long id) {
		LossEntryRecord lossEntryRecord = lossEntryRecordService.get(id);
		if (null == lossEntryRecord)
			return ResultGenerator.fail("该损耗记录不存在");
		return ResultGenerator.success(toEagerDto(lossEntryRecord));
	}

	@ApiOperation(value = "创建损耗记录")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "损耗记录对象") LossEntryRecordDto lossEntryRecordDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		LossEntryRecord lossEntryRecord = fromDto(lossEntryRecordDto);
		lossEntryRecordService.saveOrUpdate(lossEntryRecord);
		return ResultGenerator.success();
	}

	@ApiOperation(value = "PDA记录损耗")
	@PostMapping("/createByPda")
	public Result createByPda(@RequestBody @Valid @ApiParam(value = "损耗记录对象") PdaLossRecordDto pdaLossRecordDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		try {
			lossEntryRecordService.saveLossRecordByPda(pdaLossRecordDto);
		}catch (Exception e){
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success();
	}

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

	@ApiOperation(value = "PDA损耗录入校验是否符合报废")
	@PostMapping("/getVerifyScrapLoss")
	public Result getVerifyScrapLoss (@RequestBody @Valid @ApiParam(value = "损耗记录对象") PdaLossRecordDto pdaLossRecordDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		try {
			return lossEntryRecordService.getVerifyScrapLoss(pdaLossRecordDto);
		}catch (Exception e){
			return ResultGenerator.fail(e.getMessage());
		}
	}

	public LossEntryRecordDto toLazyDto(LossEntryRecord entity) {
		LossEntryRecordDto lossEntryRecordDto = modelMapper.map(entity, LossEntryRecordDto.class);
		/*if (StringUtils.isNotBlank(entity.getLossInfo())){
			List<LossRecordInfoDto> lossRecordInfoDtos= JSON.parseArray(entity.getLossInfo(), LossRecordInfoDto.class);
			StringBuilder lossType = new StringBuilder();
			StringBuilder lossLength = new StringBuilder();
			for (LossRecordInfoDto lossRecordInfoDto : lossRecordInfoDtos){
				lossType.append(lossRecordInfoDto.getLossType()).append(" ");
				lossLength.append(lossRecordInfoDto.getLossLength()).append(" ");
			}
			lossEntryRecordDto.setLossType(lossType.toString());
			lossEntryRecordDto.setLossLength(lossLength.toString());
		}*/
		return lossEntryRecordDto;
	}

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

	public LossEntryRecord fromDto(LossEntryRecordDto dto) {
		return modelMapper.map(dto, LossEntryRecord.class);
	}


}
