package com.gree.mall.manager.logic.material.stock;

import cn.hutool.core.collection.CollectionUtil;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.material.stock.WebsitStockDTO;
import com.gree.mall.manager.enums.material.DirectFlagEnum;
import com.gree.mall.manager.enums.material.PartsAttrEnum;
import com.gree.mall.manager.enums.material.WebsitGoodsTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class WebitPurchaseStockLogic {

    @Resource
    MaterialGoodsStockLogic materialGoodsStockLogic;
    @Resource
    StorageService storageService;

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void newInStock(WebsitPurchase purchase, List<WebsitPurchaseItem> websitPurchaseItems, String refType) throws Exception {
        List<WebsitStockDTO> shopStockDTOS = new ArrayList<>();
        for (WebsitPurchaseItem websitPurchaseItem : websitPurchaseItems) {
            if (websitPurchaseItem.getInStockQty().compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            // 入库注值
            WebsitStockDTO websitStockDTO = new WebsitStockDTO();
            websitStockDTO.setCompanyWechatId(websitPurchaseItem.getCompanyWechatId());
            websitStockDTO.setCompanyWechatName(purchase.getCompanyWechatName());
            websitStockDTO.setWebsitId(websitPurchaseItem.getWebsitId());
            websitStockDTO.setWebsitName(purchase.getWebsitName());
            websitStockDTO.setSdate(purchase.getCreateTime());
            websitStockDTO.setPartsAttr(PartsAttrEnum.NEW.toString());
            websitStockDTO.setGoodsId(websitPurchaseItem.getGoodsId());
            websitStockDTO.setGoodsName(websitPurchaseItem.getGoodsName());
            websitStockDTO.setGoodsType(websitPurchaseItem.getGoodsType());
            websitStockDTO.setPrice(websitPurchaseItem.getCost());
            websitStockDTO.setRef(websitPurchaseItem.getPurchaseId());
            websitStockDTO.setRefType(refType);
            websitStockDTO.setChangeQty(websitPurchaseItem.getInStockQty());
            websitStockDTO.setDirectFlag(DirectFlagEnum.ADD.getKey());
            websitStockDTO.setRemark(purchase.getRemark());
            websitStockDTO.setOperateBy(purchase.getConfirmBy());
            websitStockDTO.setOperateTime(purchase.getConfirmTime());
            websitStockDTO.setObj("供应商");
            websitStockDTO.setStorageId(purchase.getStorageId());
            shopStockDTOS.add(websitStockDTO);
        }

        if (CollectionUtil.isEmpty(shopStockDTOS)) {
            return;
        }

        // 开始处理库存
        materialGoodsStockLogic.handleWebsitStock(shopStockDTOS);
    }

    public void newRetStock(WebsitPurchaseRet purchaseRet, List<WebsitPurchaseRetItem> purchaseRetItems, String refType) throws Exception {
        List<WebsitStockDTO> shopStockDTOS = new ArrayList<>();
        for (WebsitPurchaseRetItem websitPurchaseItem : purchaseRetItems) {
            // 出库注值
            WebsitStockDTO websitStockDTO = new WebsitStockDTO();
            websitStockDTO.setCompanyWechatId(websitPurchaseItem.getCompanyWechatId());
            websitStockDTO.setCompanyWechatName(purchaseRet.getCompanyWechatName());
            websitStockDTO.setWebsitId(websitPurchaseItem.getWebsitId());
            websitStockDTO.setWebsitName(websitPurchaseItem.getWebsitName());
            websitStockDTO.setSdate(purchaseRet.getCreateTime());
            websitStockDTO.setPartsAttr(PartsAttrEnum.NEW.toString());
            websitStockDTO.setGoodsId(websitPurchaseItem.getGoodsId());
            websitStockDTO.setGoodsName(websitPurchaseItem.getGoodsName());
            websitStockDTO.setGoodsType(websitPurchaseItem.getGoodsType());
            websitStockDTO.setPrice(websitPurchaseItem.getCost());
            websitStockDTO.setRef(websitPurchaseItem.getPurchaseRetId());
            websitStockDTO.setRefType(refType);
            websitStockDTO.setChangeQty(websitPurchaseItem.getRetQty());
            websitStockDTO.setDirectFlag(DirectFlagEnum.SUB.getKey());
            websitStockDTO.setRemark(purchaseRet.getRemark());
            websitStockDTO.setOperateBy(purchaseRet.getConfirmBy());
            websitStockDTO.setOperateTime(purchaseRet.getConfirmTime());
            websitStockDTO.setObj("供应商");
            websitStockDTO.setStorageId(purchaseRet.getStorageId());
            shopStockDTOS.add(websitStockDTO);
        }

        // 开始处理库存
        materialGoodsStockLogic.handleWebsitStock(shopStockDTOS);
    }

    public void adjustmentStock(WebsitPurchaseAdjustment purchaseAdjustment, List<WebsitPurchaseAdjustmentItem> changeAdjustList, String refType) throws Exception {
        List<WebsitStockDTO> shopStockDTOS = new ArrayList<>();
        for (WebsitPurchaseAdjustmentItem adjustmentItem : changeAdjustList) {
            // 入库注值
            WebsitStockDTO subStockDTO = new WebsitStockDTO();
            subStockDTO.setCompanyWechatId(purchaseAdjustment.getCompanyWechatId());
            subStockDTO.setCompanyWechatName(purchaseAdjustment.getCompanyWechatName());
            subStockDTO.setWebsitId(purchaseAdjustment.getWebsitId());
            subStockDTO.setWebsitName(purchaseAdjustment.getWebsitName());
            subStockDTO.setSdate(purchaseAdjustment.getCreateTime());
            subStockDTO.setPartsAttr(PartsAttrEnum.NEW.toString());
            subStockDTO.setGoodsId(adjustmentItem.getGoodsId());
            subStockDTO.setGoodsName(adjustmentItem.getGoodsName());
            subStockDTO.setGoodsType(WebsitGoodsTypeEnum.M.getKey());
            subStockDTO.setPrice(adjustmentItem.getCost());
            subStockDTO.setRef(adjustmentItem.getPurchaseAdjustmentId());
            subStockDTO.setRefType(refType);
            subStockDTO.setChangeQty(adjustmentItem.getInStockQty());
            subStockDTO.setDirectFlag(DirectFlagEnum.SUB.getKey());
            subStockDTO.setRemark(purchaseAdjustment.getRemark());
            subStockDTO.setOperateBy(purchaseAdjustment.getConfirmBy());
            subStockDTO.setOperateTime(purchaseAdjustment.getConfirmTime());
            subStockDTO.setObj("供应商");
            subStockDTO.setStorageId(purchaseAdjustment.getStorageId());
            shopStockDTOS.add(subStockDTO);

            WebsitStockDTO addStockDTO = new WebsitStockDTO();
            addStockDTO.setCompanyWechatId(purchaseAdjustment.getCompanyWechatId());
            addStockDTO.setCompanyWechatName(purchaseAdjustment.getCompanyWechatName());
            addStockDTO.setWebsitId(purchaseAdjustment.getWebsitId());
            addStockDTO.setWebsitName(purchaseAdjustment.getWebsitName());
            addStockDTO.setSdate(purchaseAdjustment.getCreateTime());
            addStockDTO.setPartsAttr(PartsAttrEnum.NEW.toString());
            addStockDTO.setGoodsId(adjustmentItem.getGoodsId());
            addStockDTO.setGoodsName(adjustmentItem.getGoodsName());
            addStockDTO.setGoodsType(WebsitGoodsTypeEnum.M.getKey());
            addStockDTO.setPrice(adjustmentItem.getAdjustCost());
            addStockDTO.setRef(adjustmentItem.getPurchaseAdjustmentId());
            addStockDTO.setRefType(refType);
            addStockDTO.setChangeQty(adjustmentItem.getAdjustInStockQty());
            addStockDTO.setDirectFlag(DirectFlagEnum.ADD.getKey());
            addStockDTO.setRemark(purchaseAdjustment.getRemark());
            addStockDTO.setOperateBy(purchaseAdjustment.getConfirmBy());
            addStockDTO.setOperateTime(purchaseAdjustment.getConfirmTime());
            addStockDTO.setObj("供应商");
            addStockDTO.setStorageId(purchaseAdjustment.getStorageId());
            addStockDTO.setPurchaseId(purchaseAdjustment.getRef());
            shopStockDTOS.add(addStockDTO);
        }

        if (CollectionUtil.isEmpty(shopStockDTOS)) {
            return;
        }

        // 开始处理库存
        materialGoodsStockLogic.handleWebsitStock(shopStockDTOS);
    }

    public void newInStock(List<WebsitPartsNewInRecord> shopNewInRecords) throws Exception {
        List<WebsitStockDTO> shopStockDTOS = new ArrayList<>();
        for (WebsitPartsNewInRecord inRecord : shopNewInRecords) {
            // 入库注值
            WebsitStockDTO websitStockDTO = new WebsitStockDTO();
            websitStockDTO.setCompanyWechatId(inRecord.getCompanyWechatId());
            websitStockDTO.setCompanyWechatName(inRecord.getCompanyWechatName());
            websitStockDTO.setWebsitId(inRecord.getReceiveWebsitId());
            websitStockDTO.setWebsitName(inRecord.getReceiveWebsitName());
            websitStockDTO.setPartsWebsitId(inRecord.getReceivePartsWebsitId());
            websitStockDTO.setSdate(inRecord.getCreateTime());
            websitStockDTO.setPartsAttr(PartsAttrEnum.NEW.toString());
            websitStockDTO.setVoucherNo(inRecord.getVoucherNo());
            websitStockDTO.setApplyNo(inRecord.getVoucherNo());
            websitStockDTO.setGoodsId(inRecord.getPartsNumber());
            websitStockDTO.setGoodsName(inRecord.getPartsName());
            websitStockDTO.setGoodsType(WebsitGoodsTypeEnum.P.getKey());
            websitStockDTO.setPrice(inRecord.getPrice());
            websitStockDTO.setRef(inRecord.getId());
            websitStockDTO.setRefType(inRecord.getObjectType());
            websitStockDTO.setChangeQty(inRecord.getQty());
            websitStockDTO.setDirectFlag(DirectFlagEnum.ADD.getKey());
            websitStockDTO.setRemark(inRecord.getRemark());
            websitStockDTO.setOperateBy(inRecord.getCheckBy());
            websitStockDTO.setOperateTime(inRecord.getCheckTime());
            websitStockDTO.setObj("网点");
            websitStockDTO.setStorageId(inRecord.getStorageId());
            websitStockDTO.setGoodsStockUnit(inRecord.getGoodsStockUnit());
            websitStockDTO.setMaterialGroupName(inRecord.getMaterialGroupName());
            shopStockDTOS.add(websitStockDTO);
        }

        if (CollectionUtil.isEmpty(shopStockDTOS)) {
            return;
        }

        // 开始处理库存
        materialGoodsStockLogic.handleWebsitStock(shopStockDTOS);
    }

    public Storage handleStorage(AdminUserCom adminUser, String websitId, String goodsType, String storageId) {
//        String storageType = goodsType.equals(WebsitGoodsTypeEnum.M.getKey()) ? WebsitGoodsTypeEnum.M.getRemark() : WebsitGoodsTypeEnum.P.getRemark();
//        if (adminUser.getAdminCompanyWechat().getJoinCode().equals("NO")) {
//            final Storage storage = storageService.lambdaQuery()
//                    .eq(Storage::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
//                    .eq(Storage::getIsDefault, true)
//                    .like(Storage::getType, storageType)
//                    .last("limit 1")
//                    .one();
//            if (Objects.isNull(storage)) {
//                throw new RemoteServiceException("未发现默认仓");
//            }
//
//            storageId = storage.getStorageId();
//        } else {
            if (StringUtils.isBlank(storageId)) {
                throw new RemoteServiceException("请选择仓位");
            }
//        }

        final Storage storage = storageService.lambdaQuery()
                .eq(Storage::getStorageId, storageId)
                .eq(Storage::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(Storage::getWebsitId, websitId)
                .last("limit 1")
                .one();
        if (Objects.isNull(storage)) {
            throw new RemoteServiceException("仓位信息不存在");
        }

        if (!storage.getStatus()) {
            throw new RemoteServiceException("仓位信息已失效");
        }

        return storage;
    }



}
