package com.xiaoniu.system.pointsgoods.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.ChangeStatusDTO;
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.vo.LabelAndValueVO;
import com.xiaoniu.common.security.utils.SecurityUtils;
import com.xiaoniu.system.groupgoods.groupbuying.vo.SpecificationsListVO;
import com.xiaoniu.system.platformsettings.storetype.domain.TbStoreType;
import com.xiaoniu.system.platformsettings.storetype.mapper.TbStoreTypeMapper;
import com.xiaoniu.system.pointsgoods.domain.TbPointsGoods;
import com.xiaoniu.system.pointsgoods.domain.TbPointsGoodsSpecifications;
import com.xiaoniu.system.pointsgoods.dto.EditPointsGoodsDTO;
import com.xiaoniu.system.pointsgoods.dto.PointsGoodsQueryDTO;
import com.xiaoniu.system.pointsgoods.mapper.TbPointsGoodsMapper;
import com.xiaoniu.system.pointsgoods.mapper.TbPointsGoodsSpecificationsMapper;
import com.xiaoniu.system.pointsgoods.service.ITbPointsGoodsService;
import com.xiaoniu.system.pointsgoods.vo.AddPointsGoodsDTO;
import com.xiaoniu.system.pointsgoods.vo.PointsGoodsDetailsVO;
import com.xiaoniu.system.pointsgoods.vo.PointsGoodsListVO;
import com.xiaoniu.system.pointsgoods.vo.PointsGoodsSpecificationsVO;
import com.xiaoniu.system.store.goods.domain.TbGoods;
import com.xiaoniu.system.store.goods.dto.SpecificationQueryDTO;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 积分商品信息表 服务实现类
 * </p>
 *
 * @author haoxuyang
 * @since 2024-10-29 06:20:13
 */
@Service
public class TbPointsGoodsServiceImpl extends ServiceImpl<TbPointsGoodsMapper, TbPointsGoods> implements ITbPointsGoodsService {

    @Resource
    private TbGoodsMapper tbGoodsMapper;
    @Resource
    private TbPointsGoodsSpecificationsMapper tbPointsGoodsSpecificationsMapper;
    @Resource
    private TbGoodsSpecificationsMapper tbGoodsSpecificationsMapper;
    @Resource
    private TbStoreTypeMapper tbStoreTypeMapper;
    @Resource
    private TbStoreGoodsMapper tbStoreGoodsMapper;

