package com.yiqi.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yiqi.common.exception.ServiceException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yiqi.common.enums.SourceType;
import com.yiqi.common.utils.DateUtils;
import com.yiqi.common.utils.SecurityUtils;
import com.yiqi.common.utils.StringUtils;
import com.yiqi.common.utils.bean.BeanUtils;
import com.yiqi.core.domain.*;
import com.yiqi.core.domain.dto.GoodsInfoDto;
import com.yiqi.core.domain.dto.GoodsUpdateSalesDTO;
import com.yiqi.core.domain.dto.weapp.WeAppGoodsInfoQueryDTO;
import com.yiqi.core.domain.vo.GoodsInfoQueryVO;
import com.yiqi.core.domain.vo.GoodsSkuNumDto;
import com.yiqi.core.domain.vo.weapp.WeAppGoodsInfoQueryVO;
import com.yiqi.core.mapper.*;
import com.yiqi.core.service.IGoodsInfoService;
import com.yiqi.core.service.IGoodsSkuStoreService;
import com.yiqi.core.service.IGoodsSpecService;
import com.yiqi.core.service.IGoodsStoreService;
import com.yiqi.order.domain.dto.RetailQueryGoodsDTO;
import com.yiqi.order.domain.vo.OrderGoodsSkuInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 商品管理Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-21
 */
@Service
public class GoodsInfoServiceImpl extends ServiceImpl<GoodsInfoMapper, GoodsInfo> implements IGoodsInfoService {

    @Autowired
    IGoodsStoreService goodsStoreService;
    @Autowired
    GoodsSkuMapper goodsSkuMapper;
    @Autowired
    GoodsSpecMapper goodsSpecMapper;
    @Autowired
    IGoodsSpecService goodsSpecService;
    @Autowired
    GoodsSkuStoreMapper goodsSkuStoreMapper;
    @Autowired
    IGoodsSkuStoreService goodsSkuStoreService;

    @Override
    public List<WeAppGoodsInfoQueryVO> findPage(WeAppGoodsInfoQueryDTO weAppGoodsInfoQueryDTO) {
        return baseMapper.findPage(weAppGoodsInfoQueryDTO);
    }

    /**
     * 查询商品管理（总部）
     *
     * @param id 商品管理主键
     * @return 商品管理
     */
    @Override
    public GoodsInfoDto selectGoodsById(Long id) {
        GoodsInfo goodsInfo = baseMapper.selectById(id);
        GoodsInfoDto goodsInfoDto = new GoodsInfoDto();
        BeanUtils.copyProperties(goodsInfo, goodsInfoDto);
        List<GoodsSku> goodsSkuList = goodsSkuMapper.selectGoodsSkuListByGoodsId(id);
        // 设置规格值
        goodsSkuList.forEach(goodsSku -> {
            //values字符串数组转List
            if (StringUtils.isNotBlank(goodsSku.getSpecs())) {
                goodsSku.setSpecValLists(JSONUtil.toList(JSONUtil.parseArray(goodsSku.getSpecs()), String.class));
            }
        });
        goodsInfoDto.setSkuList(goodsSkuList);
        List<GoodsSpec> goodsSpecList = goodsSpecService.selectByGoodsId(id);
        goodsInfoDto.setSpecList(goodsSpecList);
        if (goodsInfoDto.getSkuType() == 0 && goodsSkuList.size() > 0) {
            goodsInfoDto.setSingleSkuPrice(goodsInfoDto.getSkuList().get(0).getSalePrice());
            goodsInfoDto.setSingleSkuCostPrice(goodsInfoDto.getSkuList().get(0).getCostPrice());
            goodsInfoDto.setSingleSkuPurchasePrice(goodsInfoDto.getSkuList().get(0).getPurchasePrice());
            goodsInfoDto.setSingleSkuStock(goodsInfoDto.getSkuList().get(0).getStock());
        }
        return goodsInfoDto;
    }

