package com.sy.coinage.workshop.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.sy.coinage.app.req.CheckShopOutInConfirmReq;
import com.sy.coinage.app.req.CheckWareInConfirmReq;
import com.sy.coinage.app.req.vo.CheckDetailVO;
import com.sy.coinage.core.redis.RedisService;
import com.sy.coinage.core.vo.CacheUserVO;
import com.sy.coinage.sys.model.Dept;
import com.sy.coinage.sys.model.Dict;
import com.sy.coinage.sys.model.User;
import com.sy.coinage.sys.service.IDeptService;
import com.sy.coinage.sys.service.IDictService;
import com.sy.coinage.sys.service.IUserService;
import com.sy.coinage.workshop.WareUtil;
import com.sy.coinage.workshop.req.CheckReq;
import com.sy.coinage.workshop.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sy.coinage.workshop.dao.CheckDao;
import com.sy.coinage.workshop.model.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * -ServiceImpl
 */
@Slf4j
@Service
public class CheckServiceImpl extends ServiceImpl<CheckDao, Check> implements ICheckService {

    @Autowired
    private ICheckDetailService checkDetailService;

    @Autowired
    private ICheckBackupService checkBackupService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private IDeptService deptService;

    @Autowired
    private IProductService productService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IBaseInfoService baseInfoService;

    @Autowired
    private IStockService stockService;

    @Autowired
    private IWorkshopAccountService workshopAccountService;

    @Autowired
    private IWorkshopLogService workshopLogService;
    @Autowired
    private ILogisticsService logisticsService;

    @Override
    public String creadeOutOrderNo(Integer securitiesId, Integer deptId) {
        Product product = this.productService.getById(securitiesId);
        return this.createOrderNo(product.getSecurities(), deptId);
    }

    @Override
    @Transactional
    public void wareOut(CheckReq req, CacheUserVO user) {
        log.info("抽检出库={}", req);
        Product product = this.productService.getById(req.getSecuritiesId());
        Check model = new Check();
        BeanUtils.copyProperties(req, model);
        model.setDeptId(req.getTargetDeptId());
        model.setSecurities(product.getSecurities());
        //1:初始创建 2:抽检中  3: 抽检完成（仅当qty= qty_product时）
        model.setStatus(1);
        // 车间出库单单号
        model.setOrderNo(this.createOrderNo(model.getSecurities(), model.getDeptId()));
        Dict dict = this.dictService.getByVal("wareOpt", model.getWareId(), null);
        model.setWareCn(dict.getName());
        model.setDeptId(req.getTargetDeptId());
        Dept dept = this.deptService.getById(model.getDeptId());
        model.setDept(dept.getName());
        model.setOperatorId(user.getId());
        model.setOperatorCn(user.getRealName());
        model.setChecker(this.userService.getById(req.getCheckId()).getRealName());
        model.setCrownPrefix(product.getCrownPrefix());
        model.setQtyProduct(0);
        this.save(model);
        Date now = new Date();
        Integer totalBox = 0;
        for (CheckDetailVO vo : req.getList()) {
            totalBox = totalBox + vo.getCrownArray().size();
            // 添加明细
            this.addDetail(model, vo, now);
            // 添加Backup
            this.addBackup(model, vo, now);
        }
        // 单号增加
        this.addOrderNo(model.getSecurities(), model.getDeptId());
        Integer piecesTotal = totalBox * product.getAmountPerBox();
        List<Stock> stockList = this.stockService.getStockList(model.getWareId(), model.getSecuritiesId());
        Integer wareTotal = WareUtil.piecesTotal(stockList, product);
//        Integer box = 0;
//        for (Stock stock : stockList) {
//            box = box + stock.getBoxNum() + stock.getRacketNum() * product.getBoxAmount() - stock.getCheckBoxNum();
//        }
//        Integer wareTotal = box * product.getAmountPerBox();
        // 增加抽检箱数实际为出库抽检减少的箱数
        // 2-付出(收入负)
        this.workshopAccountService.shopOut(2, model.getDeptId(), model.getDept(), user.getId(),
            user.getRealName(), model.getCheckId(), model.getChecker(), null, piecesTotal,
            wareTotal, 1, 2, model.getDept(), model.getWareId(), model.getSecuritiesId(),
            model.getSecurities());
    }

