package com.sw.common.accessory.server.controller;

import com.sw.common.accessory.server.EnumValuesAccy;
import com.sw.common.accessory.server.dto.*;
import com.sw.common.accessory.server.entity.EquipmentAccessory;
import com.sw.common.accessory.server.service.AccessoryService;
import com.sw.common.accessory.server.service.EquipmentAccessoryService;
import com.sw.common.core.request.RequestPage;
import com.sw.common.core.response.ResponsePage;
import com.sw.common.core.response.Result;
import com.sw.common.core.response.ResultGenerator;
import com.sw.common.mybatisplus.entity.Page;
import com.sw.common.mybatisplus.entity.Pageable;
import com.sw.common.mybatisplus.utils.DynamicSpecifications;
import com.sw.common.mybatisplus.utils.PageUtil;
import com.sw.common.mybatisplus.utils.Specification;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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;


@RestController
@RequestMapping("/equipmentAccessory")
@Slf4j
@Api(tags = "设备辅材接口")
public class EquipmentAccessoryController {
    @Autowired
    private EquipmentAccessoryService equipmentAccessoryService;

    @Autowired
    private AccessoryService accessoryService;

    @ApiOperation(value = "分页查询设备辅材列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<EquipmentAccessoryDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<EquipmentAccessory> specification = DynamicSpecifications.bySearchFilter(request, EquipmentAccessory.class);
        Page<EquipmentAccessory> page = equipmentAccessoryService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<EquipmentAccessoryDto> dtos = page.getContent().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        ResponsePage<EquipmentAccessoryDto> responsePage = new ResponsePage<>(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "分页查询设备辅材列表(新)")
    @PostMapping("/newListByPage")
    public Result<ResponsePage<EquipmentAccessoryDto>> newListByPage(@RequestBody EquipmentAccessBo bo,ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<EquipmentAccessory> specification = DynamicSpecifications.bySearchFilter(request, EquipmentAccessory.class);
        Pageable pageable = PageUtil.createPageable(requestPage);
        Page<EquipmentAccessory> page = equipmentAccessoryService.findByExample(specification, pageable);
        List<EquipmentAccessory> equipmentAccessorys = equipmentAccessoryService.pages(bo,pageable);
        int total = equipmentAccessoryService.pageCount(bo);
        page.setContent(equipmentAccessorys);
        page.setTotalElements(total);
        List<EquipmentAccessoryDto> dtos = page.getContent().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        List<EquipmentAccessoryDto> equipmentAccessoryDtos = dtos.stream().filter(entity -> entity.getCount() != 0).collect(Collectors.toList());
        ResponsePage<EquipmentAccessoryDto> responsePage = new ResponsePage<>(equipmentAccessoryDtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "设备辅材详细信息")
    @GetMapping("/{id}")
    public Result<List<AccessoryDetails>> get(@PathVariable @ApiParam(value = "设备辅材id") Long id, @RequestParam(required = false) @ApiParam(value = "使用状态") Integer[] statuss, @RequestParam(required = false) @ApiParam(value = "预警状态") Integer warnStatus) {
        EquipmentAccessory equipmentAccessory = equipmentAccessoryService.get(id);
        if (null == equipmentAccessory) {
            return ResultGenerator.fail("该设备辅材不存在");
        }
        List<AccessoryDetails> accessoryDetails = accessoryService.findByEquipmentAccessoryId(equipmentAccessory.getId(), statuss, warnStatus);
        return ResultGenerator.success(accessoryDetails);
    }

    @ApiOperation(value = "根据设备编号，获取设备辅材详细信息")
    @GetMapping("equipmentCode/{equipmentCode}")
    public Result<List<AccessoryDto>> findByEquipmentCode(@PathVariable @ApiParam(value = "设备编号") String equipmentCode) {
        List<AccessoryDto> accessoryDetails = accessoryService.findByEquipmentCodeAndStatus(equipmentCode, EnumValuesAccy.AccyUseStatus.上机中.getKey());
        return ResultGenerator.success(accessoryDetails);
    }

    @ApiOperation(value = "根据设备编号获取设备辅材信息")
    @GetMapping("/getAccessoryByEquipmentCode")
    public Result<List<AccessoryDto>> getAccessoryByEquipmentCode(@RequestParam @ApiParam(value = "设备编号") String equipmentCode) {
        List<AccessoryDto> accessoryDetails = accessoryService.findByEquipmentCode(equipmentCode);
        return ResultGenerator.success(accessoryDetails);
    }

    @ApiOperation(value = "申请辅材")
    @PostMapping("/applyAccessory")
    public Result applyAccessory(@RequestBody @Valid @ApiParam(value = "申请辅材") ApplyAccessoryParamDto applyAccessoryParamDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        equipmentAccessoryService.applyAccessory(applyAccessoryParamDto);
        return ResultGenerator.success();
    }
    @ApiOperation(value = "要料申请辅材")
    @PostMapping("/applyMaterial")
    public Result applyMaterial(@RequestBody @ApiParam(value = "要料申请辅材") ApplyMaterialParamDto materialParamDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        equipmentAccessoryService.applyMaterial(materialParamDto);
        return ResultGenerator.success();
    }
    @ApiOperation(value = "退库")
    @PostMapping("/stockReturn")
    public Result<String> stockReturn(@RequestBody @Valid @ApiParam(value = "申请辅材") StockReturn stockReturn, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        accessoryService.stockReturn(stockReturn);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "取消退库")
    @PostMapping("/cancelStockReturn/{id}")
    public Result<String> cancelStockReturn(@PathVariable @ApiParam(value = "设备辅材id") Long id) {
        if (id == null) {
            return ResultGenerator.fail("设备辅材id，不能为空");
        }
        accessoryService.cancelStockReturn(id);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "取消申请辅材")
    @PostMapping("/cancelApplyAccessory/{id}")
    public Result<String> cancelApplyAccessory(@PathVariable @ApiParam(value = "申请辅材Id") Long id) {
        if (id == null) {
            return ResultGenerator.fail("申请辅材Id，不能为空");
        }
        equipmentAccessoryService.cancelApplyAccessory(id);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "上机")
    @PostMapping("/upper/{id}")
    public Result<String> upper(@PathVariable @ApiParam(value = "辅材Id") Long id) {
        if (id == null) {
            return ResultGenerator.fail("辅材Id，不能为空");
        }
        accessoryService.upper(id);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "根据设备编号批量上机")
    @PostMapping("/batchUpper")
    public Result<String> batchUpper(@RequestBody @ApiParam(value = "设备编码集合") List<String> eqpNos) {
        accessoryService.batchUpper(eqpNos);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "下机")
    @PostMapping("/down/{id}")
    public Result<String> down(@PathVariable @ApiParam(value = "辅材Id") Long id) {
        if (id == null) {
            return ResultGenerator.fail("辅材Id，不能为空");
        }
        accessoryService.down(id);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "根据设备编号批量下机")
    @PostMapping("/batchDown")
    public Result<String> batchDown(@RequestBody @ApiParam(value = "设备编码集合") List<String> eqpNos) {
        accessoryService.batchDown(eqpNos);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "删除设备辅材")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            equipmentAccessoryService.delete(id);
        }
        return ResultGenerator.success();
    }

    public EquipmentAccessoryDto toLazyDto(EquipmentAccessory entity) {
        EquipmentAccessoryDto equipmentAccessoryDto = new EquipmentAccessoryDto();
        BeanUtils.copyProperties(entity, equipmentAccessoryDto);
        return equipmentAccessoryDto;
    }

    public EquipmentAccessoryDto toEagerDto(EquipmentAccessory entity) {
        EquipmentAccessoryDto equipmentAccessoryDto = new EquipmentAccessoryDto();
        BeanUtils.copyProperties(entity, equipmentAccessoryDto);
        return equipmentAccessoryDto;
    }

    public EquipmentAccessory fromDto(EquipmentAccessoryDto dto) {
        EquipmentAccessory equipmentAccessory = new EquipmentAccessory();
        BeanUtils.copyProperties(dto, equipmentAccessory);
        return equipmentAccessory;
    }
}