package com.xiaoniu.system.groupgoods.groupbuying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoniu.common.core.constant.Constants;
import com.xiaoniu.common.core.exception.ServiceException;
import com.xiaoniu.common.core.resdata.RowsData;
import com.xiaoniu.common.core.utils.DateUtils;
import com.xiaoniu.common.core.utils.StringUtils;
import com.xiaoniu.common.core.utils.bean.BeanUtils;
import com.xiaoniu.common.core.vo.LabelAndValueVO;
import com.xiaoniu.common.security.utils.SecurityUtils;
import com.xiaoniu.system.groupgoods.groupbuying.domain.TbGroupBuyingGoods;
import com.xiaoniu.system.groupgoods.groupbuying.domain.TbGroupSpecifications;
import com.xiaoniu.system.groupgoods.groupbuying.dto.*;
import com.xiaoniu.system.groupgoods.groupbuying.mapper.TbGroupBuyingGoodsMapper;
import com.xiaoniu.system.groupgoods.groupbuying.mapper.TbGroupSpecificationsMapper;
import com.xiaoniu.system.groupgoods.groupbuying.service.ITbGroupBuyingGoodsService;
import com.xiaoniu.system.groupgoods.groupbuying.vo.GroupBuyingDetailsVO;
import com.xiaoniu.system.groupgoods.groupbuying.vo.GroupBuyingListVO;
import com.xiaoniu.system.groupgoods.groupbuying.vo.SpecificationsListVO;
import com.xiaoniu.system.store.goods.domain.TbGoods;
import com.xiaoniu.system.store.goods.mapper.TbGoodsMapper;
import com.xiaoniu.system.store.goods.mapper.TbGoodsSpecificationsMapper;
import com.xiaoniu.system.store.storegoods.mapper.TbStoreGoodsMapper;
import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * <p>
 * 团购商品表 服务实现类
 * </p>
 *
 * @author haoxuyang
 * @since 2024-10-18 09:19:39
 */
@Service
public class TbGroupBuyingGoodsServiceImpl extends ServiceImpl<TbGroupBuyingGoodsMapper, TbGroupBuyingGoods> implements ITbGroupBuyingGoodsService {
    @Resource
    private TbGroupSpecificationsMapper tbGroupSpecificationsMapper;

    @Resource
    private TbGoodsSpecificationsMapper tbGoodsSpecificationsMapper;

    @Resource
    private TbGoodsMapper tbGoodsMapper;
    @Resource
    private TbStoreGoodsMapper tbStoreGoodsMapper;

