package com.fjhx.wms.service.stock.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.common.utils.Assert;
import com.fjhx.item.entity.product.po.ProductInfo;
import com.fjhx.item.service.product.ProductInfoService;
import com.fjhx.wms.entity.arrival.po.ArrivalStockRecords;
import com.fjhx.wms.entity.arrival.po.ArrivalStockRecordsDetails;
import com.fjhx.wms.entity.stock.dto.StockJournalDetailsDto;
import com.fjhx.wms.entity.stock.dto.StockJournalSelectDto;
import com.fjhx.wms.entity.stock.po.*;
import com.fjhx.wms.entity.stock.vo.StockJournalDetailsVo;
import com.fjhx.wms.entity.stock.vo.StockWaitVo;
import com.fjhx.wms.mapper.stock.StockJournalDetailsMapper;
import com.fjhx.wms.service.arrival.ArrivalStockRecordsDetailsService;
import com.fjhx.wms.service.arrival.ArrivalStockRecordsService;
import com.fjhx.wms.service.stock.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.system.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 出入库记录明细 服务实现类
 * </p>
 *
 * @author
 * @since 2023-03-20
 */
@Service
public class StockJournalDetailsServiceImpl extends ServiceImpl<StockJournalDetailsMapper, StockJournalDetails> implements StockJournalDetailsService {
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private StockWaitService stockWaitService;
    @Autowired
    private StockService stockService;
    @Autowired
    private StockJournalService stockJournalService;
    @Autowired
    private StockJournalDetailsEditRecordService stockJournalDetailsEditRecordService;
    @Autowired
    private StockWaitDetailsService stockWaitDetailsService;
    @Autowired
    private ArrivalStockRecordsDetailsService arrivalStockRecordsDetailsService;
    @Autowired
    private ArrivalStockRecordsService arrivalStockRecordsService;
    @Autowired
    private StockJournalDetailsService stockJournalDetailsService;