    /**
     * 查询商品管理列表
     *
     * @param goodsInfoQueryVO 商品管理
     * @return 商品管理
     */
    @Override
    public List<GoodsInfoQueryVO> selectGoodsList(GoodsInfoQueryVO goodsInfoQueryVO) {
        List<GoodsInfoQueryVO> goodsInfoQueryVOList = baseMapper.selectGoodsList(goodsInfoQueryVO);
        for (GoodsInfoQueryVO goodsInfoQuery : goodsInfoQueryVOList) {
            GoodsSkuNumDto goodsSkuNumDto = goodsSkuMapper.getGoodsSkuNumsByGoodsId(goodsInfoQuery.getId());
            goodsInfoQuery.setGoodsItemNum(goodsSkuNumDto.getGoodsItemNum());
            goodsInfoQuery.setGoodsStockNum(goodsSkuNumDto.getGoodsStockNum());
            //如果是门店权限，则查询门店的库存和物料数量
            if (goodsInfoQuery.getSourceType().equals(SourceType.STORE.getCode())) {
                GoodsSkuNumDto goodsStoreSkuNumDto = goodsSkuStoreMapper.getGoodsStoreSkuNumsByGoodsId(goodsInfoQuery.getId(), goodsInfoQuery.getTargetId());
                goodsInfoQuery.setGoodsStockNum(goodsStoreSkuNumDto.getGoodsStockNum());
            }
        }
        return goodsInfoQueryVOList;
    }

