package com.sw.mes.agv.controller;

import com.sw.mes.agv.dto.MonitorRechargeDto;
import com.sw.mes.agv.dto.RechargeMixDto;
import com.sw.mes.agv.entity.MonitorEquipmentRecharge;
import com.sw.mes.agv.entity.RechargeArtBagItem;
import com.sw.mes.agv.service.MonitorEquipmentRechargeService;
import com.sw.mes.agv.service.RechargeArtBagItemService;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.entity.SearchFilter;
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 io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 java.util.List;
import java.util.stream.Collectors;

/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/monitorEquipmentRecharge")
@Slf4j
@Api(description = "复投列表")
public class MonitorEquipmentRechargeController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private MonitorEquipmentRechargeService rechargeService;

    @Autowired
    private RechargeArtBagItemService rechargeArtBagItemService;

    @ApiOperation(value = "分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<MonitorRechargeDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<MonitorEquipmentRecharge> specification = DynamicSpecifications.bySearchFilter(request, MonitorEquipmentRecharge.class,
                new SearchFilter("rechargeWeight", SearchFilter.Operator.GT, 0));
        Page<MonitorEquipmentRecharge> page = rechargeService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<MonitorRechargeDto> dtos = page.getContent().stream()
                .map(entity -> toEagerDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有列表")
    @GetMapping("/listAll")
    public Result<List<MonitorRechargeDto>> listAll(ServletRequest request) {
        Specification<MonitorEquipmentRecharge> specification = DynamicSpecifications.bySearchFilter(request, MonitorEquipmentRecharge.class);
        List<MonitorEquipmentRecharge> entitys = rechargeService.findByExampleSort(specification, null);
        List<MonitorRechargeDto> dtos = entitys.stream()
                .map(item -> toEagerDto(item))
                .collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    @ApiOperation(value = "详细信息")
    @GetMapping("/{id}")
    public Result<MonitorRechargeDto> get(@PathVariable @ApiParam(value = "设备类型id") Integer id) {
        MonitorEquipmentRecharge storeInputBill = rechargeService.get(id);
        if (null == storeInputBill) {
            return ResultGenerator.fail("该对象不存在");
        }
        return ResultGenerator.success(toEagerDto(storeInputBill));
    }

    @ApiOperation(value = "创建搭配方案")
    @PostMapping("/create")
    public Result create(@RequestBody @ApiParam(value = "Dto对象") MonitorRechargeDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (StringUtils.isBlank(dto.getName())) {
            return ResultGenerator.fail("设备编号不能为空！");
        }
        if (dto.getMixDtos() == null || dto.getMixDtos().size() == 0) {
            return ResultGenerator.fail("搭配方案不能为空！");
        }
        if (StringUtils.isBlank(dto.getMixUser())) {
            dto.setMixUser(BaseContextHandler.getUsername());
        }
        try {
            rechargeService.saveOrUpdateArtBag(dto);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新搭配方案")
    @PostMapping("/update")
    public Result update(@RequestBody @ApiParam(value = "Dto对象") MonitorRechargeDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (StringUtils.isBlank(dto.getName())) {
            return ResultGenerator.fail("设备编号不能为空！");
        }
        if (dto.getMixDtos() == null || dto.getMixDtos().size() == 0) {
            return ResultGenerator.fail("搭配方案不能为空！");
        }
        if (StringUtils.isBlank(dto.getMixUser())) {
            dto.setMixUser(BaseContextHandler.getUsername());
        }
        try {
            rechargeService.saveOrUpdateArtBag(dto);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "获取搭配方案")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceNo", value = "设备编号", dataType = "String", paramType = "query")
    })
    @PostMapping("/getMixInfo")
    public Result getMixInfo(String deviceNo) {
        if (deviceNo == null) {
            return ResultGenerator.fail("设备编号不能为空");
        }
        MonitorEquipmentRecharge recharge = rechargeService.getByName(deviceNo);
        if (recharge == null) {
            return ResultGenerator.fail("设备[" + deviceNo + "]叫料信息不存在");
        }
        try {
            List<RechargeArtBagItem> items = rechargeArtBagItemService.findByDeviceNo(deviceNo);
            if (items != null && items.size() > 0) {
                List<RechargeMixDto> dtos = items.stream().map(this::artBagItemToEagerDto).collect(Collectors.toList());
                return ResultGenerator.success(dtos);
            }
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    public MonitorRechargeDto toLazyDto(MonitorEquipmentRecharge entity) {
        MonitorRechargeDto dto = modelMapper.map(entity, MonitorRechargeDto.class);
        return dto;
    }

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

    public MonitorEquipmentRecharge fromDto(MonitorRechargeDto dto) {
        return modelMapper.map(dto, MonitorEquipmentRecharge.class);
    }

    public RechargeMixDto artBagItemToEagerDto(RechargeArtBagItem entity) {
        RechargeMixDto dto = modelMapper.map(entity, RechargeMixDto.class);
        return dto;
    }

}