    @Override
    public Page<StockJournalDetailsVo> getPage(StockJournalSelectDto dto) {
        IWrapper<StockJournalDetails> wrapper = getWrapper();
        wrapper.eq("sj.op_type", dto.getOpType());
        wrapper.eq("sj.type", dto.getType());
        wrapper.eq("w.id", dto.getWarehouseId());
        wrapper.eq("sj.to_warehouse_id", dto.getToWarehouseId());
        wrapper.eq("sjd.product_id", dto.getProductId());
        wrapper.orderByDesc("sj", StockJournal::getCreateTime);

        if (ObjectUtil.isNotEmpty(dto.getKeyword())) {
            //产品编号过滤
            List<Long> productIds = productInfoService.listObject(ProductInfo::getId, q -> q.like(ProductInfo::getCustomCode, dto.getKeyword()).or()
                    .like(ProductInfo::getName, dto.getKeyword()));
            wrapper.and(q -> q.like("w.name", dto.getKeyword()).or()
                    .like("sj.link_code", dto.getKeyword()).or()
                    .in("sjd.product_id", productIds)
            );
        }

        Page<StockJournalDetailsVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<StockJournalDetailsVo> records = page.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return page;
        }
        // 赋值产品属性
        productInfoService.attributeAssign(records, StockJournalDetailsVo::getProductId, (item, product) -> {
            item.setProductCode(product.getCode());
            item.setProductUnit(product.getUnit());
            item.setProductType(product.getType());
            item.setProductName(product.getName());
            item.setProductSpec(product.getSpec());
            item.setProductCustomCode(product.getCustomCode());
        });
        //赋值操作人名称
        UserUtil.assignmentNickName(records, StockJournalDetailsVo::getCreateUser, StockJournalDetailsVo::setOpUserName);
        return page;
    }

    @Override
    public Page<StockJournalDetailsVo> getPageByWdly(StockJournalSelectDto dto) {
        Page<StockJournalDetailsVo> page = getPage(dto);
        List<StockJournalDetailsVo> records = page.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return page;
        }
        //给 采购退货 采购到货 的数据赋值关联单号
        List<Long> swIds = records.stream().map(StockJournalDetailsVo::getBusinessId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(swIds)) {
            Map<Long, StockWait> stockWaitMap = stockWaitService.mapKEntity(StockWait::getId, q -> q.in(StockWait::getId, swIds));
            for (StockJournalDetailsVo record : records) {
                StockWait stockWait = stockWaitMap.get(record.getBusinessId());
                if (ObjectUtil.isEmpty(stockWait)) {
                    continue;
                }
                record.setLinkCode(stockWait.getBusinessCode());
            }
        }
        //给 到货质检 赋值关联单号
        List<Long> qIds = records.stream().map(StockJournalDetailsVo::getBusinessId).distinct().filter(Objects::nonNull).collect(Collectors.toList());
        IWrapper<StockWait> wrapper = IWrapper.getWrapper();
        wrapper.in("qi", StockWait::getId, qIds);
        List<StockWaitVo> stockWaitInfo = baseMapper.getStockWaitInfo(wrapper);
        Map<Long, String> stockWaitInfoMap = stockWaitInfo.stream().collect(Collectors.toMap(StockWait::getId, StockWait::getBusinessCode));
        for (StockJournalDetailsVo record : records) {
            String linkCode = stockWaitInfoMap.get(record.getBusinessId());
            if (ObjectUtil.isEmpty(linkCode)) {
                continue;
            }
            record.setLinkCode(linkCode);
        }
        return page;
    }

    @Override
    public StockJournalDetailsVo detail(Long id) {
        StockJournalDetails StockJournalDetails = this.getById(id);
        StockJournalDetailsVo result = BeanUtil.toBean(StockJournalDetails, StockJournalDetailsVo.class);
        return result;
    }

    @Override
    public void add(StockJournalDetailsDto stockJournalDetailsDto) {
        this.save(stockJournalDetailsDto);
    }

    @Override
    public void edit(StockJournalDetailsDto stockJournalDetailsDto) {
        this.updateById(stockJournalDetailsDto);
    }

    @Override
    public void delete(Long id) {
        this.removeById(id);
    }

    /**
     * 维多利亚流水数量修正
     */
    @DSTransactional
    @Override
    public synchronized void editQuantity(StockJournalDetails dto) {
        Assert.notEmpty(dto.getId(), "流水明细id不能为空");
        StockJournalDetails stockJournalDetails = getById(dto.getId());

        //根据流水获取入库批次
        List<Long> stockJournalDetailsList = stockJournalDetailsService.listObject(StockJournalDetails::getId,q -> q
                .eq(StockJournalDetails::getBusinessDetailsId,stockJournalDetails.getBusinessDetailsId())
                .eq(StockJournalDetails::getProductId,stockJournalDetails.getProductId())
                .eq(StockJournalDetails::getQuantity,stockJournalDetails.getQuantity())
                .orderByAsc(StockJournalDetails::getCreateTime)
        );
        int batchIndex = stockJournalDetailsList.indexOf(stockJournalDetails.getId());
        if(batchIndex==-1){
            throw new ServiceException("找不到入库批次信息");
        }

        //保存操作记录
        StockJournalDetailsEditRecord stockJournalDetailsEditRecord = new StockJournalDetailsEditRecord();
        stockJournalDetailsEditRecord.setStockJournalDetailsId(dto.getId());
        stockJournalDetailsEditRecord.setOriginalQuantity(stockJournalDetails.getQuantity());
        stockJournalDetailsEditRecord.setChangeQuantity(dto.getQuantity());

        stockJournalDetailsEditRecordService.save(stockJournalDetailsEditRecord);

        //修改库存
        StockJournal stockJournal = stockJournalService.getById(stockJournalDetails.getStockJournalId());
        BigDecimal subtract;
        if (stockJournal.getOpType() == 1) {
            subtract = dto.getQuantity().subtract(stockJournalDetails.getQuantity());
        } else if (stockJournal.getOpType() == 2) {
            subtract = stockJournalDetails.getQuantity().subtract(dto.getQuantity());
        } else {
            throw new ServiceException("未知流水操作类型");
        }
        boolean update = stockService.update(q -> q
                .eq(Stock::getProductId, stockJournalDetails.getProductId())
                .eq(Stock::getWarehouseId, stockJournal.getWarehouseId())
                .setSql("victoriatourist_json = JSON_SET(victoriatourist_json,'$.frozenQuantity',ifnull(json_unquote(victoriatourist_json -> '$.frozenQuantity'), 0) + "+subtract+")")
        );
        if (!update) {
            throw new ServiceException("操作失败请重试");
        }
        //修改待出入库数据
        Long stockWaitDetailsId = stockJournalDetails.getBusinessDetailsId();
        Assert.notEmpty(stockWaitDetailsId,"无法关联入库信息，操作失败");


        boolean update1 = stockWaitDetailsService.update(q -> q
                .eq(StockWaitDetails::getId, stockWaitDetailsId)
                .setSql("receipt_quantity = receipt_quantity+"+subtract)
        );
        if (!update1) {
            throw new ServiceException("操作失败请重试");
        }
        //修改待入库状态
        StockWaitDetails stockWaitDetails = stockWaitDetailsService.getById(stockWaitDetailsId);
        Assert.notEmpty(stockWaitDetails,"无法查询到关联待入库信息，操作失败");
        StockWait stockWait = stockWaitService.getById(stockWaitDetails.getStockWaitId());

        if (stockWait.getStatus()!=3) {
            if (stockWaitDetails.getQuantity().compareTo(stockWaitDetails.getReceiptQuantity()) <= 0) {
                //完全入库
                stockWait.setStatus(2);
            } else {
                //部分入库
                stockWait.setStatus(1);
            }
        }
        stockWaitService.updateById(stockWait);

        //修改待质检数量
        List<Long> arrivalStockRecordsDetailsIds = arrivalStockRecordsDetailsService.listObject(ArrivalStockRecordsDetails::getId, q -> q
                .eq(ArrivalStockRecordsDetails::getBusinessDetailsId, stockJournalDetails.getBusinessDetailsId())
                .eq(ArrivalStockRecordsDetails::getProductInfoId, stockJournalDetails.getProductId())
                .eq(ArrivalStockRecordsDetails::getQuantity, stockJournalDetails.getQuantity())
                .orderByAsc(ArrivalStockRecordsDetails::getCreateTime)
        );

        //根据批次获取到入库记录
        Long arrivalStockRecordsDetailsId = arrivalStockRecordsDetailsIds.get(batchIndex);

        ArrivalStockRecordsDetails oldarrivalStockRecordsDetails = arrivalStockRecordsDetailsService.getById(arrivalStockRecordsDetailsId);
        Assert.notEmpty(oldarrivalStockRecordsDetails,"查询不到相关质检信息");
        if(oldarrivalStockRecordsDetails.getQualityQuantity().compareTo(oldarrivalStockRecordsDetails.getQuantity())>=0){
            throw new ServiceException("该记录已质检完成禁止修改");
        }

        boolean update2 = arrivalStockRecordsDetailsService.update(q -> q
                .eq(ArrivalStockRecordsDetails::getId, arrivalStockRecordsDetailsId)
                .setSql("quantity = quantity+"+subtract)
        );
        if (!update2) {
            throw new ServiceException("操作失败请重试");
        }

        //修改质检状态
        ArrivalStockRecordsDetails arrivalStockRecordsDetails = arrivalStockRecordsDetailsService.getOne(q -> q
                .eq(ArrivalStockRecordsDetails::getBusinessDetailsId, stockWaitDetailsId)
        );
        ArrivalStockRecords arrivalStockRecords = arrivalStockRecordsService.getById(arrivalStockRecordsDetails.getArrivalStockRecordsId());
        if (arrivalStockRecordsDetails.getQuantity().compareTo(arrivalStockRecordsDetails.getQualityQuantity()) <= 0) {
            //完全质检
            arrivalStockRecords.setQualityStatus(2);
        } else {
            //部分质检
            arrivalStockRecords.setQualityStatus(1);
        }
        arrivalStockRecordsService.updateById(arrivalStockRecords);


        stockJournalDetails.setQuantity(dto.getQuantity());
        this.updateById(stockJournalDetails);
    }

}
