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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.listvo.material.WebsitStockAccPVO;
import com.gree.mall.manager.bean.listvo.material.WebsitStockAccVO;
import com.gree.mall.manager.bean.listvo.material.WebsitStockPVO;
import com.gree.mall.manager.bean.listvo.material.WebsitStockVO;
import com.gree.mall.manager.commonmapper.CommonMapper;
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.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.CommonUtils;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class WebsitStockLogic {

    private final CommonLogic commonLogic;
    private final CommonMapper commonMapper;
    private final WebsitGoodsService websitGoodsService;
    private final WebsitStockService websitStockService;
    private final WebsitStockAccService websitStockAccService;
    private final AdminWebsitService adminWebsitService;
    private final WebsitGoodsPriceService websitGoodsPriceService;
    private final GoodsMaterialStockAccService goodsMaterialStockAccService;
    private final StorageService storageService;
    private final GoodsMaterialStorageService goodsMaterialStorageService;

    /**
     * 网点库存列表
     * @param zfireParamBean
     * @return
     */
    public IPage<WebsitStockVO> websitStockList(ZfireParamBean zfireParamBean){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean,WebsitStockVO.class,adminUser);

        IPage<WebsitStockVO> websitStockVOIPage = commonMapper.websitStockList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return websitStockVOIPage;
    }

    /**
     * 网点库存明细
     * @param zfireParamBean
     * @return
     */
    public IPage<WebsitStockAccVO> websitStockAccList(ZfireParamBean zfireParamBean){
        FieldUtils.supplyParam(zfireParamBean,WebsitStockAccVO.class,commonLogic.getAdminUser());
        IPage<WebsitStockAccVO> page = commonMapper.websitStockAccList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return page;
    }


    /**
     * 配件库存列表
     * @param zfireParamBean
     * @return
     */
    public IPage<WebsitStockPVO> websitStockPList(ZfireParamBean zfireParamBean){
        FieldUtils.supplyParam(zfireParamBean,WebsitStockPVO.class,commonLogic.getAdminUser());
        IPage<WebsitStockPVO> websitStockVOIPage = commonMapper.websitStockPList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return websitStockVOIPage;
    }

    /**
     * 配件库存明细
     * @param zfireParamBean
     * @return
     */
    public IPage<WebsitStockAccPVO> websitStockAccPList(ZfireParamBean zfireParamBean){
        FieldUtils.supplyParam(zfireParamBean,WebsitStockAccPVO.class,commonLogic.getAdminUser());
        IPage<WebsitStockAccPVO> page = commonMapper.websitStockAccPList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return page;
    }



    /**
     * 导入网点库存(各个商品只能导第一次)
     * @param datas
     */
    public void importData(List<Object> datas, WebsitGoodsTypeEnum websitGoodsTypeEnum){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<WebsitStock> websitStocks = new ArrayList<>();
        List<WebsitStockAcc> websitStockAccs = new ArrayList<>();
        for(int i= 0 ;i<datas.size() ; i++){
            List<String> row = (List<String>)datas.get(i);
            CommonUtils.initList(row,10);
            String goodsId = row.get(0);
            String stock = row.get(1);
            String lastCost = row.get(2);
            String oldQty = row.get(3);
            String websitName = row.get(4);
            if(StringUtils.isAnyBlank(goodsId,stock,lastCost,oldQty,websitName)){
                throw new RemoteServiceException("第"+(i+1)+"行请补充完整内容");
            }
            goodsId = goodsId.replaceAll("'", "");
            WebsitGoods websitGoods = websitGoodsService.lambdaQuery()
                    .eq(WebsitGoods::getCompanyWechatId,adminUser.getCompanyWechatId())
                    .eq(WebsitGoods::getGoodsType,websitGoodsTypeEnum.getKey())
                    .eq(WebsitGoods::getGoodsId,goodsId).one();
            if(websitGoods == null){
                throw new RemoteServiceException("商品编号【"+goodsId+"】不存在");
            }
            AdminWebsit adminWebsit = adminWebsitService.lambdaQuery()
                    .eq(AdminWebsit::getName, websitName)
                    .eq(StringUtils.isNotBlank(adminUser.getCompanyWechatId()),AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatId()).one();
            if(adminWebsit == null){
                throw new RemoteServiceException("网点名字【"+websitName+"】不存在");
            }
            Integer count = websitStockService.lambdaQuery()
                    .eq(WebsitStock::getCompanyWechatId, adminUser.getCompanyWechatId())
                    .eq(WebsitStock::getWebsitId,adminWebsit.getWebsitId())
                    .eq(WebsitStock::getGoodsId, goodsId).count();
            if(count > 0){
                throw new RemoteServiceException("商品编号【"+goodsId+"】的库存记录已存在于系统，导入失败");
            }
            if(new BigDecimal(stock).doubleValue() < 0){
                continue;
            }

            final Storage storage = storageService.lambdaQuery()
                    .eq(Storage::getCompanyWechatId, adminUser.getCompanyWechatId())
                    .eq(Storage::getWebsitId, adminWebsit.getWebsitId())
                    .eq(Storage::getIsDefault, true)
                    .one();

            if (Objects.isNull(storage)) {
                throw new RemoteServiceException("网点没有默认仓库");
            }

            WebsitStock websitStock = new WebsitStock();
            websitStock.setCompanyWechatId(adminUser.getCompanyWechatId());
            websitStock.setCompanyWechatName(adminUser.getCompanyName());
            websitStock.setWebsitId(adminWebsit.getWebsitId());
            websitStock.setWebsitName(adminWebsit.getName());
            websitStock.setGoodsType(websitGoodsTypeEnum.getKey());
            websitStock.setGoodsId(goodsId);
            websitStock.setGoodsName(websitGoods.getGoodsName());
            websitStock.setGoodsType(websitGoods.getGoodsType());
            websitStock.setQty(new BigDecimal(stock));
            websitStock.setOldQty(new BigDecimal(oldQty));
            websitStock.setLastCost(new BigDecimal(lastCost));
            websitStock.setStorageId(storage.getStorageId());
            websitStock.setCreateBy(adminUser.getNickName());
            websitStock.setUpdateBy(adminUser.getNickName());
            websitStocks.add(websitStock);

            //网点库存三级帐
            WebsitStockAcc websitStockAcc = new WebsitStockAcc();
            websitStockAcc.setCompanyWechatId(websitStock.getCompanyWechatId());
            websitStockAcc.setCompanyWechatName(websitStock.getCompanyWechatName());
            websitStockAcc.setWebsitId(websitStock.getWebsitId());
            websitStockAcc.setWebsitName(websitStock.getWebsitName());
            websitStockAcc.setGoodsType(websitStock.getGoodsType());
            websitStockAcc.setPartsAttr(PartsAttrEnum.NEW.getKey());
            websitStockAcc.setGoodsId(websitStock.getGoodsId());
            websitStockAcc.setGoodsName(websitStock.getGoodsName());
            websitStockAcc.setSdate(new Date());
            websitStockAcc.setDirectFlag(DirectFlagEnum.ADD.getKey());
            websitStockAcc.setChangeQty(websitStock.getQty());
            websitStockAcc.setCloseQty(websitStock.getQty());
            websitStockAcc.setRef("system");
            websitStockAcc.setRefType("期初导入");
            websitStockAcc.setObj("system");
            websitStockAcc.setOperateBy(adminUser.getNickName());
            websitStockAcc.setOperateTime(new Date());
            websitStockAcc.setRemark("期初导入");
            websitStockAcc.setStorageId(storage.getStorageId());
            //websitStockAcc.setQty(websitStock.getQty());
            //websitStockAcc.setCloseQty(0);
            websitStockAccs.add(websitStockAcc);
        }

        // 辅材价格表初始化
        if (websitGoodsTypeEnum.getKey().equals(WebsitGoodsTypeEnum.M.getKey())
                && CollectionUtil.isNotEmpty(websitStocks)) {
            List<WebsitGoodsPrice> priceList = new ArrayList<>();
            List<WebsitGoodsPrice> goodsPrices = websitGoodsPriceService.lambdaQuery()
                    .eq(WebsitGoodsPrice::getCompanyWechatId, websitStocks.get(0).getCompanyWechatId())
                    .eq(WebsitGoodsPrice::getWebsitId, websitStocks.get(0).getWebsitId())
                    .in(WebsitGoodsPrice::getGoodsId, websitStocks.stream()
                            .map(WebsitStock::getGoodsId)
                            .collect(Collectors.toList()))
                    .list();

            List<WebsitGoods> goodsList = websitGoodsService.lambdaQuery()
                    .eq(WebsitGoods::getCompanyWechatId, websitStocks.get(0).getCompanyWechatId())
                    .in(WebsitGoods::getGoodsId, websitStocks.stream()
                            .map(WebsitStock::getGoodsId)
                            .collect(Collectors.toList()))
                    .list();

            Map<String, WebsitGoodsPrice> priceMap = goodsPrices.stream()
                    .collect(Collectors.toMap(WebsitGoodsPrice::getGoodsId, Function.identity(), (key1, key2) -> key2));

            Map<String, BigDecimal> goodsMap = goodsList.stream()
                    .collect(Collectors.toMap(WebsitGoods::getGoodsId, WebsitGoods::getMarketPrice, (key1,key2) -> key2));

            for (WebsitStock stock : websitStocks) {
                if (!priceMap.containsKey(stock.getGoodsId())) {
                    BigDecimal goodsPrice = goodsMap.get(stock.getGoodsId());
                    WebsitGoodsPrice price = new WebsitGoodsPrice();
                    price.setCompanyWechatId(websitStocks.get(0).getCompanyWechatId());
                    price.setCompanyWechatName(websitStocks.get(0).getCompanyWechatName());
                    price.setWebsitId(websitStocks.get(0).getWebsitId());
                    price.setWebsitName(websitStocks.get(0).getWebsitName());
                    price.setGoodsType(WebsitGoodsTypeEnum.M.getKey());
                    price.setGoodsId(stock.getGoodsId());
                    price.setPrice(goodsPrice);
                    price.setRemark("初始化");

                    priceList.add(price);
                }
            }

            if (CollectionUtil.isNotEmpty(priceList)) {
                websitGoodsPriceService.saveBatch(priceList);
            }
        }
        websitStockService.saveBatch(websitStocks);
        websitStockAccService.saveBatch(websitStockAccs);
    }


}
