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

import com.sw.mes.core.context.BaseContextHandler;
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 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.domain.Sort;
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.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import com.sw.mes.yb.report.entity.BrokenBractBase;
import com.sw.mes.yb.report.dto.BrokenBractBaseDto;
import com.sw.mes.yb.report.service.BrokenBractBaseService;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/brokenBractBase")
@Slf4j
@Api(description = "断苞基础表接口接口")
public class BrokenBractBaseController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private BrokenBractBaseService brokenBractBaseService;

	@ApiOperation(value = "分页查询断苞基础表接口列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_series", value = "系列", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_GTE_dateTime", value = "日期起始值", dataType = "date", paramType = "query"),
		@ApiImplicitParam(name = "search_LT_dateTime", value = "日期终止值", dataType = "date", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_deviceNo", value = "炉台", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_crystalLengthArea", value = "长度区间", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_specs", value = "规格", dataType = "string", paramType = "query"),

	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<BrokenBractBaseDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<BrokenBractBase> specification = DynamicSpecifications.bySearchFilter(request, BrokenBractBase.class);
    	Page<BrokenBractBase> page = brokenBractBaseService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<BrokenBractBaseDto> 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<BrokenBractBaseDto>> listAll(ServletRequest request) {
		Specification<BrokenBractBase> specification = DynamicSpecifications.bySearchFilter(request, BrokenBractBase.class);
		List<BrokenBractBase> brokenBractBases = brokenBractBaseService.findByExampleSort(specification, null);
		List<BrokenBractBaseDto> brokenBractBaseDtos = brokenBractBases.stream()
					.map(brokenBractBase -> toLazyDto(brokenBractBase))
					.collect(Collectors.toList());
		return ResultGenerator.success(brokenBractBaseDtos);
	}

	@ApiOperation(value = "断苞基础表接口详细信息")
	@GetMapping("/{id}")
	public Result<BrokenBractBaseDto> get(@PathVariable @ApiParam(value="断苞基础表接口id") Long id) {
		BrokenBractBase brokenBractBase = brokenBractBaseService.get(id);
		if (null == brokenBractBase)
			return ResultGenerator.fail("该断苞基础表接口不存在");
		return ResultGenerator.success(toEagerDto(brokenBractBase));
	}

	@ApiOperation(value = "创建断苞基础表接口")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "断苞基础表接口对象") BrokenBractBaseDto brokenBractBaseDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		BrokenBractBase brokenBractBase = fromDto(brokenBractBaseDto);
		brokenBractBaseService.saveOrUpdate(brokenBractBase);
		return ResultGenerator.success();
	}

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

	@ApiOperation(value = "断苞基础表-导出")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "search_LIKE_series", value = "系列", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_GTE_dateTime", value = "日期起始值", dataType = "date", paramType = "query"),
		@ApiImplicitParam(name = "search_LT_dateTime", value = "日期终止值", dataType = "date", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_deviceNo", value = "炉台", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_crystalLengthArea", value = "长度区间", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_specs", value = "规格", dataType = "string", paramType = "query"),
	})
	@GetMapping("/export")
	public void export(ServletRequest request, HttpServletResponse response) {
		try {
			Specification<BrokenBractBase> specification = DynamicSpecifications.bySearchFilter(request, BrokenBractBase.class);
			List<BrokenBractBase> brokenBractBases = brokenBractBaseService.findByExampleSort(specification, Sort.by(Sort.Direction.DESC,  "dateTime"));
			List<BrokenBractBaseDto> brokenBractBaseDtos = brokenBractBases.stream()
					.map(brokenBractBase -> toLazyDto(brokenBractBase))
					.collect(Collectors.toList());
			EasyExcelUtils.write(response, BrokenBractBaseDto.class, "断苞基础信息", "断苞基础表数据", brokenBractBaseDtos);
		} catch (Exception e) {
			throw new RuntimeException("导出断苞基础失败，错误信息：" + e.getMessage());
		}
	}

	public BrokenBractBaseDto toLazyDto(BrokenBractBase entity) {
		return modelMapper.map(entity, BrokenBractBaseDto.class);
	}

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

	public BrokenBractBase fromDto(BrokenBractBaseDto dto) {
		return modelMapper.map(dto, BrokenBractBase.class);
	}


}