    @Override
    public RowsData<GroupBuyingListVO> groupBuyingList(GroupBuyingListQueryDTO dto) {
        try (Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize())) {
            if (StringUtils.isNotEmpty(dto.getSortType())) {
                if ("1".equals(dto.getSortType())) {
                    dto.setSortType("ASC");
                } else if ("2".equals(dto.getSortType())) {
                    dto.setSortType("DESC");
                } else {
                    dto.setSortType(null);
                }
            }
            List<GroupBuyingListVO> list = baseMapper.getGroupBuyingList(dto);
            return new RowsData<>(list, page.getTotal(), page.getPages());
        }
    }

    @Override
    public void addGroupBuying(AddGroupBuyingDTO dto) {
        if (CollectionUtils.isEmpty(dto.getSpecificationsList())) {
            throw new ServiceException("团购商品规格不能为空");
        }
        TbGroupBuyingGoods buyingGoods = new TbGroupBuyingGoods();
        BeanUtils.copyProperties(dto, buyingGoods);
        buyingGoods.setStartSaleTime(DateUtils.parseDate(dto.getStartSaleTime()));
        buyingGoods.setEndSaleTime(DateUtils.parseDate(dto.getEndSaleTime()));
        try {
            buyingGoods.setCreateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            log.error("获取用户名称失败");
        }
        buyingGoods.setCreateTime(new Date());
        //获取商品信息
        TbGoods tbGoods = tbGoodsMapper.selectById(dto.getGoodsId());
        if (StringUtils.isNull(tbGoods) || Constants.TWO.equals(tbGoods.getDelFlag())) {
            throw new ServiceException("商品不存在");
        }
        buyingGoods.setGoodsName(tbGoods.getGoodsName());
        baseMapper.insert(buyingGoods);
        //处理团购商品规格
        List<TbGroupSpecifications> list = new ArrayList<>();
        for (GroupSpecificationsInfoDTO groupSpecificationsInfoDTO : dto.getSpecificationsList()) {
            TbGroupSpecifications specifications = new TbGroupSpecifications();
            BeanUtils.copyProperties(groupSpecificationsInfoDTO, specifications);
            specifications.setGroupId(buyingGoods.getId());
            specifications.setGoodsId(dto.getGoodsId());
            list.add(specifications);
        }
        if (!CollectionUtils.isEmpty(list)) {
            tbGroupSpecificationsMapper.insertBatch(list);
        }
    }

    @Override
    public void editGroupBuying(EditGroupBuyingDTO dto) {
        TbGroupBuyingGoods buyingGoods = baseMapper.selectById(dto.getId());
        if (StringUtils.isNull(buyingGoods)) {
            throw new ServiceException("当前信息不存在");
        }
        if (Constants.TWO.equals(buyingGoods.getDelFlag())) {
            throw new ServiceException("当前信息已被删除");
        }
        BeanUtils.copyProperties(dto, buyingGoods);
        buyingGoods.setStartSaleTime(DateUtils.parseDate(dto.getStartSaleTime()));
        buyingGoods.setEndSaleTime(DateUtils.parseDate(dto.getEndSaleTime()));
        try {
            buyingGoods.setUpdateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            log.error("获取用户名称失败");
        }
        //获取商品信息
        TbGoods tbGoods = tbGoodsMapper.selectById(dto.getGoodsId());
        if (StringUtils.isNull(tbGoods) || Constants.TWO.equals(tbGoods.getDelFlag())) {
            throw new ServiceException("商品不存在");
        }
        buyingGoods.setGoodsName(tbGoods.getGoodsName());
        buyingGoods.setUpdateTime(new Date());
        baseMapper.updateById(buyingGoods);
        //处理团购商品规格
        //先删除
        tbGroupSpecificationsMapper.delete(new LambdaQueryWrapper<TbGroupSpecifications>().eq(TbGroupSpecifications::getGroupId, dto.getId()));
        List<TbGroupSpecifications> list = new ArrayList<>();
        for (GroupSpecificationsInfoDTO groupSpecificationsInfoDTO : dto.getSpecificationsList()) {
            TbGroupSpecifications specifications = new TbGroupSpecifications();
            BeanUtils.copyProperties(groupSpecificationsInfoDTO, specifications);
            specifications.setGroupId(buyingGoods.getId());
            specifications.setGoodsId(dto.getGoodsId());
            list.add(specifications);
        }
        if (!CollectionUtils.isEmpty(list)) {
            tbGroupSpecificationsMapper.insertBatch(list);
        }
    }

    @Override
    public GroupBuyingDetailsVO details(Long id) {
        TbGroupBuyingGoods buyingGoods = baseMapper.selectById(id);
        if (StringUtils.isNull(buyingGoods)) {
            throw new ServiceException("当前信息不存在");
        }
        if (Constants.TWO.equals(buyingGoods.getDelFlag())) {
            throw new ServiceException("当前信息已被删除");
        }
        GroupBuyingDetailsVO detailsVO = new GroupBuyingDetailsVO();
        BeanUtils.copyProperties(buyingGoods, detailsVO);
        detailsVO.setGoodsId(String.valueOf(buyingGoods.getGoodsId()));
        detailsVO.setGoodsType1(String.valueOf(buyingGoods.getGoodsType1()));
        detailsVO.setGoodsType2(String.valueOf(buyingGoods.getGoodsType2()));
        //团购商品规格
        List<SpecificationsListVO> tbGroupSpecifications = tbGroupSpecificationsMapper.selectVoList(new LambdaQueryWrapper<TbGroupSpecifications>().eq(TbGroupSpecifications::getGroupId, buyingGoods.getId()), SpecificationsListVO.class);
        if (!CollectionUtils.isEmpty(tbGroupSpecifications)) {
            detailsVO.setSpecificationsList(tbGroupSpecifications);
        }
        return detailsVO;
    }

    @Override
    public List<SpecificationsListVO> getSpecificationsListByGroupId(SpecificationsListQueryDTO dto) {
        return tbGroupSpecificationsMapper.getSpecificationsListByGroupId(dto);
    }

    @Override
    public void delGroupBuying(Long id) {
        baseMapper.update(new LambdaUpdateWrapper<TbGroupBuyingGoods>().eq(TbGroupBuyingGoods::getId, id).set(TbGroupBuyingGoods::getDelFlag, Constants.TWO));
    }

    @Override
    public List<SpecificationsListVO> getSpecificationsListByGoodsId(Long goodsId) {
        return tbGoodsSpecificationsMapper.getSpecificationsListByGoodsId(goodsId);
    }

    @Override
    public List<LabelAndValueVO> getGoodsListByType(Long goodType1Id, Long goodType2Id) {
        //根据类型获取商品id
        List<Long> goodsIdList = tbStoreGoodsMapper.getGoodsIdByTypeId(goodType1Id);
        if (StringUtils.isNull(goodsIdList)) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<TbGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbGoods::getGoodsType1, goodType1Id);
        if (StringUtils.isNotNull(goodType2Id)) {
            wrapper.eq(TbGoods::getGoodsType2, goodType2Id);
        }
        wrapper.eq(TbGoods::getDelFlag, Constants.ZERO);
        wrapper.eq(TbGoods::getGoodsStatus, Constants.ONE);
        wrapper.in(TbGoods::getId, goodsIdList);
        wrapper.orderByDesc(TbGoods::getCreateTime);

        List<TbGoods> tbGoods = tbGoodsMapper.selectList(wrapper);
        return tbGoods.stream().map(good -> {
            LabelAndValueVO labelAndValueVO = new LabelAndValueVO();
            labelAndValueVO.setLabel(good.getGoodsName());
            labelAndValueVO.setValue(String.valueOf(good.getId()));
            return labelAndValueVO;
        }).toList();
    }

    @Override
    @Scheduled(cron = "0 5 0 1/1 * ? ")
    public void refreshGroupsGoods() {
        //获取积分商品
        LambdaQueryWrapper<TbGroupBuyingGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbGroupBuyingGoods::getStatus, Constants.ONE);
        wrapper.eq(TbGroupBuyingGoods::getDelFlag, Constants.ZERO);
        String date = DateUtils.getTime();
        wrapper.lt(TbGroupBuyingGoods::getEndSaleTime, date);
        List<TbGroupBuyingGoods> tbGroupBuyingGoods = baseMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(tbGroupBuyingGoods)) {
            tbGroupBuyingGoods.forEach(item -> item.setStatus(Constants.TWO));
            baseMapper.updateBatchById(tbGroupBuyingGoods);
        }
    }
}
