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

import com.sw.mes.yb.accessory.dto.AccessoryOrderDto;
import com.sw.mes.yb.accessory.entity.AccessoryOrder;
import com.sw.mes.yb.accessory.service.AccessoryOrderService;
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.BeanUtil;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
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.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/accessoryOrder")
@Slf4j
@Api(description = "热场更换记录接口")
public class AccessoryOrderController {
	@Autowired
    ModelMapper modelMapper;

	@Autowired
	private AccessoryOrderService accessoryOrderService;

	//各热场件平均使用天数和定额天数对比（正常损耗）
	@ApiOperation(value = "各热场件平均使用天数和定额天数对比（正常损耗）")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "accessoryTypeName", value = "热场名称", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", dataType = "String"),
	})
	@RequestMapping(value="/accessoryLifeAvg", method= RequestMethod.GET)
	public Result accessoryLifeAvg(String accessoryTypeName,String startTime,String endTime){
		if(startTime==null||"".equals(startTime)){
			return ResultGenerator.fail("请选择开始时间");
		}
		if(endTime==null||"".equals(endTime)){
			return ResultGenerator.fail("请选择结束时间");
		}
		List<Map<String,Object>> list = accessoryOrderService.accessoryLifeAvg(accessoryTypeName,startTime,endTime);
		return ResultGenerator.success(list);
	}
	//同一热场件不同厂家寿命对比（正常损耗）
	@ApiOperation(value = "同一热场件不同厂家寿命对比（正常损耗）")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "accessoryTypeName", value = "热场名称", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", dataType = "String"),
	})
	@RequestMapping(value="/accessorySupplierLifeAvg", method= RequestMethod.GET)
	public Result accessorySupplierLifeAvg(String accessoryTypeName,String startTime,String endTime){
		if(startTime==null||"".equals(startTime)){
			return ResultGenerator.fail("请选择开始时间");
		}
		if(endTime==null||"".equals(endTime)){
			return ResultGenerator.fail("请选择结束时间");
		}
		if(accessoryTypeName==null||"".equals(accessoryTypeName)){
			return ResultGenerator.fail("请输入热场更换名称");
		}
		List<Map<String,Object>> list = accessoryOrderService.accessorySupplierLifeAvg(accessoryTypeName,startTime,endTime);
		return ResultGenerator.success(list);
	}
	//质量问题损失占比
	@ApiOperation(value = "质量问题损失占比")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "accessoryTypeName", value = "热场名称", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", dataType = "String"),
	})
	@RequestMapping(value="/accessoryQuality", method= RequestMethod.GET)
	public Result accessoryQuality(String accessoryTypeName,String startTime,String endTime){
		if(startTime==null||"".equals(startTime)){
			return ResultGenerator.fail("请选择开始时间");
		}
		if(endTime==null||"".equals(endTime)){
			return ResultGenerator.fail("请选择结束时间");
		}
		if(accessoryTypeName==null||"".equals(accessoryTypeName)){
			return ResultGenerator.fail("请输入热场更换名称");
		}
		List<Map<String,Object>> list = accessoryOrderService.accessoryQuality(accessoryTypeName,startTime,endTime);
		return ResultGenerator.success(list);
	}
	@ApiOperation(value = "分页查询热场更换记录列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_deviceNo", value = "设备编号", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_GTE_createDate", value = "开始更换时间", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LTE_createDate", value = "结束更换时间", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_createUser", value = "更换人", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_orgGoodsCode", value = "热场条码（前）", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_targetGoodsCode", value = "热场条码（后）", dataType = "string", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<AccessoryOrderDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<AccessoryOrder> specification = DynamicSpecifications.bySearchFilter(request, AccessoryOrder.class);
    	Page<AccessoryOrder> page = accessoryOrderService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<AccessoryOrderDto> 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<AccessoryOrderDto>> listAll(ServletRequest request) {
		Specification<AccessoryOrder> specification = DynamicSpecifications.bySearchFilter(request, AccessoryOrder.class);
		List<AccessoryOrder> accessoryOrders = accessoryOrderService.findByExampleSort(specification, null);
		List<AccessoryOrderDto> accessoryOrderDtos = accessoryOrders.stream()
					.map(accessoryOrder -> toLazyDto(accessoryOrder))
					.collect(Collectors.toList());
		return ResultGenerator.success(accessoryOrderDtos);
	}

	@ApiOperation(value = "热场更换记录详细信息")
	@GetMapping("/{id}")
	public Result<AccessoryOrderDto> get(@PathVariable @ApiParam(value="热场更换记录id") Long id) {
		AccessoryOrder accessoryOrder = accessoryOrderService.get(id);
		if (null == accessoryOrder) {
            return ResultGenerator.fail("该热场更换记录不存在");
        }
		return ResultGenerator.success(toEagerDto(accessoryOrder));
	}

	@ApiOperation(value = "创建热场更换记录")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "热场更换记录对象") AccessoryOrderDto accessoryOrderDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		AccessoryOrder accessoryOrder = fromDto(accessoryOrderDto);
		accessoryOrder.setCreateUserId(BaseContextHandler.getUserID());
		accessoryOrder.setCreateUser(BaseContextHandler.getUsername());
		accessoryOrder.setCreateDate(new Date());
		accessoryOrderService.saveOrUpdate(accessoryOrder);
		return ResultGenerator.success();
	}

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

	public AccessoryOrderDto toLazyDto(AccessoryOrder entity) {
		return modelMapper.map(entity, AccessoryOrderDto.class);
	}

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

	public AccessoryOrder fromDto(AccessoryOrderDto dto) {
		return modelMapper.map(dto, AccessoryOrder.class);
	}

}
