package com.zfire.mall.manager.logic.k3;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.k3.KingDeePurchaseStockOutAdd;
import com.zfire.mall.manager.bean.k3.KingDeePurchaseStockOutData;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.stock.StockCommonLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.KingDeePurchaseStockOutItemService;
import com.zfire.mall.manager.plus.service.KingDeePurchaseStockOutService;
import com.zfire.mall.manager.plus.service.StockCorrespondService;
import com.zfire.mall.manager.plus.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class K3PurchaseStockOutLogic {

    @Autowired
    KingDeePurchaseStockOutItemService kingDeePurchaseStockOutItemService;

    @Autowired
    KingDeePurchaseStockOutService kingDeePurchaseStockOutService;

    @Autowired
    StockCorrespondService stockCorrespondService;


    @Autowired
    StockService stockService;

    @Autowired
    StockCommonLogic stockCommonLogic;

    @Autowired
    CommonLogic commonLogic;

    public void add(KingDeePurchaseStockOutAdd kingDeePurchaseStockInAdd) {
        kingDeePurchaseStockInAdd.setId(IdWorker.getIdStr());
        kingDeePurchaseStockInAdd.setBillNo(kingDeePurchaseStockInAdd.getId());
        kingDeePurchaseStockInAdd.setCancelStatus(ExamineStatusEnum.WAIT.getKey());
        kingDeePurchaseStockInAdd.setForDate(new Date());
        kingDeePurchaseStockInAdd.insert();

        List<StockCorrespond> list = stockCorrespondService.lambdaQuery().list();

        for (KingDeePurchaseStockOutItem kingDeePurchaseStockOutItem : kingDeePurchaseStockInAdd.getKingDeePurchaseStockOutItems()) {

            kingDeePurchaseStockOutItem.setBillNo(kingDeePurchaseStockInAdd.getBillNo());

            if (StringUtils.isEmpty(kingDeePurchaseStockOutItem.getStockId()))
                throw new RemoteServiceException("仓库空了");


            List<StockCorrespond> collect = list.stream().filter(item -> item.getId().equals(kingDeePurchaseStockOutItem.getStockId())).collect(Collectors.toList());

            if (CollectionUtils.isEmpty(collect))
                throw new RemoteServiceException("未找到对应仓库");


            StockCorrespond stockCorrespond = collect.get(0);

            kingDeePurchaseStockOutItem.setStockName(stockCorrespond.getName());

        }

        kingDeePurchaseStockOutItemService.saveBatch(kingDeePurchaseStockInAdd.getKingDeePurchaseStockOutItems());
    }

    public void update(KingDeePurchaseStockOutAdd kingDeePurchaseStockInAdd) {

        kingDeePurchaseStockInAdd.updateById();

        kingDeePurchaseStockOutItemService.lambdaUpdate()
                .eq(KingDeePurchaseStockOutItem::getBillNo,kingDeePurchaseStockInAdd.getBillNo())
                .remove();

        for (KingDeePurchaseStockOutItem kingDeePurchaseStockOutItem : kingDeePurchaseStockInAdd.getKingDeePurchaseStockOutItems()) {

            kingDeePurchaseStockOutItem.setBillNo(kingDeePurchaseStockInAdd.getBillNo());
        }

        kingDeePurchaseStockOutItemService.saveBatch(kingDeePurchaseStockInAdd.getKingDeePurchaseStockOutItems());
    }

    @Transactional(rollbackFor = Exception.class)
    public void examine(String billNo, String cancelStatus) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        KingDeePurchaseStockOut kingDeePurchaseStockOut = kingDeePurchaseStockOutService.getById(billNo);
        kingDeePurchaseStockOut.setCancelStatus(cancelStatus);

        kingDeePurchaseStockOut.setApproveDate(new Date());

        kingDeePurchaseStockOut.setApproverId(adminUser.getNickName());
        kingDeePurchaseStockOut.updateById();

        if (cancelStatus.equals(ExamineStatusEnum.OK.getKey())) {

            List<KingDeePurchaseStockOutItem> kingDeePurchaseStockOutItems = kingDeePurchaseStockOutItemService.lambdaQuery().eq(KingDeePurchaseStockOutItem::getBillNo, billNo).list();
            for (KingDeePurchaseStockOutItem kingDeePurchaseStockOutItem : kingDeePurchaseStockOutItems) {
                this.stockSub(kingDeePurchaseStockOut, kingDeePurchaseStockOutItem);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void stockSub(KingDeePurchaseStockOut kingDeePurchaseStockOut, KingDeePurchaseStockOutItem kingDeePurchaseStockOutItem) {

        Stock stock = stockService.lambdaQuery().eq(Stock::getStockId, kingDeePurchaseStockOutItem.getStockId())
                .eq(Stock::getMaterialId, kingDeePurchaseStockOutItem.getMaterialId()).last("limit 1").one();

        if (stock == null)
            throw new RemoteServiceException(kingDeePurchaseStockOutItem.getMaterialName()+"该物料没有库存，不能退库");


        stockCommonLogic.stockAccLog("采购退料单减少库存",stock,kingDeePurchaseStockOutItem.getRmRealQty(),kingDeePurchaseStockOutItem.getBillNo(),false,"采购退料单");

        stock.setStockQty(stock.getStockQty().subtract(kingDeePurchaseStockOutItem.getRmRealQty()));

        if (stock.getStockQty().doubleValue() < 1)
            throw new RemoteServiceException(kingDeePurchaseStockOutItem.getMaterialName()+"该物料没有库存，不能退库");

        stock.updateById();

    }

    public KingDeePurchaseStockOutData detail(String id) {
        KingDeePurchaseStockOut kingDeePurchaseStockOut = kingDeePurchaseStockOutService.getById(id);

        KingDeePurchaseStockOutData kingDeePurchaseStockOutData = BeanUtil.toBean(kingDeePurchaseStockOut, KingDeePurchaseStockOutData.class);

        List<KingDeePurchaseStockOutItem> list = kingDeePurchaseStockOutItemService.lambdaQuery().eq(KingDeePurchaseStockOutItem::getBillNo, id).list();

        kingDeePurchaseStockOutData.setKingDeePurchaseStockOutItems(list);
        return kingDeePurchaseStockOutData;
    }
}
