package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import shop.alien.entity.storePlatform.StoreOperationalActivity;
import shop.alien.entity.storePlatform.StoreOperationalActivityAchievement;
import shop.alien.entity.storePlatform.vo.StoreOperationalActivityAchievementCaseDetailVo;
import shop.alien.entity.storePlatform.vo.StoreOperationalActivityAchievementCaseItemVo;
import shop.alien.entity.storePlatform.vo.StoreOperationalActivityAchievementCaseVo;
import shop.alien.entity.storePlatform.vo.StoreOperationalActivityAchievementVo;
import shop.alien.entity.storePlatform.vo.StoreOperationalActivityCasePreviewVo;
import shop.alien.mapper.storePlantform.StoreOperationalActivityAchievementMapper;
import shop.alien.mapper.storePlantform.StoreOperationalActivityMapper;
import shop.alien.store.dto.StoreOperationalActivityAchievementDto;
import shop.alien.store.service.StoreOperationalActivityAchievementService;
/**
 * 运营活动成果服务实现
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StoreOperationalActivityAchievementServiceImpl implements StoreOperationalActivityAchievementService {

    private final StoreOperationalActivityAchievementMapper achievementMapper;
    private final StoreOperationalActivityMapper activityMapper;

    @Override
    public boolean addAchievement(StoreOperationalActivityAchievementDto dto) {
        if (dto == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if (dto.getActivityId() == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }
        if (dto.getUserId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        if (dto.getSignupId() == null) {
            throw new IllegalArgumentException("报名ID不能为空");
        }

        StoreOperationalActivity activity = activityMapper.selectById(dto.getActivityId());
        if (activity == null) {
            throw new IllegalArgumentException("活动不存在");
        }
        Date now = new Date();
        if (activity.getStartTime() != null && now.before(activity.getStartTime())) {
            throw new IllegalArgumentException("活动未开始，不允许新增成果");
        }

        StoreOperationalActivityAchievement achievement = new StoreOperationalActivityAchievement();
        achievement.setActivityId(dto.getActivityId());
        achievement.setUserId(dto.getUserId());
        achievement.setSignupId(dto.getSignupId());
        achievement.setAchievementDesc(dto.getAchievementDesc());
        achievement.setMediaUrls(dto.getMediaUrls());
        achievement.setDeleteFlag(0);
        achievement.setCreatedUserId(dto.getUserId());
        return achievementMapper.insert(achievement) > 0;
    }

    @Override
    public StoreOperationalActivityAchievementVo getAchievementDetail(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("成果ID不能为空");
        }
        StoreOperationalActivityAchievement achievement = achievementMapper.selectById(id);
        if (achievement == null || achievement.getDeleteFlag() != null && achievement.getDeleteFlag() == 1) {
            return null;
        }
        StoreOperationalActivityAchievementVo vo = new StoreOperationalActivityAchievementVo();
        BeanUtils.copyProperties(achievement, vo);
        vo.setMediaUrlList(splitMediaUrls(achievement.getMediaUrls()));
        return vo;
    }

    @Override
    public IPage<StoreOperationalActivityAchievementVo> listAchievements(Integer activityId, Integer userId, Integer signupId,
                                                                         Integer pageNum, Integer pageSize) {
        int current = pageNum == null || pageNum <= 0 ? 1 : pageNum;
        int size = pageSize == null || pageSize <= 0 ? 10 : pageSize;
        Page<StoreOperationalActivityAchievement> page = new Page<>(current, size);

        LambdaQueryWrapper<StoreOperationalActivityAchievement> wrapper = new LambdaQueryWrapper<>();
        if (activityId != null) {
            wrapper.eq(StoreOperationalActivityAchievement::getActivityId, activityId);
        }
        if (userId != null) {
            wrapper.eq(StoreOperationalActivityAchievement::getUserId, userId);
        }
        if (signupId != null) {
            wrapper.eq(StoreOperationalActivityAchievement::getSignupId, signupId);
        }
        wrapper.eq(StoreOperationalActivityAchievement::getDeleteFlag, 0)
                .orderByDesc(StoreOperationalActivityAchievement::getCreatedTime);

        IPage<StoreOperationalActivityAchievement> entityPage = achievementMapper.selectPage(page, wrapper);
        Page<StoreOperationalActivityAchievementVo> voPage = new Page<>(entityPage.getCurrent(), entityPage.getSize(), entityPage.getTotal());
        if (entityPage.getRecords() != null) {
            List<StoreOperationalActivityAchievementVo> voList = new ArrayList<>();
            for (StoreOperationalActivityAchievement item : entityPage.getRecords()) {
                if (item == null) {
                    continue;
                }
                StoreOperationalActivityAchievementVo vo = new StoreOperationalActivityAchievementVo();
                BeanUtils.copyProperties(item, vo);
                vo.setMediaUrlList(splitMediaUrls(item.getMediaUrls()));
                voList.add(vo);
            }
            voPage.setRecords(voList);
        }
        return voPage;
    }

    @Override
    public IPage<StoreOperationalActivityAchievementCaseVo> listCasePage(Integer storeId, Integer activityStatus, Integer pageNum, Integer pageSize) {
        if (storeId == null) {
            throw new IllegalArgumentException("店铺ID不能为空");
        }
        int current = pageNum == null || pageNum <= 0 ? 1 : pageNum;
        int size = pageSize == null || pageSize <= 0 ? 10 : pageSize;
        Page<StoreOperationalActivityAchievementCaseVo> page = new Page<>(current, size);
        return achievementMapper.selectCasePage(page, storeId, activityStatus);
    }

    @Override
    public StoreOperationalActivityCasePreviewVo listCasePreview(Integer storeId) {
        if (storeId == null) {
            throw new IllegalArgumentException("店铺ID不能为空");
        }
        StoreOperationalActivityCasePreviewVo vo = new StoreOperationalActivityCasePreviewVo();
        IPage<StoreOperationalActivityAchievementCaseVo> page = listCasePage(storeId, null, 1, 1);
        vo.setTotal(page.getTotal());
        vo.setList(page.getRecords() != null ? page.getRecords() : new ArrayList<>());
        return vo;
    }

    @Override
    public StoreOperationalActivityAchievementCaseDetailVo getCaseDetail(Integer activityId, Integer userId) {
        if (activityId == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        StoreOperationalActivityAchievementCaseDetailVo header = achievementMapper.selectCaseHeader(activityId, userId);
        if (header == null) {
            return null;
        }
        List<StoreOperationalActivityAchievementCaseItemVo> items = achievementMapper.selectCaseItems(activityId, userId);
        
        // 根据成果数据判断上传情况：查到数据就是已上传，没有就是未上传
        if (items != null && !items.isEmpty()) {
            header.setHasResult(1); // 已上传
            for (StoreOperationalActivityAchievementCaseItemVo item : items) {
                if (item == null) {
                    continue;
                }
                item.setMediaUrlList(splitMediaUrls(item.getMediaUrls()));
            }
        } else {
            header.setHasResult(0); // 未上传
        }
        
        header.setAchievementList(items);
        return header;
    }

    @Override
    public IPage<StoreOperationalActivityAchievementCaseVo> listStoreCasePage(Integer storeId, Integer activityStatus,
                                                                               String activityName, Integer pageNum, Integer pageSize) {
        if (storeId == null || storeId <= 0) {
            throw new IllegalArgumentException("商户ID不能为空");
        }
        int current = pageNum == null || pageNum <= 0 ? 1 : pageNum;
        int size = pageSize == null || pageSize <= 0 ? 10 : pageSize;
        Page<StoreOperationalActivityAchievementCaseVo> page = new Page<>(current, size);
        return achievementMapper.selectStoreCasePage(page, storeId, activityStatus, activityName);
    }

    private List<String> splitMediaUrls(String mediaUrls) {
        if (mediaUrls == null || mediaUrls.trim().isEmpty()) {
            return Collections.emptyList();
        }
        String[] parts = mediaUrls.split(";");
        List<String> results = new ArrayList<>();
        for (String part : parts) {
            if (part != null && !part.trim().isEmpty()) {
                results.add(part.trim());
            }
        }
        return results;
    }
}
