package com.fs.his.service.impl;

import cn.hutool.json.JSONUtil;
import com.fs.common.core.domain.R;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.DateUtils;
import com.fs.course.config.CourseConfig;
import com.fs.course.domain.FsCourseAnswerReward;
import com.fs.his.domain.FsChineseMedicine;
import com.fs.his.domain.FsIntegralGoods;
import com.fs.his.domain.FsUser;
import com.fs.his.mapper.FsIntegralGoodsMapper;
import com.fs.his.mapper.FsUserMapper;
import com.fs.his.param.FsIntegralGoodsListUParam;
import com.fs.his.service.IFsIntegralGoodsService;
import com.fs.his.vo.FsIntegralGoodsChooseVO;
import com.fs.his.vo.FsIntegralGoodsListUVO;
import com.fs.his.vo.FsIntegralGoodsListVO;
import com.fs.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 积分商品Service业务层处理
 *
 * @author fs
 * @date 2023-11-02
 */
@Service
@Slf4j
public class FsIntegralGoodsServiceImpl implements IFsIntegralGoodsService
{
    @Autowired
    private FsIntegralGoodsMapper fsIntegralGoodsMapper;
    @Autowired
    private FsUserMapper fsUserMapper;

    @Autowired
    private ISysConfigService configService;

    /**
     * 查询积分商品
     *
     * @param goodsId 积分商品主键
     * @return 积分商品
     */
    @Override
    public FsIntegralGoods selectFsIntegralGoodsByGoodsId(Long goodsId)
    {
        return fsIntegralGoodsMapper.selectFsIntegralGoodsByGoodsId(goodsId);
    }

    /**
     * 查询积分商品列表
     *
     * @param fsIntegralGoods 积分商品
     * @return 积分商品
     */
    @Override
    public List<FsIntegralGoods> selectFsIntegralGoodsList(FsIntegralGoods fsIntegralGoods)
    {
        return fsIntegralGoodsMapper.selectFsIntegralGoodsList(fsIntegralGoods);
    }

    /**
     * 新增积分商品
     *
     * @param fsIntegralGoods 积分商品
     * @return 结果
     */
    @Override
    public int insertFsIntegralGoods(FsIntegralGoods fsIntegralGoods)
    {
        fsIntegralGoods.setCreateTime(DateUtils.getNowDate());
        return fsIntegralGoodsMapper.insertFsIntegralGoods(fsIntegralGoods);
    }

    /**
     * 修改积分商品
     *
     * @param fsIntegralGoods 积分商品
     * @return 结果
     */
    @Override
    public int updateFsIntegralGoods(FsIntegralGoods fsIntegralGoods)
    {
        return fsIntegralGoodsMapper.updateFsIntegralGoods(fsIntegralGoods);
    }

    /**
     * 批量删除积分商品
     *
     * @param goodsIds 需要删除的积分商品主键
     * @return 结果
     */
    @Override
    public int deleteFsIntegralGoodsByGoodsIds(Long[] goodsIds)
    {
        return fsIntegralGoodsMapper.deleteFsIntegralGoodsByGoodsIds(goodsIds);
    }

    /**
     * 删除积分商品信息
     *
     * @param goodsId 积分商品主键
     * @return 结果
     */
    @Override
    public int deleteFsIntegralGoodsByGoodsId(Long goodsId)
    {
        return fsIntegralGoodsMapper.deleteFsIntegralGoodsByGoodsId(goodsId);
    }

    @Override
    public List<FsIntegralGoodsListVO> selectFsIntegralGoodsListVO(FsIntegralGoods fsIntegralGoods) {
        return fsIntegralGoodsMapper.selectFsIntegralGoodsListVO(fsIntegralGoods);
    }

    @Override
    public List<FsIntegralGoodsListUVO> selectFsIntegralGoodsListUVO(FsIntegralGoodsListUParam param) {
        return fsIntegralGoodsMapper.selectFsIntegralGoodsListUVO(param);
    }

