package com.sw.mes.itemclean.clean.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.excel.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sw.mes.core.annotation.Jinko;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.DictionaryItemDto;
import com.sw.mes.core.dto.MaterialModelDto;
import com.sw.mes.core.dto.ProductionOrderDto;
import com.sw.mes.core.dto.RecycledMaterialManageDto;
import com.sw.mes.core.enums.ItemCleanEnums;
import com.sw.mes.core.exception.BusinessException;
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.BeanUtil;
import com.sw.mes.core.utils.DynmaicQueryWrapper;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.itemclean.clean.domain.CleanReworking;
import com.sw.mes.itemclean.clean.dto.*;
import com.sw.mes.itemclean.clean.domain.MaterialStoreSignBox;
import com.sw.mes.itemclean.clean.dto.batchNoOperate.BatchNoOperate;
import com.sw.mes.itemclean.clean.dto.boxNoOperate.BatchNo;
import com.sw.mes.itemclean.clean.dto.boxNoOperate.BoxNoOperate;
import com.sw.mes.itemclean.clean.mapper.MaterialStoreSignBoxMapper;
import com.sw.mes.itemclean.clean.service.GenerateBusinessNoService;
import com.sw.mes.itemclean.clean.service.MaterialStoreSignBoxService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


@Jinko(author = "yyl", value = "打签箱待存（待扫码领料）==>领料表")
@RestController
@RequestMapping("/clean/materialStoreSignBox")
@Slf4j
@Api(tags = "领料表")
public class MaterialStoreSignBoxController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private MaterialStoreSignBoxService materialStoreSignBoxService;

    @Autowired
    private MaterialStoreSignBoxMapper materialStoreSignBoxMapper;

    @Autowired
    private GenerateBusinessNoService generateBusinessNoService;

    @Autowired
    private YbFeignClients ybFeignClients;

    @Jinko(author = "yyl", value = "硅料审核调拨管理-清洗领料分页查询列表")
    @ApiOperation(value = "硅料审核调拨管理-清洗领料分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_materialName", value = "物料名称", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_materialCode", value = "物料编码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_createTime", value = "成箱开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_createTime", value = "成箱结束时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_createUser", value = "成箱人", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_materialType", value = "物料类型 1原生多晶2回收料3落地料4返工料5清洗料6破碎料", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_status", value = "审核状态 0 待审核 1 已接收 2已拒收", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_useStatus", value = "使用状态 0未使用 1已使用 2合批 3分选 4已清空", dataType = "integer", paramType = "query"),
    })

    @GetMapping("/listByPage")
    public Result<ResponsePage<MaterialStoreSignBoxDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        //分页查询
        QueryWrapper<MaterialStoreSignBox> queryWrapper = DynmaicQueryWrapper.searchFilter(request, MaterialStoreSignBox.class);
        queryWrapper.orderByDesc("id");
        Page<MaterialStoreSignBox> listPage = materialStoreSignBoxService.page(new Page<>(requestPage.getPage(), requestPage.getRows()), queryWrapper);
        List<MaterialStoreSignBoxDto> dtos = listPage.getRecords().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, listPage.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有列表")
    @GetMapping("/listAll")
    public Result<List<MaterialStoreSignBoxDto>> listAll(ServletRequest request) {
        QueryWrapper<MaterialStoreSignBox> queryWrapper = DynmaicQueryWrapper.searchFilter(request, MaterialStoreSignBox.class);
        List<MaterialStoreSignBox> materialStoreSignBoxs = materialStoreSignBoxService.list(queryWrapper);
        List<MaterialStoreSignBoxDto> materialStoreSignBoxDtos = materialStoreSignBoxs.stream()
                .map(materialStoreSignBox -> toLazyDto(materialStoreSignBox))
                .collect(Collectors.toList());
        return ResultGenerator.success(materialStoreSignBoxDtos);
    }

    @ApiOperation(value = "详细信息")
    @GetMapping("/{id}")
    public Result<MaterialStoreSignBoxDto> get(@PathVariable @ApiParam(value = "设备类型id") Integer id) {
        MaterialStoreSignBox materialStoreSignBox = materialStoreSignBoxService.getById(id);
        if (null == materialStoreSignBox)
            return ResultGenerator.fail("该对象不存在");
        return ResultGenerator.success(toEagerDto(materialStoreSignBox));
    }

    @Jinko(author = "yyl", value = "创建清洗待领料数据-接收线边仓余料数据")
    @ApiOperation(value = "创建清洗待领料数据-接收线边仓余料数据")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "Dto对象") MaterialStoreSignBoxDto materialStoreSignBoxDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        //校验是否存在同箱号,未使用数据
        MaterialStoreSignBox signBox = materialStoreSignBoxService.checkBox(materialStoreSignBoxDto.getBoxNo());
        if (null != signBox) {
            throw new BusinessException("箱号: " + materialStoreSignBoxDto.getBoxNo() + "存在领料信息!");
        }

        //字段需要与物料主数据对齐
      /*  Result<MaterialModelDto> result = ybFeignClients.getMaterialByCode(materialStoreSignBoxDto.getMaterialCode());
        MaterialModelDto materialModel = result.getData();
        if (materialModel == null) {
            throw new BusinessException("【" + materialStoreSignBoxDto.getMaterialCode() + "】物料主数据不存在，请检查数据！");
        }*/
        MaterialStoreSignBox materialStoreSignBox = fromDto(materialStoreSignBoxDto);
        //发起入库此处不在生成批次号，入参已经传进来

        if (StringUtils.isBlank(materialStoreSignBoxDto.getDateProduceBatchNo())) {
            //校验回收料数据
            Result<RecycledMaterialManageDto> manageDtoResult = ybFeignClients.getByProduceBatchNo(materialStoreSignBoxDto.getProductBatchNo());
            if (manageDtoResult.getCode() != ResultCode.SUCCESS.getCode() || null == manageDtoResult.getData()) {
                log.error(materialStoreSignBoxDto.getProductBatchNo() + "回收料查询异常");
                throw new RuntimeException("回收料查询异常：" + manageDtoResult.getMessage());
            }
            RecycledMaterialManageDto recycledMaterialManage = manageDtoResult.getData();
            if (manageDtoResult.getCode() != ResultCode.SUCCESS.getCode() || null == manageDtoResult.getData()) {
                log.error(materialStoreSignBoxDto.getProductBatchNo() + "回收料查询异常");
                throw new RuntimeException("回收料查询异常：" + manageDtoResult.getMessage());
            }
            String dateProduceBatchNo = recycledMaterialManage.getDateProduceBatchNo();
            materialStoreSignBox.setDateProduceBatchNo(dateProduceBatchNo);
        }
        materialStoreSignBox.setMaterialBoxNo(generateBusinessNoService.generateBoxNo(new BoxNoOperate(ItemCleanEnums.BoxNoType.默认, new BatchNo(materialStoreSignBox.getProductBatchNo()))));
        materialStoreSignBox.setBoxNo(materialStoreSignBoxDto.getBoxNo());
        materialStoreSignBox.setStatus(ItemCleanEnums.MaterialStatus.待审核.getKey());
        materialStoreSignBox.setPickingStatus(ItemCleanEnums.MaterialPickStatus.未领料.getKey());
        materialStoreSignBox.setUseStatus(ItemCleanEnums.MaterialUseStatus.未使用.getKey());
        materialStoreSignBox.setUsedWeight(BigDecimal.ZERO);
        materialStoreSignBox.setWeight(materialStoreSignBoxDto.getWeight());
        materialStoreSignBox.setActualWeight(materialStoreSignBoxDto.getWeight());
        materialStoreSignBox.setUnusedWeight(materialStoreSignBoxDto.getWeight());
        materialStoreSignBox.setCreateTime(LocalDateTime.now());
        materialStoreSignBox.setInitiateTime(LocalDateTime.now());
        materialStoreSignBox.setInitiateUser(materialStoreSignBoxDto.getCreateUser());
        materialStoreSignBox.setSupplier(materialStoreSignBoxDto.getSupplier());
        materialStoreSignBox.setSupplierCode(materialStoreSignBoxDto.getSupplierCode());
        materialStoreSignBox.setDelFlag(ItemCleanEnums.MaterialDelFlag.未删除.getKey());
        materialStoreSignBox.setAufnr(materialStoreSignBoxDto.getAufnr());
        materialStoreSignBoxService.saveOrUpdate(materialStoreSignBox);
        return ResultGenerator.success();
    }

    @Jinko(author = "yyl", value = "硅料审核调拨管理-审核按钮")
    @ApiOperation(value = "硅料审核调拨管理-审核按钮")
    @GetMapping("/examineStatus")
    public Result examineStatus(@ApiParam(value = "待领料ID") Integer id, @ApiParam(value = "审核状态 0 待审核 1 已接收 2已拒收") Integer status) {

        MaterialStoreSignBox entity = materialStoreSignBoxService.getById(id);
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            materialStoreSignBoxService.examineStatus(entity, status);
        } catch (Exception e) {
            log.error(ExceptionUtil.stacktraceToString(e));
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success();
    }


    @Jinko(author = "yyl", value = "清洗领料数据合批")
    @ApiOperation(value = "清洗领料数据合批")
    @PostMapping("/blending")
    public Result blending(@RequestBody @Valid @ApiParam(value = "Dto对象") List<MaterialStoreSignBoxDto> dtos, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        materialStoreSignBoxService.blending(dtos);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "Dto对象") MaterialStoreSignBoxDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
        MaterialStoreSignBox entity = materialStoreSignBoxService.getById(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            MaterialStoreSignBox entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            materialStoreSignBoxService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            log.error(ExceptionUtil.stacktraceToString(e));
            return ResultGenerator.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "更新是否空箱状态")
    @PostMapping("/updateIsEmptyBox")
    public Result updateIsEmptyBox(@RequestBody @Valid @ApiParam(value = "Dto对象") MaterialStoreSignBoxDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getMaterialBoxNo() == null)
            return ResultGenerator.fail("箱号不能为空");
        MaterialStoreSignBox entity = materialStoreSignBoxService.getByBoxNo(dto.getMaterialBoxNo());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            entity.setIsEmptyBox(dto.getIsEmptyBox());
            materialStoreSignBoxService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            log.error(ExceptionUtil.stacktraceToString(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) {
            materialStoreSignBoxMapper.deleteById(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "扫描箱号")
    @GetMapping("/generalScanBoxNo")
    public Result<BoxPropertyDto> generalScanBoxNo(GeneralScanBoxNoParam param) {
        BoxPropertyDto dto = materialStoreSignBoxService.generalScanBoxNo(param);
        return ResultGenerator.success(dto);
    }

    @ApiOperation(value = "测试流水号生成")
    @GetMapping("/generateProductBatchNo")
    public Result<String> genSerialNumber(String code) {
        String s = generateBusinessNoService.genSerialNumber(code);
        return ResultGenerator.success(s);
    }

    @ApiOperation(value = "分选成箱扫描箱号")
    @PostMapping("/generalScanFxBoxNo")
    public Result<MaterialStoreSignBox> generalScanFxBoxNo(@RequestBody @Valid @ApiParam(value = "打签箱待存（待扫码领料）对象") MaterialStoreSignBox materialStoreSignBox, BindingResult bindingResult) {

        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());

        MaterialStoreSignBox materialStoreSignBoxResult = materialStoreSignBoxService.getByBoxNo(materialStoreSignBox);
        if (materialStoreSignBoxResult == null) {
            return ResultGenerator.fail("该箱号不存在");
        } else {
            if (materialStoreSignBox.getMaterialType() != null) {
                if (!materialStoreSignBox.getMaterialType().equals(materialStoreSignBoxResult.getMaterialType())) {
                    return ResultGenerator.fail("该箱号物料类型和上一箱的物料类型不相同");
                }
            }
            if (materialStoreSignBox.getProductBatchNo() != null) {
                if (!materialStoreSignBox.getProductBatchNo().equals(materialStoreSignBoxResult.getProductBatchNo())) {
                    return ResultGenerator.fail("该箱号生产批次和上一箱的生产批次不相同");
                }
            }
            return ResultGenerator.success(materialStoreSignBoxResult);
        }
    }

    /**
     * 通过卡板箱号确定是否存在待领料表中并且未领料但是被占用
     *
     * @param materialBoxNo
     * @return
     */
    @ApiOperation(value = "通过卡板箱号确定箱子使用状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "materialBoxNo", value = "卡板箱号", dataType = "String", paramType = "query"),
    })
    @GetMapping(value = "/findEmptyMaterialBoxNo")
    public Result findEmptyMaterialBoxNo(String materialBoxNo) {
        MaterialStoreSignBox materialStoreSignBox = materialStoreSignBoxService.getByKbxBoxNo(materialBoxNo);
        if (null == materialStoreSignBox) {
            return ResultGenerator.success("扫入料箱号成功");
        } else {
            return ResultGenerator.fail("该箱号: " + materialBoxNo + " 被占用,等待清洗车间领料后回流空箱方可使用!");
        }
    }

    @ApiOperation(value = "通过箱号获取箱内物料信息(也可用于校验重量等信息)")
    @GetMapping("/getInfoByBoxNo")
    public Result<MaterialStoreSignBox> getInfoByBoxNo(String materialStoreSignBox) {
        MaterialStoreSignBox materialStoreSignBoxResult = materialStoreSignBoxService.getByKbxBoxNo(materialStoreSignBox);
        if (materialStoreSignBoxResult == null) {
            return ResultGenerator.fail("该箱号不存在");
        } else {
            return ResultGenerator.success(materialStoreSignBoxResult);
        }
    }

    @Jinko(author = "yyl", value = "通过箱号获取领料箱内物料信息")
    @ApiOperation(value = "通过箱号获取领料箱内物料信息")
    @GetMapping("/getInfoByMaterialStoreSignBox")
    public Result<MaterialStoreSignBox> getInfoByMaterialStoreSignBox(String materialStoreSignBox) {
        MaterialStoreSignBox materialStoreSignBoxResult = materialStoreSignBoxService.getByKbxBoxNo(materialStoreSignBox);
        if (materialStoreSignBoxResult == null) {
            return ResultGenerator.fail("该箱号不存在领料表");
        } else {
            return ResultGenerator.success(materialStoreSignBoxResult);
        }
    }


    @Jinko(author = "yyl", value = "合批使用-通过批次号获取领料箱内物料信息")
    @ApiOperation(value = "合批使用-通过批次号获取领料箱内物料信息")
    @GetMapping("/getInfoByMaterialProductBatchNo")
    public Result<MaterialStoreSignBox> getInfoByMaterialProductBatchNo(String productBatchNo) {
        MaterialStoreSignBox materialStoreSignBoxResult = materialStoreSignBoxService.getByProductBatchNo(productBatchNo);
        if (materialStoreSignBoxResult == null) {
            return ResultGenerator.fail("该批次号不存在领料信息中");
        } else {
            return ResultGenerator.success(materialStoreSignBoxResult);
        }
    }

    @Jinko(author = "yyl", value = "分选投料使用-通过批次号获取领料箱内物料信息")
    @ApiOperation(value = "分选投料使用-通过批次号获取领料箱内物料信息")
    @GetMapping("/useInfoByMaterialProductBatchNo")
    public Result<MaterialStoreSignBox> useInfoByMaterialProductBatchNo(String productBatchNo) {
        MaterialStoreSignBox materialStoreSignBoxResult = materialStoreSignBoxService.useInfoByMaterialProductBatchNo(productBatchNo);
        if (materialStoreSignBoxResult == null) {
            return ResultGenerator.fail("该批次号不存在可用信息");
        } else {
            return ResultGenerator.success(materialStoreSignBoxResult);
        }
    }

    @Jinko(author = "yyl", value = "检验硅料是否存在未使用完的相同箱号")
    @ApiOperation(value = "检验硅料是否存在未使用完的相同箱号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "boxNo", value = "卡板箱号", dataType = "String", paramType = "query"),
    })
    @GetMapping("/checkBox")
    public Result checkBox(String boxNo) {
        MaterialStoreSignBox signBox = materialStoreSignBoxService.checkBox(boxNo);
        if (null != signBox) {
            throw new BusinessException("硅料存在箱号: " + boxNo + "的未使用完的物料信息!");
        }
        return ResultGenerator.success();
    }

    public MaterialStoreSignBoxDto toLazyDto(MaterialStoreSignBox entity) {
        return modelMapper.map(entity, MaterialStoreSignBoxDto.class);
    }

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

    public MaterialStoreSignBox fromDto(MaterialStoreSignBoxDto dto) {
        return modelMapper.map(dto, MaterialStoreSignBox.class);
    }

    public MaterialStoreSignBox fromDto(MaterialStoreSignBoxFromWarehouseDto dto) {
        return modelMapper.map(dto, MaterialStoreSignBox.class);
    }
}
