package com.ruoyi.frequency.mallgoods.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.page.PageResult;
import com.ruoyi.controller.req.GoodsPageReq;
import com.ruoyi.controller.resp.GoodsDetailResp;
import com.ruoyi.controller.resp.GoodsPageResp;
import com.ruoyi.frequency.mallgoods.entity.MallGoods;
import com.ruoyi.frequency.mallgoods.mapper.MallGoodsMapper;
import com.ruoyi.frequency.mallgoods.service.MallGoodsService;
import com.ruoyi.frequency.mallspecifications.entity.MallSpecifications;
import com.ruoyi.frequency.mallspecifications.service.MallSpecificationsService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.vo.UserVo;
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.Date;
import java.util.List;

/**
 * 商品Service业务层处理
 *
 * @author liwenlong
 * @date 2024-01-25
 */
@Service
public class MallGoodsServiceImpl extends ServiceImpl<MallGoodsMapper, MallGoods>  implements MallGoodsService
{
    @Autowired
    private MallGoodsMapper mallGoodsMapper;

    /**
     * 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public MallGoods selectMallGoodsById(Long id)
    {

        MallGoods mallGoods = mallGoodsMapper.selectMallGoodsById(id);

        if (mallGoods != null){
            List<MallSpecifications> mallSpecificationsList = specificationsService.selectMallSpecificationsList(new MallSpecifications().setDelFlag(PublicCommon.启用).setGoodsId(id));
            mallGoods.setSpecificationsList(mallSpecificationsList);
        }
        return mallGoods;
    }

    /**
     * 查询商品列表
     *
     * @param mallGoods 商品
     * @return 商品
     */
    @Override
    public List<MallGoods> selectMallGoodsList(MallGoods mallGoods)
    {
        return mallGoodsMapper.selectMallGoodsList(mallGoods);
    }

    /**
     * 新增商品
     *
     * @param goods 商品
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertMallGoods(MallGoods goods)
    {

        if (ObjectUtil.notEqual(PublicCommon.禁用,goods.getDelFlag())){
            //上架时间
            goods.setListingTime(new Date());
        }
        // 将dto转为实体
        boolean save = this.save(goods);

        if (save && goods.getSpecificationsList().size() > 0){
            //关联规格
            goods.getSpecificationsList().stream().forEach(s->{
                s.setGoodsId(goods.getId());
            });
            specificationsService.saveBatch(goods.getSpecificationsList());
        }
        return 1;
    }

    /**
     * 修改商品
     *
     * @param goods 商品
     * @return 结果
     */
    @Override
    public int updateMallGoods(MallGoods goods)
    {
        this.updateById(goods);

        //关联规格
        if (goods.getSpecificationsList().size()  > 0){

            List<Long> specIds = new ArrayList<>();
            goods.getSpecificationsList().stream().forEach(s->{
                if (ObjectUtil.isEmpty(s.getId())){
                    s.setGoodsId(goods.getId());
                }else {
                    specIds.add(s.getId());
                }
            });
            //删除
            specificationsService.remove(new QueryWrapper<MallSpecifications>().lambda()
                    .eq(MallSpecifications::getGoodsId,goods.getId())
                    .notIn(specIds.size() > 0,MallSpecifications::getGoodsId,specIds));

            specificationsService.saveOrUpdateBatch(goods.getSpecificationsList());
        }
        return 1;
    }

    /**
     * 批量删除商品
     *
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteMallGoodsByIds(Long[] ids,Integer delFlag)
    {
        this.lambdaUpdate().set(MallGoods::getDelFlag,delFlag)
                .set(ObjectUtil.equal(PublicCommon.启用,delFlag),MallGoods::getListingTime,new Date())
                .in(MallGoods::getId,ids).update();
        return ids.length;
    }

    @Autowired
    private MallSpecificationsService specificationsService;

    @Override
    public ResponseData goodsPage(GoodsPageReq req, UserVo userVo) {

        Page<GoodsPageResp> page = this.baseMapper.goodsPage(new Page<>(req.getPageNo(),req.getPageSize()),req,userVo);

        if (page.getRecords().size() > 0){

            page.getRecords().stream().forEach(s->{
                //商品规格
                List<MallSpecifications> specifications = specificationsService.getBaseMapper().selectList(new QueryWrapper<MallSpecifications>().lambda()
                        .eq(MallSpecifications::getGoodsId, s.getId())
                        .eq(MallSpecifications::getDelFlag, PublicCommon.启用).orderByDesc(BaseEntity::getCreateTime));

                s.setGoodsSpecList(specifications);
            });

        }

        return ResponseData.success(new PageResult<>(page));
    }


    @Override
    public ResponseData goodsDetail(Long goodsId, UserVo userVo) {
        GoodsDetailResp goodsDetailResp = this.baseMapper.goodsDetail(goodsId,userVo);

        if (goodsDetailResp != null){
            //商品规格
            List<MallSpecifications> specifications = specificationsService.getBaseMapper().selectList(new QueryWrapper<MallSpecifications>().lambda()
                    .eq(MallSpecifications::getGoodsId, goodsId)
//                    .gt(MallSpecifications::getStock,BigDecimal.ZERO)
                    .eq(MallSpecifications::getDelFlag, PublicCommon.启用).orderByDesc(BaseEntity::getCreateTime));
            goodsDetailResp.setGoodsSpecList(specifications);

            Integer sales = 0;
            for (MallSpecifications spec : specifications) {
                sales = sales + spec.getSales();
            }
            goodsDetailResp.setSales(sales);
        }
        return ResponseData.success(goodsDetailResp);
    }
}
