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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
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.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.fb.accessory.dto.*;
import com.sw.mes.fb.accessory.entity.FbEquipmentAccessory;
import com.sw.mes.fb.accessory.service.FbEquipmentAccessoryService;
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.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/fbEquipmentAccessory")
@Slf4j
@Api(description = "方棒辅料监控接口")
public class FbEquipmentAccessoryController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private FbEquipmentAccessoryService fbEquipmentAccessoryService;

	@ApiOperation(value = "分页查询方棒辅料监控列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<FbEquipmentAccessoryDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<FbEquipmentAccessory> specification = DynamicSpecifications.bySearchFilter(request, FbEquipmentAccessory.class);
    	Page<FbEquipmentAccessory> page = fbEquipmentAccessoryService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<FbEquipmentAccessoryDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}

    @ApiOperation(value = "new分页查询方棒辅料监控列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/newListByPage")
    public Result<ResponsePage<FbEquipmentAccessoryDto>> newListByPage(ServletRequest request, @ApiIgnore RequestPage requestPage, NewAccessoryListByPageParamDto paramDto) {
        requestPage.setOrderField("b.yujing");
        requestPage.setOrderDirection("DESC");
        Page<Map<String, Object>> page = fbEquipmentAccessoryService.newListByPage(paramDto, PageUtil.createPageable(requestPage));
        List<NewAccessoryDto> dtos = page.getContent().stream()
                .map(entity -> JSON.parseObject(JSON.toJSONString(entity), new TypeReference<NewAccessoryDto>(){}))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

	@ApiOperation(value = "获取所有方棒辅料监控")
	@GetMapping("/listAll")
	public Result<List<FbEquipmentAccessoryDto>> listAll(ServletRequest request) {
		Specification<FbEquipmentAccessory> specification = DynamicSpecifications.bySearchFilter(request, FbEquipmentAccessory.class);
		List<FbEquipmentAccessory> fbEquipmentAccessorys = fbEquipmentAccessoryService.findByExampleSort(specification, null);
		List<FbEquipmentAccessoryDto> fbEquipmentAccessoryDtos = fbEquipmentAccessorys.stream()
					.map(fbEquipmentAccessory -> toLazyDto(fbEquipmentAccessory))
					.collect(Collectors.toList());
		return ResultGenerator.success(fbEquipmentAccessoryDtos);
	}

	@ApiOperation(value = "方棒辅料监控详细信息")
	@GetMapping("/{id}")
	public Result<FbEquipmentAccessoryDto> get(@PathVariable @ApiParam(value="方棒辅料监控id") Long id) {
		FbEquipmentAccessory fbEquipmentAccessory = fbEquipmentAccessoryService.get(id);
		if (null == fbEquipmentAccessory)
			return ResultGenerator.fail("该方棒辅料监控不存在");
		return ResultGenerator.success(toEagerDto(fbEquipmentAccessory));
	}

	@ApiOperation(value = "创建方棒辅料监控")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "方棒辅料监控对象") FbEquipmentAccessoryCreatDto createDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
        fbEquipmentAccessoryService.createMonitor(createDto);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更换方棒辅料监控")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "方棒辅料监控") FbEquipmentAccessoryUpdateDto updateDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (updateDto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            FbEquipmentAccessory entity = fbEquipmentAccessoryService.get(updateDto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            fbEquipmentAccessoryService.updateMonitor(updateDto);
            return ResultGenerator.success();
        } catch (Exception e) {
            e.printStackTrace();
            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) {
            FbEquipmentAccessory equipmentAccessory = fbEquipmentAccessoryService.get(id);
            equipmentAccessory.setUpdateDate(new Date());
            equipmentAccessory.setOperateUser(BaseContextHandler.getUsername());
            equipmentAccessory.setOperateUserId(BaseContextHandler.getUserID());
            equipmentAccessory.setDeleted(1);
            fbEquipmentAccessoryService.saveOrUpdate(equipmentAccessory);
        }
		return ResultGenerator.success();
	}

    @ApiOperation(value = "方棒辅料报表")
    @GetMapping("/fbAccessoryReport")
    public Result fbAccessoryReport(FbAccessoryReportParamDto paramDto,@ApiIgnore RequestPage requestPage){
        Page<Map<String, Object>> page;
        if ("jdjhl".equals(paramDto.getSign())){
            page = fbEquipmentAccessoryService.jdjhl(paramDto, PageUtil.createPageable(requestPage));
        }else if ("jdjqgx".equals(paramDto.getSign())){
            page = fbEquipmentAccessoryService.jdjqgx(paramDto, PageUtil.createPageable(requestPage));
        }else if ("mxjsl".equals(paramDto.getSign())){
            page = fbEquipmentAccessoryService.mxjsl(paramDto, PageUtil.createPageable(requestPage));
        }else if ("mxjxzsl".equals(paramDto.getSign())){
            page = fbEquipmentAccessoryService.mxjxzsl(paramDto, PageUtil.createPageable(requestPage));
        }else if ("qfjhl".equals(paramDto.getSign())){
            page = fbEquipmentAccessoryService.qfjhl(paramDto, PageUtil.createPageable(requestPage));
        }else if ("qfjqgx".equals(paramDto.getSign())){
            page = fbEquipmentAccessoryService.qfjqgx(paramDto, PageUtil.createPageable(requestPage));
        }else {
            return ResultGenerator.fail("未知标识符！");
        }
        List<FbAccessoryReportDto> dtos = page.getContent().stream()
                .map(entity -> JSON.parseObject(JSON.toJSONString(entity), new TypeReference<FbAccessoryReportDto>(){}))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "方棒辅料报表")
    @GetMapping("/fbAccessoryReportDetail")
    public Result fbAccessoryReportDetail(FbAccessoryReportDetailParamDto paramDto, @ApiIgnore RequestPage requestPage){
        List<Map<String, Object>> list;
        if ("jdjhl".equals(paramDto.getSign())){
            list = fbEquipmentAccessoryService.jdjhlDetail(paramDto);
        }else if ("jdjqgx".equals(paramDto.getSign())){
            list = fbEquipmentAccessoryService.jdjqgxDetail(paramDto);
        }else if ("mxjsl".equals(paramDto.getSign())){
            list = fbEquipmentAccessoryService.mxjslDetail(paramDto);
        }else if ("mxjxzsl".equals(paramDto.getSign())){
            list = fbEquipmentAccessoryService.mxjxzslDetail(paramDto);
        }else if ("qfjhl".equals(paramDto.getSign())){
            list = fbEquipmentAccessoryService.qfjhlDetail(paramDto);
        }else if ("qfjqgx".equals(paramDto.getSign())){
            list = fbEquipmentAccessoryService.qfjqgxDetail(paramDto);
        }else {
            return ResultGenerator.fail("未知标识符！");
        }
        List<FbAccessoryReportDetailDto> collect = list.stream().map(item -> JSON.parseObject(JSON.toJSONString(item), new TypeReference<FbAccessoryReportDetailDto>() {
        })).collect(Collectors.toList());
        return ResultGenerator.success(collect);
    }

	public FbEquipmentAccessoryDto toLazyDto(FbEquipmentAccessory entity) {
		return modelMapper.map(entity, FbEquipmentAccessoryDto.class);
	}

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

	public FbEquipmentAccessory fromDto(FbEquipmentAccessoryDto dto) {
		return modelMapper.map(dto, FbEquipmentAccessory.class);
	}

}
