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

import com.sw.mes.base.erp.dto.ErpOrderDto;
import com.sw.mes.core.dto.PlanWaterLineManageRecordDto;
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.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.inspect.entity.YbInspectData;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.yb.plan.dto.PlanWaterLineManageDto;
import com.sw.mes.yb.plan.dto.PlanWaterLineManageObj;
import com.sw.mes.yb.plan.entity.PlanWaterLineManage;
import com.sw.mes.yb.plan.entity.PlanWaterLineManageRecord;
import com.sw.mes.yb.plan.service.PlanWaterLineManageService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
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.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/planWaterLineManage")
@Slf4j
@Api(description = "水位拉动配置接口")
public class PlanWaterLineManageController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private PlanWaterLineManageService planWaterLineManageService;

	@Autowired
    private YbInspectDataService ybInspectDataService;

	@ApiOperation(value = "分页查询水位拉动列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<PlanWaterLineManageDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<PlanWaterLineManage> specification = DynamicSpecifications.bySearchFilter(request, PlanWaterLineManage.class);
    	Page<PlanWaterLineManage> page = planWaterLineManageService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<PlanWaterLineManageDto> list = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		ResponsePage responsePage = new ResponsePage(list, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}

	@ApiOperation(value = "获取所有圆棒拼棒")
	@GetMapping("/listAll")
	public Result<List<PlanWaterLineManageDto>> listAll(ServletRequest request) {
		Specification<PlanWaterLineManage> specification = DynamicSpecifications.bySearchFilter(request, PlanWaterLineManage.class);
		List<PlanWaterLineManage> planWaterLineManages = planWaterLineManageService.findByExampleSort(specification, null);
		List<PlanWaterLineManageDto> planWaterLineManageDto = planWaterLineManages.stream()
					.map(planWaterLineManage -> toLazyDto(planWaterLineManage))
					.collect(Collectors.toList());
		return ResultGenerator.success(planWaterLineManageDto);
	}

	@ApiOperation(value = "水位拉动详细信息")
	@GetMapping("/{id}")
	public Result<PlanWaterLineManageObj> get(@PathVariable @ApiParam(value="水位拉动id") Long id) {
		PlanWaterLineManage planWaterLineManage = planWaterLineManageService.get(id);
		List<PlanWaterLineManageRecord> planWaterLineManageRecords = planWaterLineManageService.findPlanWaterLineById(id);
		if (planWaterLineManageRecords == null || planWaterLineManageRecords.size() ==0) {
            return ResultGenerator.fail("该水位拉动信息不存在");
        }
		if (null == planWaterLineManage) {
            return ResultGenerator.fail("该水位拉动信息不存在");
        }
		PlanWaterLineManageObj obj = new PlanWaterLineManageObj();
		obj.setId(planWaterLineManage.getId());
		obj.setWaterLineName(planWaterLineManage.getWaterLineName());
		obj.setCacheNum(planWaterLineManage.getCacheNum());
		obj.setRecordList(planWaterLineManageRecords);
//		obj.setStrategy(planWaterLineManage.getStrategy());
		return ResultGenerator.success(obj);
	}

    @ApiOperation(value = "更新水位拉动")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "水位拉动") PlanWaterLineManageObj dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            return planWaterLineManageService.saveOrUpdateRecord(dto);
        } catch (Exception e) {
            log.error("更新水位拉动", 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) {
				planWaterLineManageService.delete(id);
		}
		return ResultGenerator.success();
	}


	@ApiOperation(value = "获取所有适合的水位订单")
	@GetMapping("/selectOrders")
	public Result<List<PlanWaterLineManageRecordDto>> selectOrders(String dopant, String conductiveType, String productTypeSecond, String sideLengthRange, String productLevel, BigDecimal resistanceLevel) {
		String ybLevel = "%" + productLevel + "%";
        String resistanceLevel1 = ybInspectDataService.getResistanceLevel(resistanceLevel);
        List<PlanWaterLineManageRecord> planWaterLineManageRecords = planWaterLineManageService.selectOrders(dopant, conductiveType, productTypeSecond, sideLengthRange, ybLevel, "%" + resistanceLevel1 + "%");

		List<PlanWaterLineManageRecordDto> dtos = planWaterLineManageRecords.stream().map(temp -> toEagerDto(temp)).collect(Collectors.toList());

		return ResultGenerator.success(dtos);
	}

	public PlanWaterLineManageDto toLazyDto(PlanWaterLineManage entity) {
		return modelMapper.map(entity, PlanWaterLineManageDto.class);
	}

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

	public PlanWaterLineManage fromDto(PlanWaterLineManageDto dto) {
		return modelMapper.map(dto, PlanWaterLineManage.class);
	}
	public PlanWaterLineManageRecordDto toEagerDto(PlanWaterLineManageRecord entity) {
		PlanWaterLineManageRecordDto dto = modelMapper.map(entity, PlanWaterLineManageRecordDto.class);
		return dto;
	}

}
