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

import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
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.yb.turnstore.dto.RecheckInspectReceiveDetailDto;
import com.sw.mes.yb.turnstore.dto.RecheckInspectReceiveDto;
import com.sw.mes.yb.turnstore.dto.RecheckInspectReceivePostDto;
import com.sw.mes.yb.turnstore.dto.YbReturnReceiptDto;
import com.sw.mes.yb.turnstore.entity.RecheckInspectReceive;
import com.sw.mes.yb.turnstore.entity.RecheckInspectReceiveDetail;
import com.sw.mes.yb.turnstore.service.RecheckInspectReceiveDetailService;
import com.sw.mes.yb.turnstore.service.RecheckInspectReceiveService;
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.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/RecheckInspectReceive")
@Slf4j
@Api(description = "圆棒退库复检接收接口")
public class RecheckInspectReceiveController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private RecheckInspectReceiveService recheckInspectReceiveService;

    @Autowired
    private RecheckInspectReceiveDetailService recheckInspectReceiveDetailService;


    @ApiOperation(value = "分页查询圆棒退库复检接收列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_outOrderNo", value = "出库单号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_trayNo", value = "托号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_state", value = "状态", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_confirmTime", value = "操作时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_confirmTime", value = "操作时间", dataType = "string", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<RecheckInspectReceiveDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<RecheckInspectReceive> specification = DynamicSpecifications.bySearchFilter(request, RecheckInspectReceive.class);
        Page<RecheckInspectReceive> page = recheckInspectReceiveService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<RecheckInspectReceiveDto> dtos = page.getContent().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有圆棒退库复检接收")
    @GetMapping("/listAll")
    public Result<List<RecheckInspectReceiveDto>> listAll(ServletRequest request) {
        Specification<RecheckInspectReceive> specification = DynamicSpecifications.bySearchFilter(request, RecheckInspectReceive.class);
        List<RecheckInspectReceive> recheckInspectReceives = recheckInspectReceiveService.findByExampleSort(specification, null);
        List<RecheckInspectReceiveDto> recheckInspectReceiveDtos = recheckInspectReceives.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(recheckInspectReceiveDtos);
    }

    @ApiOperation(value = "圆棒退库复检接收详细信息")
    @PostMapping("/ybReturnReceipt")
    public Result ybReturnReceipt(@RequestBody List<YbReturnReceiptDto> ybReturnReceiptDto) {
        Result result;
        for (YbReturnReceiptDto receiptDto : ybReturnReceiptDto) {
            String[] crystalNoArray = receiptDto.getCrystalNo().split(",");
            //正常退库
            if ("1".equals(receiptDto.getStatus())) {
                result = recheckInspectReceiveDetailService.normal(receiptDto, crystalNoArray);
            } else {
                //冲销退库
                result = recheckInspectReceiveDetailService.writeOff(crystalNoArray);
            }
            //异常返回
            if (result.getCode() != ResultCode.SUCCESS.code) {
                return result;
            }
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "WMS退库复检接收")
    @GetMapping("/{id}")
    public Result<RecheckInspectReceiveDto> get(@PathVariable @ApiParam(value = "圆棒退库复检接收id") Integer id) {
        RecheckInspectReceive recheckInspectReceive = recheckInspectReceiveService.get(id);
        if (null == recheckInspectReceive) {
            return ResultGenerator.fail("该圆棒退库复检接收不存在");
        }
        return ResultGenerator.success(toEagerDto(recheckInspectReceive));
    }


    @ApiOperation(value = "创建圆棒退库复检接收")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "圆棒退库复检接收对象") RecheckInspectReceiveDto recheckInspectReceiveDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        RecheckInspectReceive recheckInspectReceive = fromDto(recheckInspectReceiveDto);
        recheckInspectReceiveService.saveOrUpdate(recheckInspectReceive);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新圆棒退库复检接收+详情")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "圆棒退库复检接收") RecheckInspectReceivePostDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getReceiveDto().getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        RecheckInspectReceive entity = recheckInspectReceiveService.get(dto.getReceiveDto().getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            //更新主表
            RecheckInspectReceive entityFromFto = fromDto(dto.getReceiveDto());
            //将结果反馈至WMS
            Result result = recheckInspectReceiveService.mesToWmsReceipt(entityFromFto.getOutOrderNo(), entityFromFto.getState());
            if (result.getCode() == ResultCode.SUCCESS.getCode()) {
                //更新数据
                recheckInspectReceiveService.updateState(entityFromFto, dto.getDetailDtoList());
            }
            return result;
        } 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) {
            recheckInspectReceiveService.delete(id);
        }
        return ResultGenerator.success();
    }


    @ApiOperation(value = "导出Excel")
    @GetMapping("/exportExcel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search_EQ_outOrderNo", value = "出库单号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_trayNo", value = "托号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_state", value = "状态", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_confirmTime", value = "操作时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_confirmTime", value = "操作时间", dataType = "string", paramType = "query"),
    })
    public Result exportExcel(HttpServletRequest request, HttpServletResponse resp) {
        recheckInspectReceiveService.exportExcel(request, resp);
        return ResultGenerator.success();
    }


    public RecheckInspectReceiveDto toLazyDto(RecheckInspectReceive entity) {
        return modelMapper.map(entity, RecheckInspectReceiveDto.class);
    }

    public RecheckInspectReceiveDto toEagerDto(RecheckInspectReceive entity) {
        return modelMapper.map(entity, RecheckInspectReceiveDto.class);
    }

    public RecheckInspectReceive fromDto(RecheckInspectReceiveDto dto) {
        return modelMapper.map(dto, RecheckInspectReceive.class);
    }

    public RecheckInspectReceiveDetail fromDto(RecheckInspectReceiveDetailDto dto) {
        return modelMapper.map(dto, RecheckInspectReceiveDetail.class);
    }

}