    private void addBackup(Check check, CheckDetailVO vo, Date now) {
        CheckBackup model = new CheckBackup();
        BeanUtils.copyProperties(vo, model);
        model.setQty(vo.getCrownArray().size());
        model.setCrownList(JSON.toJSONString(vo.getCrownArray()));
        model.setCheckTime(now);
        model.setCheckOperatorCn(check.getOperatorCn());
        model.setChecker(check.getChecker());
        model.setCrownPrefix(check.getCrownPrefix());
        // 抽检登记: 1.库房抽检 2:车间抽检入库3.车间抽检出库4库房抽检返回确认
        model.setStatus(1);
        model.setWareId(String.valueOf(check.getWareId()));
        model.setWareCn(check.getWareCn());
        model.setDeptId(check.getDeptId());
        model.setDept(check.getDept());
        this.checkBackupService.save(model);
    }

    private void addDetail(Check check, CheckDetailVO vo, Date now) {
        BaseInfo info = this.baseInfoService.updateCheckStatus(vo.getRfid(), 4, 5, now, 1);
        CheckDetail model = new CheckDetail();
        BeanUtils.copyProperties(vo, model);
        model.setCheckId(check.getId());
        // 初始创建的冠字号列表
        model.setWareInitList(JSON.toJSONString(vo.getCrownArray()));
        this.checkDetailService.save(model);
        // FIXME 查询状态为4总库入库的 修改主库出库抽捡时间和状态5:主库抽检出库 抽捡状态1:主库出库
        Dict dict = this.dictService.getByVal("wareOpt", info.getLocWareId(), null);
        this.stockService.stockAdd(info.getSecuritiesId(), info.getSecurities(),
                info.getLocAreaId(), info.getLocWareId(), dict.getName(), 0, 0, 0, vo.getCrownArray().size());
        // FIXME 记录物流信息日志表
        this.logisticsService.add(model.getRfid(), model.getSerialNumber(), check.getWareId(),
            check.getWareCn(), 5, check.getCheckId(), check.getChecker(), check.getOperatorId(),
            check.getOperatorCn(), JSON.toJSONString(vo.getCrownArray()), null);
    }