    /**
     * 新增商品管理
     *
     * @param goods 商品管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertGoods(GoodsInfoDto goods) {
        goods.buildCreateData();
        goods.setSellNum(0);
        goods.setGoodComment(BigDecimal.ZERO);
        goods.setDelFlag("0");
        goods.setSkuType(0);
        if (goods.getSpecList() != null && goods.getSpecList().size() > 0) {
            goods.setSkuType(1);
        }
        int i = baseMapper.insertGoods(goods);

        //如果是单规格
        if (goods.getSkuType() == 0) {
            GoodsSku goodsSku = new GoodsSku();
            if (StringUtils.isNotBlank(goods.getGoodsCode())) {
                goodsSku.setSkuCode(goods.getGoodsCode());
            } else {
                goodsSku.setSkuCode(goods.getId() + RandomUtil.randomNumbers(6));
            }
            goodsSku.setSalePrice(goods.getSingleSkuPrice());
            goodsSku.setCostPrice(goods.getSingleSkuCostPrice());
            goodsSku.setPurchasePrice(goods.getSingleSkuPurchasePrice());
            goodsSku.setStock(goods.getSingleSkuStock());
            goodsSku.setSourceType(SourceType.MANAGER.getCode());
            goodsSku.setStatus("0");
            goodsSku.setDelFlag("0");
            goodsSku.setSpecs(JSONUtil.toJsonStr(new ArrayList<>()));
            goodsSku.setCreateTime(DateUtils.getNowDate());
            goodsSku.setCreateById(SecurityUtils.getUserId());
            goodsSku.setCreateBy(SecurityUtils.getUsername());
            goodsSku.setGoodsId(goods.getId());
            goodsSkuMapper.insert(goodsSku);
        } else {
            //新增规格
            goods.getSpecList().forEach(goodsSpec -> {
                goodsSpec.setVals(JSONUtil.toJsonStr(goodsSpec.getSpecValues()));
                goodsSpec.setGoodsId(goods.getId());
                goodsSpec.buildCreateData();
                goodsSpecService.save(goodsSpec);
            });
            //新增SKU
            goods.getSkuList().forEach(goodsSku -> {
                goodsSku.setSpecs(JSONUtil.toJsonStr(goodsSku.getSpecValLists()));
                goodsSku.setGoodsId(goods.getId());
                goodsSku.setSourceType(SourceType.MANAGER.getCode());
                goodsSku.setStatus("0");
                goodsSku.setDelFlag("0");
                if (StringUtils.isBlank(goodsSku.getSkuCode())) {
                    goodsSku.setSkuCode(goods.getId() + RandomUtil.randomNumbers(6));
                }
                goodsSku.buildCreateData();
                goodsSkuMapper.insert(goodsSku);
            });
        }
        // 新增商品总部关系
        GoodsStore goodsStore = new GoodsStore();
        goodsStore.setSourceType(SourceType.MANAGER.getCode());
        goodsStore.setGoodsId(goods.getId());
        goodsStore.setStatus("0");
        goodsStore.buildCreateData();
        goodsStoreService.insertGoodsStore(goodsStore);
        // 新增商品工厂关系
//        goodsStoreService.insertGoodsToAllFactory(goodsStore);
        // 新增商品门店关系
        goodsStoreService.insertGoodsToAllStore(goodsStore);
        //新增商品sku与门店关系
        // 新增门店物料关系
        List<GoodsSku> goodsSkuList = goodsSkuMapper.selectGoodsSkuListByGoodsId(goods.getId());
        for (GoodsSku goodsSku : goodsSkuList) {
            GoodsSkuStore store = new GoodsSkuStore();
            store.setGoodsSkuId(goodsSku.getId());
            store.setGoodsId(goodsSku.getGoodsId());
            store.setCreateBy(goodsSku.getCreateBy());
            store.setCreateById(goodsSku.getCreateById());
            store.setCreateTime(DateUtils.getNowDate());
            store.setStatus("0");
            store.setStock(0);
            goodsSkuStoreService.insertSkuToAllStore(store);
        }
        return i;
    }

    /**
     * 修改商品管理 （由于商品涉及库存管理，因此不能修改规格属性等逻辑）
     *
     * @param goods 商品管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateGoods(GoodsInfoDto goods) {
        if (goods.getId() == null) {
            throw new ServiceException("商品ID不能为空");
        }
        goods.buildUpdateData();
        //获取原商品的规格属性，如果商品的规格发生变更，则清除历史规格
        GoodsInfo origin = baseMapper.selectById(goods.getId());
        if (origin.getSkuType() != goods.getSkuType()) {
            goodsSkuMapper.delete(new QueryWrapper<GoodsSku>().eq("goods_id", goods.getId()));
            goodsSpecMapper.delete(new QueryWrapper<GoodsSpec>().eq("goods_id", goods.getId()));
        }
        //多规格处理
        if (goods.getSkuType() == 1) {
            if (CollUtil.isEmpty(goods.getSkuList())) {
                throw new ServiceException("规格类型为多规格时，规格不能为空");
            }
            // 获取原规格列表
//            List<GoodsSpec> originalSpecList = goodsSpecService.selectByGoodsId(goods.getId());
//
//            // 创建新规格ID集合
//            List<Long> newSpecIds = goods.getSpecList().stream().map(GoodsSpec::getId).filter(id -> id != null).collect(Collectors.toList());
//
//            // 找出需要删除的规格
//            List<GoodsSpec> specsToDelete = originalSpecList.stream()
//                    .filter(originalSpec -> !newSpecIds.contains(originalSpec.getId()))
//                    .collect(Collectors.toList());
//
//            // 删除多余的规格
//            specsToDelete.forEach(specToDelete -> goodsSpecService.removeById(specToDelete.getId()));

            // 更新或新增规格
            goods.getSpecList().forEach(goodsSpec -> {
                goodsSpec.setVals(JSONUtil.toJsonStr(goodsSpec.getSpecValues()));
                if (goodsSpec.getId() != null) {
                    goodsSpec.buildUpdateData();
                    goodsSpecService.updateById(goodsSpec);
                }
//                else {
//                    goodsSpec.setGoodsId(goods.getId());
//                    goodsSpec.buildCreateData();
//                    goodsSpecService.save(goodsSpec);
//                }
            });

            // 获取原SKU列表
//            List<GoodsSku> originalSkuList = goodsSkuMapper.selectGoodsSkuListByGoodsId(goods.getId());
//
//            // 创建新SKU ID集合
//            List<Long> newSkuIds = goods.getSkuList().stream().map(GoodsSku::getId).filter(id -> id != null).collect(Collectors.toList());
//
//            // 找出需要删除的SKU
//            List<GoodsSku> skusToDelete = originalSkuList.stream()
//                    .filter(originalSku -> !newSkuIds.contains(originalSku.getId()))
//                    .collect(Collectors.toList());
//
//            // 删除多余的SKU
//            skusToDelete.forEach(skuToDelete -> goodsSkuMapper.deleteById(skuToDelete.getId()));

            // 更新或新增SKU
            goods.getSkuList().forEach(goodsSku -> {
                goodsSku.setSpecs(JSONUtil.toJsonStr(goodsSku.getSpecValLists()));
                if (goodsSku.getId() != null) {
                    goodsSku.buildUpdateData();
                    goodsSkuMapper.updateById(goodsSku);
                }
//                else {
//                    goodsSku.setSourceType(SourceType.MANAGER.getCode());
//                    goodsSku.setStatus("0");
//                    goodsSku.setDelFlag("0");
//                    goodsSku.setGoodsId(goods.getId());
//                    goodsSku.buildCreateData();
//                    goodsSkuMapper.insert(goodsSku);
//                }
            });
        } else {
            //单规格处理，找到默认规格，更新默认规格，新增其他规格
            GoodsSku oriSku = null;
            List<GoodsSku> originalSkuList = goodsSkuMapper.selectGoodsSkuListByGoodsId(goods.getId());
            if (originalSkuList == null || originalSkuList.size() == 0) {
                oriSku = new GoodsSku();
                oriSku.setSkuCode(goods.getGoodsCode());
                oriSku.setSalePrice(goods.getSingleSkuPrice());
                oriSku.setCostPrice(goods.getSingleSkuCostPrice());
                oriSku.setPurchasePrice(goods.getSingleSkuPurchasePrice());
                oriSku.setStock(goods.getSingleSkuStock());
                oriSku.setSourceType(SourceType.MANAGER.getCode());
                oriSku.setStatus("0");
                oriSku.setDelFlag("0");
                oriSku.setSpecs(JSONUtil.toJsonStr(new ArrayList<>()));
                oriSku.setCreateTime(DateUtils.getNowDate());
                oriSku.setCreateById(SecurityUtils.getUserId());
                oriSku.setCreateBy(SecurityUtils.getUsername());
                oriSku.setGoodsId(goods.getId());
                goodsSkuMapper.insert(oriSku);
            } else {
                oriSku = originalSkuList.get(0);
                oriSku.setSkuCode(goods.getGoodsCode());
                oriSku.setSalePrice(goods.getSingleSkuPrice());
                oriSku.setCostPrice(goods.getSingleSkuCostPrice());
                oriSku.setPurchasePrice(goods.getSingleSkuPurchasePrice());
                oriSku.setStock(goods.getSingleSkuStock());
                oriSku.buildUpdateData();
                goodsSkuMapper.updateById(oriSku);
            }
        }
        baseMapper.updateGoods(goods);
        return 1; // 返回结果
    }

    /**
     * 批量删除商品管理
     *
     * @param ids 需要删除的商品管理主键
     * @return 结果
     */
    @Override
    public int deleteGoodsByIds(Long[] ids) {
        for (Long id : ids) {
            GoodsInfo goodsInfo = new GoodsInfo();
            goodsInfo.setId(id);
            goodsInfo.setDelFlag("2");
            goodsInfo.buildUpdateData();
            baseMapper.updateById(goodsInfo);
        }
        return 1;
    }