    @Override
    public RowsData<PointsGoodsListVO> pointsGoodsList(PointsGoodsQueryDTO 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<PointsGoodsListVO> list = baseMapper.pointsGoodsList(dto);
            return new RowsData<>(list, page.getTotal(), dto.getPageNum());
        }
    }

    @Override
    public void addPointsGoods(AddPointsGoodsDTO dto) {
        TbPointsGoods tbPointsGoods = new TbPointsGoods();
        tbPointsGoods.setGoodsId(dto.getGoodsId());
        tbPointsGoods.setSalesBeginTime(DateUtils.parseDate(dto.getSalesBeginTime()));
        tbPointsGoods.setSalesEndTime(DateUtils.parseDate(dto.getSalesEndTime()));
        tbPointsGoods.setStatus(dto.getStatus());
        try {
            tbPointsGoods.setCreateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            log.error("获取当前登陆人失败");
        }
        tbPointsGoods.setCreateTime(new Date());
        tbPointsGoods.setDelFlag(Constants.ZERO);
        baseMapper.insert(tbPointsGoods);
        if (!CollectionUtils.isEmpty(dto.getSpecificationsList())) {
            //获取商品类型
            String goodsType = tbGoodsMapper.getGoodsTypeByGoodsId(dto.getGoodsId());
            //处理商品规格信息
            List<TbPointsGoodsSpecifications> specificationList = dto.getSpecificationsList().stream().map(item -> {
                TbPointsGoodsSpecifications specifications = new TbPointsGoodsSpecifications();
                specifications.setPointsGoodsId(tbPointsGoods.getId());
                specifications.setGoodsId(dto.getGoodsId());
                specifications.setSpecificationsId(item.getSpecificationsId());
                specifications.setSpecificationsName(item.getSpecificationsName());
                specifications.setOriginalPrice(item.getOriginalPrice());
                specifications.setGoodsType(goodsType);
                specifications.setPointsPrice(item.getPointsPrice());
                specifications.setExchangeAmount(item.getExchangeAmount());
                specifications.setStatus(item.getStatus());
                return specifications;
            }).toList();
            if (!CollectionUtils.isEmpty(specificationList)) {
                tbPointsGoodsSpecificationsMapper.insertBatch(specificationList);
            }
        }
    }

    @Override
    public void editPointsGoods(EditPointsGoodsDTO dto) {
        TbPointsGoods tbPointsGoods = baseMapper.selectById(dto.getId());
        if (StringUtils.isNull(tbPointsGoods)) {
            throw new ServiceException("当前信息不存在");
        }
        tbPointsGoods.setGoodsId(dto.getGoodsId());
        tbPointsGoods.setSalesBeginTime(DateUtils.parseZonedDate(dto.getSalesBeginTime()));
        tbPointsGoods.setSalesEndTime(DateUtils.parseZonedDate(dto.getSalesEndTime()));
        tbPointsGoods.setStatus(dto.getStatus());
        try {
            tbPointsGoods.setUpdateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            log.error("获取当前登陆人失败");
        }
        tbPointsGoods.setUpdateTime(new Date());
        baseMapper.updateById(tbPointsGoods);
        //先删除原先得规格
        tbPointsGoodsSpecificationsMapper.delete(new LambdaUpdateWrapper<TbPointsGoodsSpecifications>().eq(TbPointsGoodsSpecifications::getPointsGoodsId, dto.getId()));
        if (!CollectionUtils.isEmpty(dto.getSpecificationsList())) {
            //获取商品类型
            String goodsType = tbGoodsMapper.getGoodsTypeByGoodsId(dto.getGoodsId());
            //处理商品规格信息
            List<TbPointsGoodsSpecifications> specificationList = dto.getSpecificationsList().stream().map(item -> {
                TbPointsGoodsSpecifications specifications = new TbPointsGoodsSpecifications();
                specifications.setPointsGoodsId(tbPointsGoods.getId());
                specifications.setGoodsId(dto.getGoodsId());
                specifications.setSpecificationsId(item.getSpecificationsId());
                specifications.setSpecificationsName(item.getSpecificationsName());
                specifications.setOriginalPrice(item.getOriginalPrice());
                specifications.setGoodsType(goodsType);
                specifications.setPointsPrice(item.getPointsPrice());
                specifications.setExchangeAmount(item.getExchangeAmount());
                specifications.setStatus(item.getStatus());
                return specifications;
            }).toList();
            if (!CollectionUtils.isEmpty(specificationList)) {
                tbPointsGoodsSpecificationsMapper.insertBatch(specificationList);
            }
        }
    }

    @Override
    public PointsGoodsDetailsVO details(Long id) {
        PointsGoodsDetailsVO details = baseMapper.details(id);
        //获取商品规格
        List<TbPointsGoodsSpecifications> specifications = tbPointsGoodsSpecificationsMapper.selectList(new LambdaQueryWrapper<TbPointsGoodsSpecifications>().eq(TbPointsGoodsSpecifications::getPointsGoodsId, id));
        if (!CollectionUtils.isEmpty(specifications)) {
            details.setSpecificationsList(specifications.stream().map(item -> {
                PointsGoodsSpecificationsVO specificationsVO = new PointsGoodsSpecificationsVO();
                specificationsVO.setSpecificationsId(item.getSpecificationsId());
                specificationsVO.setSpecificationsName(item.getSpecificationsName());
                specificationsVO.setOriginalPrice(item.getOriginalPrice());
                specificationsVO.setGoodsType(item.getGoodsType());
                specificationsVO.setPointsPrice(item.getPointsPrice());
                specificationsVO.setExchangeAmount(item.getExchangeAmount());
                specificationsVO.setStatus(item.getStatus());
                return specificationsVO;
            }).toList());
        }
        return details;

    }

    @Override
    public void changeStatus(ChangeStatusDTO dto) {
        TbPointsGoods tbPointsGoods = baseMapper.selectById(dto.getId());
        if (StringUtils.isNull(tbPointsGoods)) {
            throw new ServiceException("当前信息不存在");
        }
        tbPointsGoods.setStatus(dto.getStatus());
        baseMapper.updateById(tbPointsGoods);
    }

    @Override
    public void delGoods(Long id) {
        TbPointsGoods tbPointsGoods = baseMapper.selectById(id);
        if (StringUtils.isNull(tbPointsGoods)) {
            throw new ServiceException("当前信息不存在");
        }
        tbPointsGoods.setDelFlag(Constants.TWO);
        baseMapper.updateById(tbPointsGoods);
        //先删除原先得规格
        tbPointsGoodsSpecificationsMapper.delete(new LambdaUpdateWrapper<TbPointsGoodsSpecifications>().eq(TbPointsGoodsSpecifications::getPointsGoodsId, id));
    }

    @Override
    public List<PointsGoodsSpecificationsVO> specificationList(SpecificationQueryDTO dto) {
        //获取商品类型
        String goodsType = tbGoodsMapper.getGoodsTypeByGoodsId(dto.getGoodsId());
        List<SpecificationsListVO> specificationsList = tbGoodsSpecificationsMapper.getSpecificationsListByGoodsId(dto.getGoodsId());
        return specificationsList.stream().map(specifications -> {
            PointsGoodsSpecificationsVO specificationsVO = new PointsGoodsSpecificationsVO();
            specificationsVO.setSpecificationsId(specifications.getSpecificationsId());
            specificationsVO.setSpecificationsName(specifications.getSpecificationsName());
            specificationsVO.setOriginalPrice(specifications.getOriginalPrice());
            specificationsVO.setGoodsType(goodsType);
            specificationsVO.setPointsPrice(Constants.ZERO);
            specificationsVO.setExchangeAmount(BigDecimal.ZERO);
            specificationsVO.setStatus(specifications.getStatus());
            return specificationsVO;
        }).toList();
    }

    @Override
    public List<LabelAndValueVO> getGoodsListByType(Long typeId) {
        if (StringUtils.isNull(typeId)) {
            return new ArrayList<>();
        }
        //根据二级分类获取一级分类
        TbStoreType tbStoreType = tbStoreTypeMapper.selectById(typeId);
        if (StringUtils.isNull(tbStoreType) || StringUtils.isNull(tbStoreType.getParentId())) {
            return new ArrayList<>();
        }
        //根据类型id获取商品id
        List<Long> goodsIdList = tbStoreGoodsMapper.getGoodsIdByTypeId(tbStoreType.getParentId());
        LambdaQueryWrapper<TbGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbGoods::getGoodsType1, tbStoreType.getParentId());
        wrapper.eq(TbGoods::getGoodsType2, typeId);
        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);
        if (CollectionUtils.isEmpty(tbGoods)) {
            return new ArrayList<>();
        }
        return tbGoods.stream().map(item -> {
            LabelAndValueVO andValueVO = new LabelAndValueVO();
            andValueVO.setLabel(item.getGoodsName());
            andValueVO.setValue(String.valueOf(item.getId()));
            return andValueVO;
        }).toList();
    }

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