    @Override
    @Transactional
    public void shopIn(CheckShopOutInConfirmReq req, CacheUserVO user) {
        log.info("抽检车间入库={}", req);
        User checkUser = this.userService.getById(req.getCheckId());
        Check model = this.getByOrderNo(req.getOrderNo());
        Dept dept = this.deptService.getById(model.getDeptId());
        Integer wareId = Integer.parseInt(dept.getRemark());
        Product product = this.productService.getById(model.getSecuritiesId());
        Date now = new Date();
        Integer totalBox = 0;
        for (CheckDetailVO vo : req.getList()) {
            totalBox = totalBox + vo.getCrownArray().size();
            CheckBackup backup = this.checkBackupService.getByRfidSerialNumber(vo.getRfid(), vo.getSerialNumber());
            CheckDetail detail = this.checkDetailService.getByRfidSerialNumber(vo.getRfid(), vo.getSerialNumber(), model.getId());
            if (req.getOpType() == 2) {// 2:车间抽检单入剔除品库确认 （对应shop_receive_list字段）
                // 只能入一次
                detail.setShopReceiveList(JSON.toJSONString(vo.getCrownArray()));
                detail.setShopReceiveOperCn(user.getRealName());
                detail.setShopReceiveCheck(checkUser.getRealName());
                detail.setShopReceiveTime(now);
                // 记录入库信息
                backup.setWorkshopCheckInCn(checkUser.getRealName());
                backup.setWorkshopCheckInOperatorCn(user.getRealName());
                backup.setWorkshopCheckInTime(now);
                // 抽检登记: 1.库房抽检 2:车间抽检入库3.车间抽检出库4库房抽检返回确认
                backup.setStatus(2);
                // 临时库库位区域：1:产成品区域2剔除品库区域（抽检单确认后默认选择2）
                backup.setAreaId(2);
                this.checkBackupService.updateById(backup);
                // 车间入库 修改抽检状态1:初始创建 2:抽检中  3: 抽检完成（仅当qty= qty_product时）
                model.setStatus(2);
                this.updateById(model);
                // FIXME 查询状态为5:主库抽检出库的 修改车间确认入库时间和状态6.车间抽检入库确认 抽捡状态2:车间入库
                this.baseInfoService.updateCheckStatus(vo.getRfid(), 5, 6, now, 2);
                Dict dict = dictService.getByVal("shopWareOpt", wareId, null);
                this.stockService.stockAdd(model.getSecuritiesId(), model.getSecurities(), 2,
                        wareId, dict.getName(), 0, 0, 0,
                        vo.getCrownArray().size());
                this.workshopLogService.addWorkshopLog(null, JSON.toJSONString(vo.getCrownArray()),
                        model.getSecuritiesId(), model.getSecurities(), detail.getRfid(),
                        detail.getSerialNumber(),
                        model.getDeptId(), model.getDept(), user.getId(), user.getRealName(),
                        checkUser.getId(), checkUser.getRealName(), 1, 5, 5, vo.getCrownArray().size(),
                        null);
                // FIXME 记录物流信息日志表
                this.logisticsService.add(detail.getRfid(), detail.getSerialNumber(),
                        wareId, null, 6, checkUser.getId(),
                        checkUser.getRealName(), user.getId(), user.getRealName(),
                        JSON.toJSONString(vo.getCrownArray()), null);
            } else if (req.getOpType() == 4) {// 4:车间抽检单机台到产成品库确认（对应shop_in_pro_list）
                // 可分多次入
//                if (StringUtils.isNotBlank(detail.getShopInProList())) {
//                    List<String> list = JSON.parseArray(detail.getShopInProList(), String.class);
//                    list.addAll(vo.getCrownArray());
//                    detail.setShopInProList(JSON.toJSONString(list));
//                } else {
                detail.setShopInProList(JSON.toJSONString(vo.getCrownArray()));
//                }
                detail.setShopInProOperCn(user.getRealName());
                detail.setShopInProCheck(checkUser.getRealName());
                detail.setShopInProTime(now);
                // 临时库库位区域：1:产成品区域2剔除品库区域（抽检单确认后默认选择2）
                backup.setAreaId(1);
                this.checkBackupService.updateById(backup);
                Dict dict = dictService.getByVal("shopWareOpt", wareId, null);
                this.stockService.stockAdd(model.getSecuritiesId(), model.getSecurities(), 1,
                        wareId, dict.getName(), 0, 0, 0,
                        vo.getCrownArray().size());
                this.workshopLogService.addWorkshopLog(null, JSON.toJSONString(vo.getCrownArray()),
                        model.getSecuritiesId(), model.getSecurities(), detail.getRfid(),
                        detail.getSerialNumber(),
                        model.getDeptId(), model.getDept(), user.getId(), user.getRealName(),
                        checkUser.getId(), checkUser.getRealName(), 3, 4, 7, vo.getCrownArray().size(),
                        null);
                // FIXME 记录物流信息日志表
//                this.logisticsService.add(detail.getRfid(), detail.getSerialNumber(),
//                        user.getSelfWareId(), null, 13, checkUser.getId(),
//                        checkUser.getRealName(), user.getId(), user.getRealName(),
//                        JSON.toJSONString(vo.getCrownArray()), null);
            } else if (req.getOpType() == 9) {// 9: 车间抽检机台返回剔除品库（很少发生，即没处理又返回剔除品库位了。只需将入库的冠字号，在shop_out_machine_list冠字号出库列表中去除）
                // 机台减少
                List<String> list = JSON.parseArray(detail.getShopOutMachineList(), String.class);
                list.removeAll(vo.getCrownArray());
                detail.setShopOutMachineList(JSON.toJSONString(list));
                Dict dict = dictService.getByVal("shopWareOpt", wareId, null);
                this.stockService.stockAdd(model.getSecuritiesId(), model.getSecurities(), 2,
                        wareId, dict.getName(), 0, 0, 0,
                        vo.getCrownArray().size());
                this.workshopLogService.addWorkshopLog(null, JSON.toJSONString(vo.getCrownArray()),
                        model.getSecuritiesId(), model.getSecurities(), detail.getRfid(),
                        detail.getSerialNumber(),
                        model.getDeptId(), model.getDept(), user.getId(), user.getRealName(),
                        checkUser.getId(), checkUser.getRealName(), 3, 4, 7, vo.getCrownArray().size(),
                        null);
                // FIXME 记录物流信息日志表
//                this.logisticsService.add(detail.getRfid(), detail.getSerialNumber(),
//                        user.getSelfWareId(), null, 14, checkUser.getId(),
//                        checkUser.getRealName(), user.getId(), user.getRealName(),
//                        JSON.toJSONString(vo.getCrownArray()), null);
            }
            this.checkDetailService.updateById(detail);
        }
        Integer piecesTotal = totalBox * product.getAmountPerBox();
        if (req.getOpType() == 2) {
            // 添加车间台账
            // 5封箱成品出入库台账-收入(付出负)
            this.workshopAccountService.shopIn(2, model.getDeptId(), model.getDept(), user.getId(),
                    user.getRealName(), model.getCheckId(), model.getChecker(), model.getOrderNo(),
                    piecesTotal, piecesTotal, 5, 1, "总库", null, model.getSecuritiesId(),
                    model.getSecurities());
            // 5封箱成品出入库台账-付出(收入负)
            this.workshopAccountService.shopOut(2, model.getDeptId(), model.getDept(), user.getId(),
                    user.getRealName(), model.getCheckId(), model.getChecker(), null, piecesTotal, 0, 5,
                    1, "印花成品", null, model.getSecuritiesId(), model.getSecurities());
            // 如果全部返检出库明细单 都存在确认入库时间 主单状态改为车间已入库
            // 4-收入(付出负)
            Integer inventory =
                    this.workshopAccountService.getLastInventory(model.getSecuritiesId(),
                            model.getDeptId()) + piecesTotal;
            this.workshopAccountService.shopIn(2, model.getDeptId(), model.getDept(), user.getId(),
                    user.getRealName(), model.getCheckId(), model.getChecker(), null, piecesTotal,
                    inventory, 4, 1, "封箱成品", null, model.getSecuritiesId(), model.getSecurities());
            this.stockService.getStock(model.getSecuritiesId(), wareId, 1);
            // 产成品库总数 + 入库数
//            Integer wareTotal = WareUtil.piecesTotal(stock1, product) + piecesTotal;
            Integer wareTotal = this.stockService.getProductStockTotal(wareId, model.getSecuritiesId(), product) + piecesTotal;
            // 2-收入(付出负)
            this.workshopAccountService.shopIn(2, model.getDeptId(), model.getDept(), user.getId(),
                    user.getRealName(), model.getCheckId(), model.getChecker(), null, piecesTotal,
                    wareTotal, 2, 2, "总库", null, model.getSecuritiesId(), model.getSecurities());
            // 2-付出(收入负)
            this.workshopAccountService.shopOut(2, model.getDeptId(), model.getDept(), user.getId(),
                    user.getRealName(), model.getCheckId(), model.getChecker(), null, piecesTotal,
                    (wareTotal - piecesTotal), 2, 1, "剔除品", null, model.getSecuritiesId(),
                    model.getSecurities());
            Integer eliminateStockTotal = this.stockService.getEliminateStockTotal(wareId, model.getSecuritiesId(), product);
            // 3-收入(付出负)
            this.workshopAccountService.shopIn(2, model.getDeptId(), model.getDept(), user.getId(),
                    user.getRealName(), model.getCheckId(), model.getChecker(), null, piecesTotal,
                    eliminateStockTotal, 3, 2, "封箱成品", null, model.getSecuritiesId(), model.getSecurities());
        } else if (req.getOpType() == 4) {
            this.stockService.getStock(model.getSecuritiesId(), wareId, 1);
            Integer wareTotal = this.stockService.getProductStockTotal(wareId, model.getSecuritiesId(), product);
//            Integer wareTotal = WareUtil.piecesTotal(stock1, product);
            // 2-收入
            this.workshopAccountService.shopIn(1, model.getDeptId(), model.getDept(), user.getId(),
                    user.getRealName(), model.getCheckId(), model.getChecker(), null, piecesTotal,
                    wareTotal, 2, 1, "机台", null, model.getSecuritiesId(), model.getSecurities());

        } else if (req.getOpType() == 9) {
            Integer eliminateStockTotal = this.stockService.getEliminateStockTotal(wareId, model.getSecuritiesId(), product);
            // 3-收入
            this.workshopAccountService.shopIn(1, model.getDeptId(), model.getDept(), user.getId(),
                    user.getRealName(), model.getCheckId(), model.getChecker(), null, piecesTotal,
                    eliminateStockTotal, 3, 1, "机台", null, model.getSecuritiesId(), model.getSecurities());
        }


    }

