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

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.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.yb.accessory.dao.AccessoryMaterialOutDao;
import com.sw.mes.yb.accessory.dto.AccessoryMaterialOutDto;
import com.sw.mes.yb.accessory.entity.AccessoryMaterial;
import com.sw.mes.yb.accessory.entity.AccessoryMaterialOut;
import com.sw.mes.yb.accessory.entity.EquipmentAccessory;
import com.sw.mes.yb.accessory.service.AccessoryMaterialOutService;
import com.sw.mes.yb.accessory.service.AccessoryMaterialService;
import com.sw.mes.yb.accessory.service.EquipmentAccessoryService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
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.List;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/accessoryMaterialOut")
@Slf4j
@Api(description = "辅料线边仓发料出库接口wms→mes(辅料申请发料)")
public class AccessoryMaterialOutController {
    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private AccessoryMaterialOutService accessoryMaterialOutService;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private AccessoryMaterialService accessoryMaterialService;

    @Autowired
    private AccessoryMaterialOutDao accessoryMaterialOutDao;

    @Autowired
    private EquipmentAccessoryService equipmentAccessoryService;

    @ApiOperation(value = "分页查询辅料线边仓发料列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_uniqueCode", value = "热场条码", dataType = "string", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<AccessoryMaterialOutDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<AccessoryMaterialOut> specification = DynamicSpecifications.bySearchFilter(request, AccessoryMaterialOut.class);
        Page<AccessoryMaterialOut> page = accessoryMaterialOutService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<AccessoryMaterialOutDto> 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<AccessoryMaterialOutDto>> listAll(ServletRequest request) {
        Specification<AccessoryMaterialOut> specification = DynamicSpecifications.bySearchFilter(request, AccessoryMaterialOut.class);
        List<AccessoryMaterialOut> accessoryMaterialOuts = accessoryMaterialOutService.findByExampleSort(specification, null);
        List<AccessoryMaterialOutDto> accessoryMaterialOutDtos = accessoryMaterialOuts.stream()
                .map(accessoryMaterialOut -> toLazyDto(accessoryMaterialOut))
                .collect(Collectors.toList());
        return ResultGenerator.success(accessoryMaterialOutDtos);
    }

    @ApiOperation(value = "辅料线边仓发料出库详细信息")
    @GetMapping("/{id}")
    public Result<AccessoryMaterialOutDto> get(@PathVariable @ApiParam(value = "辅料线边仓发料出库id") Integer id) {
        AccessoryMaterialOut accessoryMaterialOut = accessoryMaterialOutService.get(id);
        if (null == accessoryMaterialOut) {
            return ResultGenerator.fail("该辅料线边仓发料出库不存在");
        }
        return ResultGenerator.success(toEagerDto(accessoryMaterialOut));
    }

    @ApiOperation(value = "创建辅料线边仓发料出库")
//    @PostMapping("/create")  已废弃  发料用的这个接口/accessoryApplyFeedback/create
    public Result create(@RequestBody @Valid @ApiParam(value = "辅料线边仓发料出库对象") List<AccessoryMaterialOutDto> dtos, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if(dtos.isEmpty()){
            throw new RuntimeException("收到的参数为空");
        }
        for (AccessoryMaterialOutDto accessoryMaterialOutDto : dtos) {
            AccessoryMaterialOut accessoryMaterialOut = fromDto(accessoryMaterialOutDto);
            Equipment equipment = equipmentService.findByCode(accessoryMaterialOut.getDeviceNo());
            if (equipment == null) {
                throw new RuntimeException("该设备编号"+accessoryMaterialOut.getDeviceNo()+"在mes设备台账中不存在");
            }
            AccessoryMaterial accessoryMaterial = accessoryMaterialService.findByCodes(accessoryMaterialOut.getProductNo());
            if (accessoryMaterial == null) {
                throw new RuntimeException("该辅料模型"+accessoryMaterialOut.getProductNo()+"在mes易耗品模型中不存在");
            }
            List<EquipmentAccessory> list = equipmentAccessoryService.findByGoodCodesWithBind(accessoryMaterialOutDto.getUniqueCode());
            if (list != null && list.size() > 0) {
                throw new RuntimeException("uniqueCode唯一编码"+accessoryMaterialOutDto.getUniqueCode()+"已存在");
            }
            accessoryMaterialOut.setEquipment(equipment);
            accessoryMaterialOut.setMaterial(accessoryMaterial);

            accessoryMaterialOutService.saveMaterialOut(accessoryMaterialOut);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新辅料线边仓发料出库")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "辅料线边仓发料出库") AccessoryMaterialOutDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        AccessoryMaterialOut entity = accessoryMaterialOutService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            AccessoryMaterialOut entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            accessoryMaterialOutService.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 Integer[] ids) {
        for (Integer id : ids) {
            accessoryMaterialOutService.delete(id);
        }
        return ResultGenerator.success();
    }

    public AccessoryMaterialOutDto toLazyDto(AccessoryMaterialOut entity) {
        return modelMapper.map(entity, AccessoryMaterialOutDto.class);
    }

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

    public AccessoryMaterialOut fromDto(AccessoryMaterialOutDto dto) {
        //ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        return modelMapper.map(dto, AccessoryMaterialOut.class);
    }


}
