package com.fs.hisStore.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.erp.dto.ErpGoodsStockQueryRequert;
import com.fs.erp.dto.ErpGoodsStockQueryResponse;
import com.fs.erp.service.IErpGoodsService;
import com.fs.his.utils.ConfigUtil;
import com.fs.hisStore.config.FsErpConfig;
import com.fs.hisStore.config.MedicalMallConfig;
import com.fs.hisStore.domain.FsStoreCartScrm;
import com.fs.hisStore.domain.FsStoreProductAttrValueScrm;
import com.fs.hisStore.domain.FsStoreProductGroupScrm;
import com.fs.hisStore.dto.StoreProductGroupDTO;
import com.fs.hisStore.mapper.FsStoreCartScrmMapper;
import com.fs.hisStore.mapper.FsStoreProductAttrValueScrmMapper;
import com.fs.hisStore.mapper.FsStoreProductGroupScrmMapper;
import com.fs.hisStore.mapper.FsStoreProductScrmMapper;
import com.fs.hisStore.param.FsStoreCartCountParam;
import com.fs.hisStore.param.FsStoreCartDelParam;
import com.fs.hisStore.param.FsStoreCartNumParam;
import com.fs.hisStore.param.FsStoreCartParam;
import com.fs.hisStore.service.IFsStoreCartScrmService;
import com.fs.hisStore.vo.FsStoreCartVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

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

/**
 * 购物车Service业务层处理
 *
 * @author fs
 * @date 2022-03-21
 */
@Service
@Slf4j
public class FsStoreCartScrmServiceImpl implements IFsStoreCartScrmService
{
    @Autowired
    private FsStoreCartScrmMapper fsStoreCartMapper;
    @Autowired
    private FsStoreProductScrmMapper fsStoreProductMapper;
    @Autowired
    private FsStoreProductAttrValueScrmMapper valueMapper;
    @Autowired
    private FsStoreProductGroupScrmMapper productGroupMapper;
    @Qualifier("erpGoodsServiceImpl")
    private IErpGoodsService gyGoodsService;

    @Autowired
    @Qualifier("wdtErpGoodsServiceImpl")
    private IErpGoodsService wdtErpGoodsService;

    @Autowired
    @Qualifier("k9StockScrmServiceImpl")
    private IErpGoodsService k9StockService;

    @Autowired
    private ConfigUtil configUtil;

    @Autowired
    private MedicalMallConfig medicalMallConfig;



    /**
     * 查询购物车
     *
     * @param id 购物车ID
     * @return 购物车
     */
    @Override
    public FsStoreCartScrm selectFsStoreCartById(Long id)
    {
        return fsStoreCartMapper.selectFsStoreCartById(id);
    }

    /**
     * 查询购物车列表
     *
     * @param fsStoreCart 购物车
     * @return 购物车
     */
    @Override
    public List<FsStoreCartScrm> selectFsStoreCartList(FsStoreCartScrm fsStoreCart)
    {
        return fsStoreCartMapper.selectFsStoreCartList(fsStoreCart);
    }

    /**
     * 新增购物车
     *
     * @param fsStoreCart 购物车
     * @return 结果
     */
    @Override
    public int insertFsStoreCart(FsStoreCartScrm fsStoreCart)
    {
        fsStoreCart.setCreateTime(DateUtils.getNowDate());
        return fsStoreCartMapper.insertFsStoreCart(fsStoreCart);
    }

    /**
     * 修改购物车
     *
     * @param fsStoreCart 购物车
     * @return 结果
     */
    @Override
    public int updateFsStoreCart(FsStoreCartScrm fsStoreCart)
    {
        fsStoreCart.setUpdateTime(DateUtils.getNowDate());
        return fsStoreCartMapper.updateFsStoreCart(fsStoreCart);
    }

    /**
     * 批量删除购物车
     *
     * @param ids 需要删除的购物车ID
     * @return 结果
     */
    @Override
    public int deleteFsStoreCartByIds(Long[] ids)
    {
        return fsStoreCartMapper.deleteFsStoreCartByIds(ids);
    }