    @Override
    @Transactional
    public void shopOut(CheckShopOutInConfirmReq req, CacheUserVO user) {
        log.info("抽检车间出库={}", req);
        User checkUser = this.userService.getById(req.getCheckId());
        Check model = this.getByOrderNo(req.getOrderNo());
        Dept dept = this.deptService.getById(model.getDeptId());
        Integer wareId = Integer.parseInt(dept.getRemark());
        Product product = this.productService.getById(model.getSecuritiesId());
        Date now = new Date();
        Integer totalBox = 0;
        for (CheckDetailVO vo : req.getList()) {
            totalBox = totalBox + vo.getCrownArray().size();
            CheckBackup backup = this.checkBackupService.getByRfidSerialNumber(vo.getRfid(), vo.getSerialNumber());
            CheckDetail detail = this.checkDetailService.getByRfidSerialNumber(vo.getRfid(), vo.getSerialNumber(), model.getId());
            if (req.getOpType() == 3) {// 3:车间抽检单剔除品到机台确认（对应shop_out_machine_list）
                // 可分多次出
//                if (StringUtils.isNotBlank(detail.getShopOutMachineList())) {
//                    List<String> list = JSON.parseArray(detail.getShopOutMachineList(), String.class);
//                    list.addAll(vo.getCrownArray());
//                    detail.setShopOutMachineList(JSON.toJSONString(list));
//                } else {
                detail.setShopOutMachineList(JSON.toJSONString(vo.getCrownArray()));
//                }
                detail.setShopOutMachineOperCn(user.getRealName());
                detail.setShopOutMachineCheck(checkUser.getRealName());
                detail.setShopOutMachineTime(now);
                Dict dict = dictService.getByVal("shopWareOpt", wareId, null);
                this.stockService.stockSub(model.getSecuritiesId(), model.getSecurities(), 2,
                        wareId, dict.getName(), 0, 0, 0,
                        vo.getCrownArray().size());
                this.workshopLogService.addWorkshopLog(null, JSON.toJSONString(vo.getCrownArray()),
                        model.getSecuritiesId(), model.getSecurities(), detail.getRfid(),
                        detail.getSerialNumber(),
                        model.getDeptId(), model.getDept(), user.getDeptId(), user.getRealName(),
                        checkUser.getId(), checkUser.getRealName(), 5, 3, 6, vo.getCrownArray().size(),
                        null);
            } else if (req.getOpType() == 5) {// 车间抽检单产成品库出库确认（对应shop_out_list）
                // 只能出一次
                detail.setShopOutList(JSON.toJSONString(vo.getCrownArray()));
                detail.setShopOutOperCn(user.getRealName());
                detail.setShopOutcheck(checkUser.getRealName());
                detail.setShopOutTime(now);
                // 记录出库信息
                backup.setWorkshopCheckOutCn(checkUser.getRealName());
                backup.setWorkshopCheckOutOperatorCn(user.getRealName());
                backup.setWorkshopCheckOutTime(now);
                // 抽检登记: 1.库房抽检 2:车间抽检入库3.车间抽检出库4库房抽检返回确认
                backup.setStatus(3);
                this.checkBackupService.updateById(backup);
                // FIXME 查询状态为6:车间抽检入库确认 修改抽捡车间出库时间和状态7.车间抽检出库 抽捡状态3:车间出库
                this.baseInfoService.updateCheckStatus(vo.getRfid(), 6, 7, now, 3);
                Dict dict = dictService.getByVal("shopWareOpt", wareId, null);
                this.stockService.stockSub(model.getSecuritiesId(), model.getSecurities(), 1,
                        wareId, dict.getName(), 0, 0, 0,
                        vo.getCrownArray().size());
                this.workshopLogService.addWorkshopLog(null, JSON.toJSONString(vo.getCrownArray()),
                        model.getSecuritiesId(), model.getSecurities(), detail.getRfid(),
                        detail.getSerialNumber(),
                        model.getDeptId(), model.getDept(), user.getId(), user.getRealName(),
                        checkUser.getId(), checkUser.getRealName(), 4, 1, 8, vo.getCrownArray().size(),
                        null);
                this.logisticsService.add(detail.getRfid(), detail.getSerialNumber(),
                        wareId, null, 7, checkUser.getId(),
                        checkUser.getRealName(), user.getId(), user.getRealName(),
                        JSON.toJSONString(vo.getCrownArray()), null);
            }
            this.checkDetailService.updateById(detail);
        }
        Integer piecesTotal = totalBox * product.getAmountPerBox();
        if (req.getOpType() == 3) {
            Integer eliminateStockTotal = this.stockService.getEliminateStockTotal(wareId, model.getSecuritiesId(), product);
            // 3-付出
            this.workshopAccountService.shopOut(1, model.getDeptId(), model.getDept(), user.getId(),
                    user.getRealName(), model.getCheckId(), model.getChecker(), null, piecesTotal,
                    eliminateStockTotal, 3, 1, "机台", null, model.getSecuritiesId(), model.getSecurities());
        } else if (req.getOpType() == 5) {
            this.stockService.getStock(model.getSecuritiesId(), wareId, 1);
            // 2封箱成品实物收发卡-付出
//            Integer wareTotal1 = WareUtil.piecesTotal(stock1, product);
            Integer wareTotal1 = this.stockService.getProductStockTotal(wareId, model.getSecuritiesId(), product);
            this.workshopAccountService.shopOut(1,
                    model.getDeptId(), model.getDept(), user.getId(), user.getRealName(),
                    model.getCheckId(), model.getChecker(), null, piecesTotal,
                    wareTotal1, 2, 2, "总库", null, model.getSecuritiesId(),
                    model.getSecurities());
            // 2-付出
            // 4this.workshopAccountService.shopOut(1, model.getDeptId(), model.getDept(), model.getDeptId(), model.getDept(), user.getId(), user.getRealName(), model.getCheckId(), model.getChecker(), null, piecesTotal, wareTotal1, 2, 2, "总库", null, model.getSecuritiesId(), model.getSecurities());
            Integer inventory =
                    this.workshopAccountService.getLastInventory(model.getSecuritiesId(),
                            user.getDeptId()) - piecesTotal;
            // 4印花成品出入库台账-付出
            this.workshopAccountService.shopOut(1,
                    model.getDeptId(), model.getDept(), user.getId(), user.getRealName(),
                    model.getCheckId(), model.getChecker(), null, piecesTotal, inventory, 4, 2,
                    "封箱成品", null, model.getSecuritiesId(), model.getSecurities());
            // 5封箱成品出入库台账-收入
            this.workshopAccountService.shopIn(1,
                    model.getDeptId(), model.getDept(), user.getId(), user.getRealName(),
                    model.getCheckId(), model.getChecker(), null, piecesTotal, piecesTotal, 5, 2,
                    "印花成品", null, model.getSecuritiesId(), model.getSecurities());
            // 5封箱成品出入库台账-付入
            this.workshopAccountService.shopOut(1,
                    model.getDeptId(), model.getDept(), user.getId(), user.getRealName(),
                    model.getCheckId(), model.getChecker(), model.getOrderNo(), piecesTotal, 0, 5, 2,
                    "总库", null, model.getSecuritiesId(), model.getSecurities());
        }

    }