    /**
     * 删除商品管理信息
     *
     * @param id 商品管理主键
     * @return 结果
     */
    @Override
    public int deleteGoodsById(Long id) {
        return baseMapper.deleteGoodsById(id);
    }

    /**
     * 修改商品管理状态
     *
     * @param goods 商品管理
     * @return 结果
     */
    @Override
    public int updateGoodsStatus(GoodsInfo goods) {
        goods.buildUpdateData();
        return baseMapper.updateGoods(goods);
    }

    /**
     * 查询商品管理
     *
     * @param ids 商品管理主键
     * @return 商品管理
     */
    @Override
    public int selectGoodsByBrandIds(Long[] ids) {
        return baseMapper.selectGoodsByBrandIds(ids);
    }

    /**
     * 查询商品管理
     *
     * @param ids 商品管理主键
     * @return 商品管理
     */
    @Override
    public int selectGoodsCategoryIds(Long[] ids) {
        return baseMapper.selectGoodsCategoryIds(ids);
    }

    @Override
    public List<GoodsInfo> selectGoodsByCategoryId(RetailQueryGoodsDTO retailQueryGoodsDTO) {
        retailQueryGoodsDTO.setSourceType(SecurityUtils.getLoginUser().getSourceType());
        retailQueryGoodsDTO.setOrgId(SecurityUtils.getLoginUser().getOrgId());
        return baseMapper.selectGoodsByCategoryId(retailQueryGoodsDTO);
    }