    /**
     * 删除购物车信息
     *
     * @param id 购物车ID
     * @return 结果
     */
    @Override
    public int deleteFsStoreCartById(Long id)
    {
        return fsStoreCartMapper.deleteFsStoreCartById(id);
    }

    @Override
    public R addCart(long uid, FsStoreCartParam cartParam) {
        //如果是直接购买，直接写入记录
        if(cartParam.getIsBuy()==1){
            FsStoreCartScrm storeCart = FsStoreCartScrm.builder()
                    .cartNum(cartParam.getCartNum())
                    .productAttrValueId(cartParam.getAttrValueId())
                    .productId(cartParam.getProductId())
                    .userId(uid)
                    .cartNum(cartParam.getCartNum())
                    .isPay(0)
                    .isDel(0)
                    .isBuy(cartParam.getIsBuy())
                    .build();
            storeCart.setCreateTime(new Date());
            checkProductStock(cartParam.getProductId(),storeCart.getProductAttrValueId());
            fsStoreCartMapper.insertFsStoreCart(storeCart);
            return R.ok().put("id",storeCart.getId());

        }
        else{
            FsStoreCartScrm cartMap=new FsStoreCartScrm();
            cartMap.setUserId(uid);
            cartMap.setIsPay(0);
            cartMap.setIsBuy(0);
            cartMap.setProductId(cartParam.getProductId());
            cartMap.setProductAttrValueId(cartParam.getAttrValueId());
            List<FsStoreCartScrm> cart = fsStoreCartMapper.selectFsStoreCartList(cartMap);
            FsStoreCartScrm storeCart;
            if(cart==null||cart.size()==0){
                storeCart = FsStoreCartScrm.builder()
                        .cartNum(cartParam.getCartNum())
                        .productAttrValueId(cartMap.getProductAttrValueId())
                        .productId(cartMap.getProductId())
                        .userId(uid)
                        .cartNum(cartParam.getCartNum())
                        .isPay(0)
                        .isDel(0)
                        .isBuy(0)
                        .build();
                storeCart.setCreateTime(new Date());
                checkProductStock(cartParam.getProductId(),storeCart.getProductAttrValueId());
                fsStoreCartMapper.insertFsStoreCart(storeCart);
                return R.ok().put("id",storeCart.getId());
            }
            else{
                storeCart=cart.get(0);
                storeCart.setCartNum(cartParam.getCartNum() + cart.get(0).getCartNum());
                storeCart.setUpdateTime(new Date());
                checkProductStock(cartParam.getProductId(),storeCart.getProductAttrValueId());
                fsStoreCartMapper.updateFsStoreCart(storeCart);
                return R.ok().put("id",storeCart.getId());
            }

        }
    }

    @Override
    public List<FsStoreCartVO> selectFsStoreCartListByUid(long uid) {
        return fsStoreCartMapper.selectFsStoreCartListByUid(uid, medicalMallConfig);
    }

    @Override
    public R delCart(long userId, FsStoreCartDelParam cartParam) {
        fsStoreCartMapper.delCart(cartParam.getIds());
        return R.ok();
    }

    @Override
    public R changeNum(long userId, FsStoreCartNumParam cartParam) {
        FsStoreCartScrm cart=fsStoreCartMapper.selectFsStoreCartById(cartParam.getId());
        checkProductStock(cart.getProductId(),cart.getProductAttrValueId());
        cart.setCartNum(cartParam.getNumber());
        cart.setUpdateTime(new Date());
        fsStoreCartMapper.updateFsStoreCart(cart);
        return R.ok();
    }