    @Override
    @Transactional
    public void wareIn(CheckWareInConfirmReq req, CacheUserVO user) {
        User checkUser = this.userService.getById(req.getCheckId());
        Check model = this.getByOrderNo(req.getOrderNo());
        Product product = this.productService.getById(model.getSecuritiesId());
        Date now = new Date();
        Integer totalBox = 0;
        for (CheckDetailVO vo : req.getList()) {
            totalBox = totalBox + vo.getCrownArray().size();
            CheckBackup backup = this.checkBackupService.getByRfidSerialNumber(vo.getRfid(), vo.getSerialNumber());
            CheckDetail detail = this.checkDetailService.getByRfidSerialNumber(vo.getRfid(), vo.getSerialNumber(), model.getId());
            detail.setWareInList(JSON.toJSONString(vo.getCrownArray()));
            detail.setWareInOperCn(user.getRealName());
            detail.setWareInCheck(checkUser.getRealName());
            detail.setWareInTime(now);
            this.checkDetailService.updateById(detail);
            backup.setCheckBackOperatorCn(user.getRealName());
            backup.setCheckBackCn(checkUser.getRealName());
            backup.setCheckBackTime(now);
            // 抽检登记: 1.库房抽检 2:车间抽检入库3.车间抽检出库4库房抽检返回确认
            backup.setStatus(4);
            backup.setReturnCrownList(JSON.toJSONString(vo.getCrownArray()));
            this.checkBackupService.updateById(backup);
            // FIXME 查询状态为7.车间抽检入库确认 修改抽查返回时间和状态8.主库抽检返回确认 抽捡状态4:主库入库
            BaseInfo info = this.baseInfoService.updateCheckStatus(vo.getRfid(), 7, 8, now, 4);
            this.stockService.stockSub(info.getSecuritiesId(), info.getSecurities(),
                    info.getLocAreaId(), info.getLocWareId(), info.getLocWare(), 0, 0, 0, vo.getCrownArray().size());
            // FIXME 记录物流信息日志表
            this.logisticsService.add(detail.getRfid(), detail.getSerialNumber(), model.getWareId(),
                    model.getWareCn(), 8, checkUser.getId(), checkUser.getRealName(), user.getId(),
                user.getRealName(), JSON.toJSONString(vo.getCrownArray()), null);
        }
        model.setQtyProduct(model.getQtyProduct() + totalBox);
        if (model.getQty().equals(model.getQtyProduct())) {
            // 车间入库 修改抽检状态1:初始创建 2:抽检中  3: 抽检完成（仅当qty= qty_product时）
            model.setStatus(3);
        }
        this.updateById(model);
        Integer piecesTotal = totalBox * product.getAmountPerBox();
        List<Stock> stockList = this.stockService.getStockList(model.getWareId(), model.getSecuritiesId());
        Integer wareTotal = WareUtil.piecesTotal(stockList, product);
//        Integer box = 0;
//        for (Stock stock : stockList) {
//            box = box + stock.getBoxNum() + stock.getRacketNum() * product.getBoxAmount() - stock.getCheckBoxNum();
//        }
//        Integer wareTotal = box * product.getAmountPerBox();
        this.workshopAccountService.shopIn(1, model.getDeptId(), model.getDept(), user.getId(),
                user.getRealName(), model.getCheckId(), model.getChecker(), null, piecesTotal,
                wareTotal, 1, 1, model.getDept(), model.getWareId(), model.getSecuritiesId(),
                model.getSecurities());

    }

