package co.yixiang.yshop.module.product.service.storeproduct;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.yshop.framework.common.constant.ShopConstants;
import co.yixiang.yshop.framework.common.enums.ShopCommonEnum;
import co.yixiang.yshop.module.product.controller.app.product.param.AppStoreProductQueryParam;
import co.yixiang.yshop.module.product.controller.app.product.vo.AppProductVo;
import co.yixiang.yshop.module.product.controller.app.product.vo.AppStoreProductAttrQueryVo;
import co.yixiang.yshop.module.product.controller.app.product.vo.AppStoreProductReplyQueryVo;
import co.yixiang.yshop.module.product.controller.app.product.vo.AppStoreProductRespVo;
import co.yixiang.yshop.module.product.convert.storeproduct.StoreProductConvert;
import co.yixiang.yshop.module.product.dal.dataobject.shippingtemplates.ShippingTemplatesDO;
import co.yixiang.yshop.module.product.dal.dataobject.storeproduct.StoreProductDO;
import co.yixiang.yshop.module.product.dal.dataobject.storeproductattrvalue.StoreProductAttrValueDO;
import co.yixiang.yshop.module.product.dal.mysql.storeproduct.StoreProductMapper;
import co.yixiang.yshop.module.product.dal.mysql.storeproductattrvalue.StoreProductAttrValueMapper;
import co.yixiang.yshop.module.product.enums.ProductConstants;
import co.yixiang.yshop.module.product.enums.product.ProductEnum;
import co.yixiang.yshop.module.product.enums.product.ProductTypeEnum;
import co.yixiang.yshop.module.product.enums.product.RelationCateEnum;
import co.yixiang.yshop.module.product.service.shippingtemplates.ShippingTemplatesService;
import co.yixiang.yshop.module.product.service.storeproductattr.AppStoreProductAttrService;
import co.yixiang.yshop.module.product.service.storeproductattrvalue.StoreProductAttrValueService;
import co.yixiang.yshop.module.product.service.storeproductrelation.AppStoreProductRelationService;
import co.yixiang.yshop.module.product.service.storeproductreply.AppStoreProductReplyService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static co.yixiang.yshop.module.product.enums.ErrorCodeConstants.PRODUCT_STOCK_LESS;
import static co.yixiang.yshop.module.product.enums.ErrorCodeConstants.STORE_PRODUCT_NOT_EXISTS;

/**
 * 商品 AppService 实现类
 *
 * @author yshop
 */
@Service
@Validated
public class AppStoreProductServiceImpl extends ServiceImpl<StoreProductMapper,StoreProductDO> implements AppStoreProductService {

    @Resource
    private AppStoreProductAttrService appStoreProductAttrService;
    @Resource
    private AppStoreProductRelationService appStoreProductRelationService;
    @Resource
    private AppStoreProductReplyService appStoreProductReplyService;
    @Resource
    private ShippingTemplatesService shippingTemplatesService;
    @Resource
    private StoreProductAttrValueService storeProductAttrValueService;
    @Resource
    private StoreProductAttrValueMapper storeProductAttrValueMapper;

    /**
     * 商品列表
     *
     * @param page  页码
     * @param limit 条数
     * @param order ProductEnum
     * @return List
     */
    @Override
    public List<AppStoreProductRespVo> getList(int page, int limit, int order) {
        LambdaQueryWrapper<StoreProductDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StoreProductDO::getIsShow, ShopCommonEnum.SHOW_1.getValue())
                //.eq(YxStoreProduct::getIsDel,ShopCommonEnum.DELETE_0.getValue())
                .orderByDesc(StoreProductDO::getSort);
        wrapper.eq(StoreProductDO::getIsIntegral,0);
        // order
        switch (ProductEnum.toType(order)) {
            //精品推荐
            case TYPE_1:
                wrapper.eq(StoreProductDO::getIsBest,
                        ShopCommonEnum.IS_STATUS_1.getValue());
                break;
            //首发新品
            case TYPE_3:
                wrapper.eq(StoreProductDO::getIsNew,
                        ShopCommonEnum.IS_STATUS_1.getValue());
                break;
            // 猜你喜欢
            case TYPE_4:
                wrapper.eq(StoreProductDO::getIsBenefit,
                        ShopCommonEnum.IS_STATUS_1.getValue());
                break;
            // 热门榜单
            case TYPE_2:
                wrapper.eq(StoreProductDO::getIsHot,
                        ShopCommonEnum.IS_STATUS_1.getValue());
                break;
            default:
        }
        Page<StoreProductDO> pageModel = new Page<>(page, limit);

