package com.sw.mes.store.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.DynmaicQueryWrapper;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.store.api.interfaces.consumer.WarehouseConsumerService;
import com.sw.mes.store.dto.WarehouseAllotBillDto;
import com.sw.mes.store.entity.WarehouseAllotBill;
import com.sw.mes.store.entity.WarehouseAllotRecordBill;
import com.sw.mes.store.entity.WarehouseAllotRecordBillDetail;
import com.sw.mes.store.service.WarehouseAllotBillService;
import com.sw.mes.store.service.WarehouseAllotRecordBillDetailService;
import com.sw.mes.store.service.WarehouseAllotRecordBillService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
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.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/warehouse/allotBill")
@Slf4j
@Api(tags = "调拨单接口")
public class WarehouseAllotBillController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private WarehouseAllotBillService warehouseAllotBillService;

    @Autowired
    private WarehouseConsumerService warehouseConsumerService;

    @Autowired
    private WarehouseAllotRecordBillService warehouseAllotRecordBillService;

    @Autowired
    private WarehouseAllotRecordBillDetailService warehouseAllotRecordBillDetailService;
    @ApiOperation(value = "分页查询调拨单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<WarehouseAllotBillDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        //分页查询
        QueryWrapper<WarehouseAllotBill> queryWrapper = DynmaicQueryWrapper.bySearchFilter(request, WarehouseAllotBill.class);
        Page<WarehouseAllotBill> page = new Page<>(requestPage.getPage(), requestPage.getRows());
        String orderDirection = requestPage.getOrderDirection();
        String orderField = requestPage.getOrderField();
        page.addOrder(RequestPage.ORDER_DIRECTION_DESC.equals(orderDirection) ? OrderItem.desc(orderField) : OrderItem.asc(orderField));
        Page<WarehouseAllotBill> listPage = warehouseAllotBillService.page(page, queryWrapper);
        List<WarehouseAllotBillDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage<WarehouseAllotBillDto> responsePage = new ResponsePage(dtos, listPage.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有调拨单")
    @GetMapping("/listAll")
    public Result<List<WarehouseAllotBillDto>> listAll(ServletRequest request) {
        QueryWrapper<WarehouseAllotBill> queryWrapper = DynmaicQueryWrapper.bySearchFilter(request, WarehouseAllotBill.class);
        List<WarehouseAllotBill> entities = warehouseAllotBillService.list(queryWrapper);
        List<WarehouseAllotBillDto> dtos = entities.stream()
                .map(storeOutputBill -> toLazyDto(storeOutputBill))
                .collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    @ApiOperation(value = "调拨单详细信息")
    @GetMapping("/{id}")
    public Result<WarehouseAllotBillDto> get(@PathVariable @ApiParam(value = "调拨单id") Integer id) {
        WarehouseAllotBill warehouseAllotBill = warehouseAllotBillService.getById(id);
        if (null == warehouseAllotBill) {
            return ResultGenerator.fail("该调拨单不存在");
        }
        return ResultGenerator.success(toEagerDto(warehouseAllotBill));
    }

    @ApiOperation(value = "创建调拨单")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "调拨单对象") WarehouseAllotBillDto warehouseAllotBillDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        warehouseAllotBillService.create(warehouseAllotBillDto);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "调拨单审核-拒收")
    @PostMapping("/rejection")
    public Result rejection(@RequestBody @Valid @ApiParam(value = "调拨单对象") WarehouseAllotBillDto warehouseAllotBillDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            return warehouseAllotBillService.rejectApply(warehouseAllotBillDto);
        } catch (Exception e) {
            return ResultGenerator.fail("拒收失败，失败原因：" + e.getMessage());
        }
    }

    @ApiOperation(value = "调拨单审核-接收")
    @PostMapping("/receive")
    public Result receive(@RequestBody @Valid @ApiParam(value = "调拨单对象") WarehouseAllotBillDto warehouseAllotBillDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        String billNo = warehouseAllotBillDto.getBillNo();
        if (StringUtils.isBlank(billNo)) {
            return ResultGenerator.fail("单据号不能为空！");
        }
        try {
            warehouseAllotBillService.auditReceiveAtomic(warehouseAllotBillDto);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "调拨单审核-测试")
    @PostMapping("/test")
    public Result test(@RequestBody @Valid @ApiParam(value = "调拨单对象") WarehouseAllotBillDto warehouseAllotBillDto, BindingResult bindingResult) {
        warehouseConsumerService.afterAuditAllot(warehouseAllotBillDto);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新调拨单")
    @PostMapping("/update")
    public Result<String> update(@RequestBody @Valid @ApiParam(value = "调拨单") WarehouseAllotBillDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        WarehouseAllotBill entity = warehouseAllotBillService.getById(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            WarehouseAllotBill entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            warehouseAllotBillService.saveOrUpdate(entity);
            //保存调拨单记录
            WarehouseAllotRecordBill recordBill = new WarehouseAllotRecordBill();
            List<WarehouseAllotRecordBillDetail>  allotRecordBillDetails = new ArrayList<>();
            BeanUtils.copyProperties(entityfromFto,recordBill);
            recordBill.setAllotBillNo(entityfromFto.getBillNo());
            recordBill.setAllotBillId(entityfromFto.getId());
            recordBill.setRecordBillNo(entityfromFto.getBillNo());
            warehouseAllotRecordBillService.saveOrUpdate(recordBill);
            entityfromFto.getAllotBillDetailDtos().stream().forEach(detail->{
                WarehouseAllotRecordBillDetail warehouseAllotRecordBillDetail = new WarehouseAllotRecordBillDetail();
                BeanUtils.copyProperties(detail,warehouseAllotRecordBillDetail);
                warehouseAllotRecordBillDetail.setRecordBillId(recordBill.getId());
                warehouseAllotRecordBillDetail.setRecordBillNo(recordBill.getRecordBillNo());
                warehouseAllotRecordBillDetail.setMaterialModelId(Integer.valueOf(String.valueOf(detail.getMaterialModelId())));
                warehouseAllotRecordBillDetail.setAllotBillNo(detail.getAllotBillNo());
                warehouseAllotRecordBillDetail.setAllotBillId(detail.getAllotBillId());
                warehouseAllotRecordBillDetail.setCreateUserId(detail.getCreateUserId());
                warehouseAllotRecordBillDetail.setCreateUserName(detail.getCreateUserName());
                warehouseAllotRecordBillDetail.setCreateTime(detail.getCreateTime());
                allotRecordBillDetails.add(warehouseAllotRecordBillDetail);
            });
            warehouseAllotRecordBillDetailService.saveBatch(allotRecordBillDetails);
            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) {
        warehouseAllotBillService.removeByIds(Arrays.asList(ids));
        return ResultGenerator.success();
    }

    public WarehouseAllotBillDto toLazyDto(WarehouseAllotBill entity) {
        return modelMapper.map(entity, WarehouseAllotBillDto.class);
    }

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

    public WarehouseAllotBill fromDto(WarehouseAllotBillDto dto) {
        return modelMapper.map(dto, WarehouseAllotBill.class);
    }
}