package com.sw.mes.fineReport.controller;

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.fineReport.dto.FineReportDataFbDto;
import com.sw.mes.fineReport.entity.FineReportDataFb;
import com.sw.mes.fineReport.service.FineReportDataFbService;
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 org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/fineReportDataFb")
@Slf4j
@Api(description = "方棒报表数据接口")
public class FineReportDataFbController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private FineReportDataFbService fineReportDataFbService;

	@ApiOperation(value = "分页查询方棒报表数据列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<FineReportDataFbDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<FineReportDataFb> specification = DynamicSpecifications.bySearchFilter(request, FineReportDataFb.class);
    	Page<FineReportDataFb> page = fineReportDataFbService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<FineReportDataFbDto> 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<FineReportDataFbDto>> listAll(ServletRequest request) {
		Specification<FineReportDataFb> specification = DynamicSpecifications.bySearchFilter(request, FineReportDataFb.class);
		List<FineReportDataFb> fineReportDataFbs = fineReportDataFbService.findByExampleSort(specification, null);
		List<FineReportDataFbDto> fineReportDataFbDtos = fineReportDataFbs.stream()
					.map(fineReportDataFb -> toLazyDto(fineReportDataFb))
					.collect(Collectors.toList());
		return ResultGenerator.success(fineReportDataFbDtos);
	}

	@ApiOperation(value = "方棒报表数据详细信息")
	@GetMapping("/{id}")
	public Result<FineReportDataFbDto> get(@PathVariable @ApiParam(value="方棒报表数据id") Long id) {
		FineReportDataFb fineReportDataFb = fineReportDataFbService.get(id);
		if (null == fineReportDataFb)
			return ResultGenerator.fail("该方棒报表数据不存在");
		return ResultGenerator.success(toEagerDto(fineReportDataFb));
	}

	@ApiOperation(value = "创建方棒报表数据")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "方棒报表数据对象") FineReportDataFbDto fineReportDataFbDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		FineReportDataFb fineReportDataFb = fromDto(fineReportDataFbDto);
		fineReportDataFb.setCreateTime(new Date());
		if (!"开方机,磨削机,方棒设备".contains(fineReportDataFb.getEquipmentType())){
			return ResultGenerator.fail("设备类型格式错误！");
		}
		if (!"一模块,二模块,三模块,四模块".contains(fineReportDataFb.getModule())){
			return ResultGenerator.fail("模块格式错误！");
		}
		List<FineReportDataFb> info = fineReportDataFbService.findByModuleAndDateTimeAndEquipmentTypeAndDataType(fineReportDataFb.getModule(), fineReportDataFb.getDateTime(), fineReportDataFb.getEquipmentType(), fineReportDataFb.getDataType());
		if (info != null && info.size() > 0){
			return ResultGenerator.fail("当日数据重复！");
		}
		fineReportDataFbService.saveOrUpdate(fineReportDataFb);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新方棒报表数据")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "方棒报表数据") FineReportDataFbDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            FineReportDataFb entity = fineReportDataFbService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            FineReportDataFb entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			entity.setUpdateTime(new Date());
			if (!"开方机,磨削机,方棒设备".contains(entity.getEquipmentType())){
				return ResultGenerator.fail("设备类型格式错误！");
			}
			if (!"一模块,二模块,三模块,四模块".contains(entity.getModule())){
				return ResultGenerator.fail("模块格式错误！");
			}
			List<FineReportDataFb> info = fineReportDataFbService.findByModuleAndDateTimeAndEquipmentTypeAndDataType(entity.getModule(), entity.getDateTime(), entity.getEquipmentType(), entity.getDataType());
			if (info != null && info.size() > 0 && info.get(0).getId() != entity.getId()){
				return ResultGenerator.fail("当日数据重复！");
			}
			fineReportDataFbService.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 Long[] ids) {
		for (Long id : ids) {
			fineReportDataFbService.delete(id);
		}
		return ResultGenerator.success();
	}

	@ApiOperation(value = "导入数据")
	@PostMapping("/excelImport")
	public @ResponseBody
	Result excelImport(MultipartFile file) throws Exception {

		try {
			fineReportDataFbService.readExcelFile(file);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success("数据导入成功!");
	}

	public FineReportDataFbDto toLazyDto(FineReportDataFb entity) {
		return modelMapper.map(entity, FineReportDataFbDto.class);
	}

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

	public FineReportDataFb fromDto(FineReportDataFbDto dto) {
		return modelMapper.map(dto, FineReportDataFb.class);
	}


}