        IPage<StoreProductDO> pageList = this.baseMapper.selectPage(pageModel, wrapper);

        return StoreProductConvert.INSTANCE.convertList03(pageList.getRecords());
    }


    /**
     * 商品列表
     *
     * @param productQueryParam AppStoreProductQueryParam
     * @return list
     */
    @Override
    public List<AppStoreProductRespVo> getGoodsList(AppStoreProductQueryParam productQueryParam) {

        LambdaQueryWrapper<StoreProductDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StoreProductDO::getIsShow, ShopCommonEnum.SHOW_1.getValue());

        if(productQueryParam.getIsIntegral()!=null){
            wrapper.eq(StoreProductDO::getIsIntegral, productQueryParam.getIsIntegral());
        }
        //多字段模糊查询分类搜索
        if (StrUtil.isNotBlank(productQueryParam.getSid()) &&
                !ShopConstants.YSHOP_ZERO.equals(productQueryParam.getSid())) {
            wrapper.eq(StoreProductDO::getCateId, productQueryParam.getSid());
        }
        //关键字搜索
        if (StrUtil.isNotEmpty(productQueryParam.getKeyword())) {
            wrapper.and(wrapper1 -> {
                wrapper1.or();
                wrapper1.like(StoreProductDO::getStoreName, productQueryParam.getKeyword());
                wrapper1.or();
                wrapper1.like(StoreProductDO::getStoreInfo, productQueryParam.getKeyword());
                wrapper1.or();
                wrapper1.like(StoreProductDO::getKeyword, productQueryParam.getKeyword());
            });
        }
        //新品搜索
        if (StrUtil.isNotBlank(productQueryParam.getNews()) &&
                !ShopConstants.YSHOP_ZERO.equals(productQueryParam.getNews())) {
            wrapper.eq(StoreProductDO::getIsNew, ShopCommonEnum.IS_NEW_1.getValue());
        }


        Page<StoreProductDO> pageModel = new Page<>(productQueryParam.getPage(),
                productQueryParam.getLimit());

        IPage<StoreProductDO> pageList = this.baseMapper.selectPage(pageModel, wrapper);

        return StoreProductConvert.INSTANCE.convertList03(pageList.getRecords());
    }


    /**
     * 商品详情
     *
     * @param id        商品id
     * @param uid       用户id
     * @return ProductVo
     */
    @Override
    public AppProductVo goodsDetail(Long id, Long uid) {
        LambdaQueryWrapper<StoreProductDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StoreProductDO::getIsShow, ShopCommonEnum.SHOW_1.getValue())
                .eq(StoreProductDO::getId, id);
        StoreProductDO storeProduct = this.baseMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(storeProduct)) {
            throw exception(STORE_PRODUCT_NOT_EXISTS);
        }

        //获取商品sku
        Map<String, Object> returnMap = appStoreProductAttrService.getProductAttrDetail(id);
        AppProductVo productVo = new AppProductVo();

        AppStoreProductRespVo storeProductQueryVo = StoreProductConvert.INSTANCE.convert01(storeProduct);

        //设置销量
        storeProductQueryVo.setSales(storeProductQueryVo.getSales() + storeProduct.getFicti());

        if (uid.longValue() > 0) {
            //设置VIP价格
           //todo

            //收藏
            boolean isCollect = appStoreProductRelationService.isProductRelation(id, uid, RelationCateEnum.COMMON.getValue());
            storeProductQueryVo.setUserCollect(isCollect);
        }
        //总条数
        Long totalCount = appStoreProductReplyService.productReplyCount(id);
        productVo.setReplyCount(totalCount);

        //评价
        AppStoreProductReplyQueryVo storeProductReplyQueryVo = appStoreProductReplyService.getReply(id);
        productVo.setReply(storeProductReplyQueryVo);

        //好评比例
        String replyPer = appStoreProductReplyService.replyPer(id);
        productVo.setReplyChance(replyPer);

        //获取运费模板名称
        String tempName = "";
        if (storeProduct.getPostage().intValue() == 0 && storeProduct.getTempId() == 0) {
            tempName = ProductConstants.FREE_POSTAGE;
        } else {
            ShippingTemplatesDO shippingTemplates = shippingTemplatesService.getById(storeProduct.getTempId());
            if (ObjectUtil.isNotNull(shippingTemplates)) {
                tempName = shippingTemplates.getName();
            } else {
                tempName = ProductConstants.POSTAGE_TEMP_NOT;
            }

        }
        productVo.setTempName(tempName);

        //设置商品相关信息
        productVo.setStoreInfo(storeProductQueryVo);
        productVo.setProductAttr((List<AppStoreProductAttrQueryVo>) returnMap.get("productAttr"));
        productVo.setProductValue((Map<String, StoreProductAttrValueDO>) returnMap.get("productValue"));


        return productVo;
    }


    /**
     * 返回普通商品库存
     *
     * @param productId 商品id
     * @param unique    sku唯一值
     * @return int
     */
    @Override
    public int getProductStock(Long productId, String unique, String type) {
        StoreProductAttrValueDO storeProductAttrValue = storeProductAttrValueService
                .getOne(Wrappers.<StoreProductAttrValueDO>lambdaQuery()
                        .eq(StoreProductAttrValueDO::getUnique, unique)
                        .eq(StoreProductAttrValueDO::getProductId, productId));

        if (storeProductAttrValue == null) {
            return 0;
        }
        if (ProductTypeEnum.PINK.getValue().equals(type)) {
            return storeProductAttrValue.getPinkStock();
        } else if (ProductTypeEnum.SECKILL.getValue().equals(type)) {
            return storeProductAttrValue.getSeckillStock();
        }
        return storeProductAttrValue.getStock();

    }

    /**
     * 获取单个商品
     *
     * @param id 商品id
     * @return YxStoreProductQueryVo
     */
    @Override
    public AppStoreProductRespVo getStoreProductById(Long id) {
        return  StoreProductConvert.INSTANCE.convert01(this.baseMapper.selectById(id));
    }


    /**
     * 减少库存与增加销量
     *
     * @param num       数量
     * @param productId 商品id
     * @param unique    sku
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void decProductStock(int num, Long productId, String unique, Long activityId, String type) {


        int res = 0;
        res =  storeProductAttrValueMapper.decStockIncSales(num,productId,unique);

        if(res == 0) {
            throw exception(PRODUCT_STOCK_LESS);
        }

        int product = this.baseMapper.decStockIncSales(num, productId);
        if (product == 0) {
            throw exception(PRODUCT_STOCK_LESS);
        }


    }


    /**
     * 增加库存 减少销量
     *
     * @param num       数量
     * @param productId 商品id
     * @param unique    sku唯一值
     */
    @Override
    public void incProductStock(Integer num, Long productId, String unique, Long activityId, String type) {
        //处理属性sku
        if (StrUtil.isNotEmpty(unique)) {
            storeProductAttrValueMapper.incStockDecSales(num, productId, unique);
        }
        //更新商品
        this.baseMapper.incStockDecSales(num, productId);
    }



}
