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

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.ServletRequest;
import javax.validation.Valid;

import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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.base.workinprocess.entity.WipStorage;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.yb.production.dto.ConfigureAlloyDto;
import com.sw.mes.yb.production.entity.ConfigureAlloy;
import com.sw.mes.yb.production.service.ConfigureAlloyService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/productionConfigureAlloy")
@Slf4j
@Api(description = "配合金接口")
public class ConfigureAlloyController {
	@Autowired
	ModelMapper modelMapper;
	@Autowired
	private ConfigureAlloyService configureAlloyService;
    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;
    @Autowired
    private EquipmentService equipmentService;

	@ApiOperation(value = "分页查询配合金列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<ConfigureAlloyDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<ConfigureAlloy> specification = DynamicSpecifications.bySearchFilter(request, ConfigureAlloy.class);
    	Page<ConfigureAlloy> page = configureAlloyService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<ConfigureAlloyDto> 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<ConfigureAlloyDto>> listAll(ServletRequest request) {
		Specification<ConfigureAlloy> specification = DynamicSpecifications.bySearchFilter(request, ConfigureAlloy.class);
		List<ConfigureAlloy> configureAlloys = configureAlloyService.findByExampleSort(specification, null);
		List<ConfigureAlloyDto> configureAlloyDtos = configureAlloys.stream()
					.map(configureAlloy -> toLazyDto(configureAlloy))
					.collect(Collectors.toList());
		return ResultGenerator.success(configureAlloyDtos);
	}

	@ApiOperation(value = "配合金详细信息")
	@GetMapping("/{id}")
	public Result<ConfigureAlloyDto> get(@PathVariable @ApiParam(value="配合金id") Long id) {
		ConfigureAlloy configureAlloy = configureAlloyService.get(id);
		if (null == configureAlloy) {
            return ResultGenerator.fail("该配合金不存在");
        }
		return ResultGenerator.success(toEagerDto(configureAlloy));
	}



    @ApiOperation(value = "根据设备号查询炉次号")
    @GetMapping("/getLotno")
    public Result<String> getLotno(@ApiParam(value = "设备号") String equipmentCode) {
        Equipment equipment = equipmentService.findByCode(equipmentCode);
        if (equipment == null) {
            return ResultGenerator.fail("设备号不存在");
        }
        PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByEquipmentIdAndOrderTypeAndStatus(equipment.getId(), EnumValuesFactory.PlanProcessingOrderOrderType.炉次.getKey(), EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey());
        if (planProcessingOrder != null) {
            String code = planProcessingOrder.getCode();
            return ResultGenerator.success(code);
        } else {
            return ResultGenerator.fail(equipmentCode + "设备没有正在运行的炉次");
        }
    }


	@ApiOperation(value = "创建配合金")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "配合金对象") ConfigureAlloyDto configureAlloyDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		ConfigureAlloy configureAlloy = fromDto(configureAlloyDto);
		configureAlloy.setOperationTime(new Date());
		configureAlloy.setApplyCreate(new Date());
		configureAlloyService.saveOrUpdate(configureAlloy);
		return ResultGenerator.success();
	}

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

	public ConfigureAlloyDto toLazyDto(ConfigureAlloy entity) {
		return modelMapper.map(entity, ConfigureAlloyDto.class);
	}

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

	public ConfigureAlloy fromDto(ConfigureAlloyDto dto) {
		return modelMapper.map(dto, ConfigureAlloy.class);
	}


}