    @Override
    public List<BaseInfo> securitiesOpt() {
        LambdaQueryWrapper<BaseInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseInfo::getStatus, 4);
        queryWrapper.groupBy(BaseInfo::getStatus);
        return this.baseInfoService.list(queryWrapper);
    }

    @Override
    public Check getByOrderNo(String orderNo) {
        LambdaQueryWrapper<Check> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Check::getOrderNo, orderNo);
        return this.getOne(queryWrapper);
    }


    public void addOrderNo(String securities, Integer deptId) {
        String key = "check_num:" + securities + "_" + deptId;
        this.redisService.set(key, String.valueOf(Integer.parseInt(this.redisService.get(key)) + 1));
    }

    public String createOrderNo(String securities, Integer deptId) {
        // 车间出库单号由系统自动生成，编号由“品名+部门编号+T2+3位数字编号”构成，Y211-1T2001
        // 车间出库单号
        String resp = null;
        String key = "check_num:" + securities + "_" + deptId;
        if (redisService.hasKey(key)) {
            resp = deptId + "-" + securities + "-" + String.format("%03d", Integer.parseInt(this.redisService.get(key)) + 1);
        } else {
            this.redisService.set(key, "0");
            resp = deptId + "-" + securities + "-" + String.format("%03d", 1);
        }
        return resp;
    }

}