    @Override
    public void checkProductStock(Long productId, Long productAttrValueId) {
        IErpGoodsService goodsService = getErpService();
        if(goodsService != null){
            log.info("检查库存 {} {}",productId,productAttrValueId);
            FsStoreProductAttrValueScrm productAttrValue=valueMapper.selectFsStoreProductAttrValueById(productAttrValueId);
            if(StringUtils.isEmpty(productAttrValue.getGroupBarCode())){
                //单品
                ErpGoodsStockQueryRequert queryRequert = new ErpGoodsStockQueryRequert();
                queryRequert.setBarcode(productAttrValue.getBarCode());
                ErpGoodsStockQueryResponse goodsStock = goodsService.getGoodsStockScrm(queryRequert);
                if(goodsStock != null && goodsStock.getStocks() != null && !goodsStock.getStocks().isEmpty()){

//                    int stocks = Double.valueOf(goodsStock.getStocks().get(0).getSalable_qty()).intValue();
                    int stocks = Integer.valueOf(goodsStock.getStocks().get(0).getSalable_qty());

                    if(stocks<=0){
                        productAttrValue.setStock(0);
                        valueMapper.updateFsStoreProductAttrValue(productAttrValue);
                        fsStoreProductMapper.updateStock(productId);
                        throw new CustomException("库存不足");
                    }
                    else{
                        //更新库存
                        productAttrValue.setStock(stocks);
                        valueMapper.updateFsStoreProductAttrValue(productAttrValue);
                        fsStoreProductMapper.updateStock(productId);
                        return;
                    }

                }
                else{
                    throw new CustomException("未获取到库存");
                }

            }
            else{
                //组合码
                FsStoreProductGroupScrm group=productGroupMapper.selectFsStoreProductGroupByBarCode(productAttrValue.getGroupBarCode());
                if(group!=null){
                    Integer totalStock=0;
                    JSONArray jsonArray= JSONUtil.parseArray(group.getProducts());
                    List<StoreProductGroupDTO> productGroupDTOS=JSONUtil.toList(jsonArray, StoreProductGroupDTO.class);
                    if(productGroupDTOS!=null){
                        for(StoreProductGroupDTO dto:productGroupDTOS){
                            FsStoreProductAttrValueScrm attrValue=valueMapper.selectFsStoreProductAttrValueById(dto.getId());
                            ErpGoodsStockQueryRequert queryRequert = new ErpGoodsStockQueryRequert();
                            queryRequert.setBarcode(attrValue.getGroupBarCode());
                            ErpGoodsStockQueryResponse goodsStock = goodsService.getGoodsStockScrm(queryRequert);
                            if(goodsStock != null && goodsStock.getStocks() != null && !goodsStock.getStocks().isEmpty()){
                                int stocks = Integer.valueOf(goodsStock.getStocks().get(0).getSalable_qty());


                                if(stocks<=0){
                                    attrValue.setStock(0);
                                    valueMapper.updateFsStoreProductAttrValue(attrValue);
                                    fsStoreProductMapper.updateStock(productId);
                                    throw new CustomException("库存不足");
                                }
                                else{
                                    //更新库存
                                    attrValue.setStock(stocks);
                                    valueMapper.updateFsStoreProductAttrValue(attrValue);
                                    fsStoreProductMapper.updateStock(productId);
                                }
                                totalStock+=stocks;
                            }
                        }
                    }
                    productAttrValue.setStock(totalStock);
                    valueMapper.updateFsStoreProductAttrValue(productAttrValue);
                    fsStoreProductMapper.updateStock(productId);
                }

            }
        }
        int stock=valueMapper.selectFsStoreProductStockById(productAttrValueId);
        if (stock < 1) {
            throw new CustomException("库存不足");
        }
    }




    @Override
    public Integer selectFsStoreCartCountByUserId(long userId) {

        return  fsStoreCartMapper.selectFsStoreCartCountByUserId(userId);
    }

    @Override
    public Integer selectFsStoreCartCount(FsStoreCartCountParam param) {
        return  fsStoreCartMapper.selectFsStoreCartCount(param);
    }

    private IErpGoodsService getErpService(){
        //判断是否开启erp
        IErpGoodsService goodsService = null;
        FsErpConfig erpConfig = configUtil.getErpConfig();
        Integer erpOpen = erpConfig.getErpOpen();
        if (erpOpen != null && erpOpen == 1) {
            //判断erp类型
            Integer erpType = erpConfig.getErpType();
            if (erpType != null) {


                if (erpType == 1) {
                    //管易
                    goodsService = gyGoodsService;
                } else if (erpType == 2) {
                    //旺店通
                    goodsService = wdtErpGoodsService;
                } else if (erpType == 3) {
                    //旺店通
                    goodsService = k9StockService;
                }
            }
        }
        return goodsService;
    }


}