    /**
     * 处理商品销量
     *
     * @param goodsUpdateSales
     * @param isAdd            是否增加销售
     * @return
     */
    @Override
    public int handleGoodsSellNum(List<GoodsUpdateSalesDTO> goodsUpdateSales, boolean isAdd) {
        if (isAdd) {
            return baseMapper.addGoodsSaleNumber(goodsUpdateSales);
        } else {
            return baseMapper.minusGoodsSaleNumber(goodsUpdateSales);
        }
    }

    /**
     * 直接更新虚拟销售的值
     *
     * @param goodsId
     * @param virtualSellNum
     * @return
     */
    @Override
    public int updateGoodsVirtualSellNum(Long goodsId, Integer virtualSellNum) {
        this.update(new UpdateWrapper<GoodsInfo>().lambda()
                .set(GoodsInfo::getVirtualSellNum, virtualSellNum)
                .eq(GoodsInfo::getId, goodsId));
        return 1;
    }

    /**
     * 获取商品物料信息，通过物料id
     *
     * @param skuIdList
     * @param sourceType
     * @return
     */
    @Override
    public List<OrderGoodsSkuInfoVO> getSkuInfoList(List<Long> skuIdList, String sourceType) {
        if (SourceType.MANAGER.getCode().equals(sourceType)) {
            return baseMapper.getSkuInfoListByApp(skuIdList);
        }
        if (SourceType.STORE.getCode().equals(sourceType)) {
            return baseMapper.getSkuInfoListByStore(skuIdList, SecurityUtils.getLoginUser().getSourceType(), SecurityUtils.getLoginUser().getOrgId());
        }
        return null;
    }

    @Override
    public void clearGoodsSkuInfo() {
        List<GoodsInfo> goodsInfos = list();
        for (GoodsInfo goodsInfo : goodsInfos) {
            if (StringUtils.isEmpty(goodsInfo.getGoodsImg())) {
                deleteAllGoodsByGoodsId(goodsInfo.getId());
            }
            GoodsInfoDto goods = new GoodsInfoDto();
            BeanUtils.copyProperties(goodsInfo, goods);
            goods.setId(null);
            List<GoodsSku> goodsSkuList = goodsSkuMapper.selectGoodsSkuListByGoodsId(goodsInfo.getId());
            if (goodsSkuList.size() > 1) {
                goods.setSkuType(1);
            } else {
                goods.setSkuType(0);
            }

        }
    }

    /**
     * 删除这个商品所有的信息
     */
    private void deleteAllGoodsByGoodsId(Long goodsId) {
        //删除 goods_store
        goodsStoreService.remove(new LambdaQueryWrapper<GoodsStore>().eq(GoodsStore::getGoodsId, goodsId));
        //删除 goods_sku_store
        goodsSkuStoreMapper.delete(new LambdaQueryWrapper<GoodsSkuStore>().eq(GoodsSkuStore::getGoodsId, goodsId));
        //删除 goods_sku
        goodsSkuMapper.delete(new LambdaQueryWrapper<GoodsSku>().eq(GoodsSku::getGoodsId, goodsId));
        //删除 goods_spec
        goodsSpecMapper.delete(new LambdaQueryWrapper<GoodsSpec>().eq(GoodsSpec::getGoodsId, goodsId));
        //删除 goods_info
        baseMapper.delete(new LambdaQueryWrapper<GoodsInfo>().eq(GoodsInfo::getId, goodsId));
    }
}
