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

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sw.mes.core.annotation.Jinko;
import com.sw.mes.core.annotation.TokenNotValidation;
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.fb.turnstore.dto.FbReturnReceiptDto;
import com.sw.mes.fb.turnstore.dto.RecheckInspectReceiveDto;
import com.sw.mes.fb.turnstore.dto.RecheckInspectReceivePostDto;
import com.sw.mes.fb.turnstore.entity.RecheckInspectReceive;
import com.sw.mes.fb.turnstore.entity.RecheckInspectReceiveDetail;
import com.sw.mes.fb.turnstore.service.RecheckInspectReceiveDetailService;
import com.sw.mes.fb.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.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 receiveDetailService;

    @Autowired
    private ObjectMapper objectMapper;

    @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 = "方棒退料复检接收详细信息")
    @GetMapping("/{id}")
    public Result 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("/fbReturnReceipt")
    @TokenNotValidation
    public Result fbReturnReceipt(@RequestBody List<FbReturnReceiptDto> fbReturnReceiptDto) {
        Result result;
        for (FbReturnReceiptDto receiptDto : fbReturnReceiptDto) {
            String[] crystalNoArray = receiptDto.getCrystalNo().split(",");
            //正常退库
            if ("1".equals(receiptDto.getStatus())) {
                result = receiveDetailService.normal(receiptDto, crystalNoArray);
            } else {
                //冲销退库
                result = receiveDetailService.writeOff(crystalNoArray, receiptDto);
            }
            if (result.getCode() != ResultCode.SUCCESS.code) {
                return result;
            }
        }
        return ResultGenerator.success();
    }

    @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.getReceive().getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        RecheckInspectReceive entity = recheckInspectReceiveService.get(dto.getReceive().getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        List<RecheckInspectReceiveDetail> detailDtoList = dto.getDetailList();
        if (null == detailDtoList || detailDtoList.isEmpty()) {
            return ResultGenerator.fail("详情列表不能为空");
        }

        if (entity.getState() != null && entity.getState() != 0) {
            return ResultGenerator.fail("此托号【" + dto.getReceive().getTrayNo() + "】不处于待确认状态，不允许操作！");
        }
        //更新数据
        recheckInspectReceiveService.updateState(dto.getReceive(), detailDtoList);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "删除方棒退料复检接收")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {
        for (Integer id : ids) {
            recheckInspectReceiveService.delete(id);
        }
        return ResultGenerator.success();
    }

    @Jinko(value = "审核是否接收接口", author = "liangfeng")
    @ApiOperation(value = "审核是否接收")
    @PostMapping("/audit")
    public Result audit(@ApiParam(value = "id", type = "query") @RequestParam Integer id,
                        @ApiParam(value = "state,审核结果", type = "query") @RequestParam Integer state) {
        recheckInspectReceiveService.audit(id, state);
        return ResultGenerator.success();
    }
    @Jinko(value = "wms退库复检", author = "liangfeng")
    @ApiOperation("wms退库复检")
    @PostMapping("/wmsReturnInspection")
    public Result wmsReturnInspection(@RequestBody @Valid @ApiParam(value = "方棒退料复检接收") RecheckInspectReceivePostDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            log.info("wms新增退库复检请求参数:{}",objectMapper.writeValueAsString(dto));
            recheckInspectReceiveService.wmsReturnInspection(dto.getReceive(), dto.getDetailList());
        } catch (Exception e) {
            log.error("wms新增退库复检失败原因:",e);
            return ResultGenerator.fail("wms新增退库复检失败");
        }
        return ResultGenerator.success();
    }
    @Jinko(value = "切片MES退库复检接收", author = "liangfeng")
    @ApiOperation("切片MES退库复检接收")
    @PostMapping("/sectionMesReturnInspection")
    public Result sectionMesReturnInspection(@RequestBody @Valid @ApiParam(value = "方棒退料复检接收") RecheckInspectReceivePostDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            log.info("切片MES退库复检接收:{}",objectMapper.writeValueAsString(dto));
            recheckInspectReceiveService.sectionMesReturnInspection(dto.getReceive(), dto.getDetailList());
        } catch (Exception e) {
            log.error("切片MES退库复检接收:",e);
            return ResultGenerator.fail("切片MES退库复检接收");
        }
        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);
    }


}