    @Override
    public String importIntegralGoodsService(List<FsIntegralGoods> list) {
        if (com.fs.common.utils.StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (FsIntegralGoods vo : list)
        {
            try
            {
                vo.setCreateTime(DateUtils.getNowDate());
                int i = fsIntegralGoodsMapper.insertFsIntegralGoods(vo);

                successNum++;
                successMsg.append("<br/>" + successNum + "、名称 " + vo.getGoodsName() + " 导入成功");

            }
            catch (Exception e)
            {

                failureNum++;
                String msg = "<br/>" + failureNum + "、名称 " +vo.getGoodsName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public R getCourseIntegralGoods(Long userId) {
        log.info("获取答题奖励信息, userId:{}", userId);
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        FsUser user = fsUserMapper.selectFsUserByUserId(userId);

        // 1. 创建返回对象
        FsCourseAnswerReward reward = new FsCourseAnswerReward();

        // 2. 设置当前积分
        Integer currentPoints = user.getIntegral().intValue();
        reward.setCurrentPoints(currentPoints);

        // 3. 计算用户所在阶段(每5000积分一个阶段)
        int currentStage = (currentPoints / 5000) + 1;
        int stageMaxPoints = currentStage * 5000;

        // 4. 获取当前阶段的积分商品(随机获取3个)
        FsIntegralGoodsListUParam param = new FsIntegralGoodsListUParam();
        param.setMinPoints(currentPoints);
        param.setMaxPoints(stageMaxPoints);
        List<FsIntegralGoods> stageGoods = selectRandomStageGoods(param);

        if (stageGoods.size()<3){
            param.setMinPoints(stageMaxPoints-5000);
            param.setMaxPoints(stageMaxPoints);
            stageGoods = selectRandomStageGoods(param);
        }

        // 5. 转换为奖励商品列表
        List<FsCourseAnswerReward.RewardProduct> products = new ArrayList<>();
        int minRequiredPoints = stageMaxPoints; // 用于计算进度的最小积分要求

        for (FsIntegralGoods goods : stageGoods) {
            FsCourseAnswerReward.RewardProduct product = new FsCourseAnswerReward.RewardProduct();
            product.setProductId(goods.getGoodsId());
            product.setProductName(goods.getGoodsName());
            product.setRequiredPoints(goods.getIntegral().intValue());
            product.setImageUrl(goods.getImgUrl());
            product.setOtPrice(goods.getOtPrice());
            products.add(product);

            // 更新最小所需积分
            if (goods.getIntegral().intValue() < minRequiredPoints) {
                minRequiredPoints = goods.getIntegral().intValue();
            }
        }
        reward.setProducts(products);

        // 6. 计算兑换进度(基于最低积分商品)
        int exchangeProgress = (int) ((currentPoints * 100.0) / minRequiredPoints);
        // 进度最大显示100%
        reward.setExchangeProgress(Math.min(exchangeProgress, 100));
        reward.setAvailableCoins(config.getAnswerIntegral());
        log.info("答题奖励信息: {}", reward);
        return R.ok().put("data", reward);
    }

    /**
     * 随机获取当前阶段的积分商品
     */
    private List<FsIntegralGoods> selectRandomStageGoods(FsIntegralGoodsListUParam param) {
        // 查询当前阶段的所有商品
        List<FsIntegralGoods> allGoods = fsIntegralGoodsMapper.selectFsIntegralGoodsByStage(param);

        // 如果商品数量不足3个,直接返回全部
        if (allGoods.size() <= 3) {
            return allGoods;
        }

        // 随机选择3个商品
        List<FsIntegralGoods> selectedGoods = new ArrayList<>();
        Random random = new Random();

        while (selectedGoods.size() < 3 && !allGoods.isEmpty()) {
            int index = random.nextInt(allGoods.size());
            selectedGoods.add(allGoods.get(index));
            allGoods.remove(index);
        }

        return selectedGoods;
    }

    /**
     * 获取选择积分商品列表
     */
    @Override
    public List<FsIntegralGoodsChooseVO> getChooseIntegralGoodsListByMap(Map<String, Object> params) {
        return fsIntegralGoodsMapper.getChooseIntegralGoodsListByMap(params);
    }
}
