package shop.alien.store.service.impl;

import com.alibaba.excel.util.StringUtils;
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 shop.alien.entity.store.LifeDiscountCoupon;
import shop.alien.entity.store.StoreImg;
import shop.alien.entity.store.StoreInfo;
import shop.alien.entity.storePlatform.StoreOperationalActivity;
import shop.alien.entity.storePlatform.vo.StoreOperationalActivityVO;
import shop.alien.mapper.LifeDiscountCouponMapper;
import shop.alien.mapper.StoreImgMapper;
import shop.alien.mapper.StoreInfoMapper;
import shop.alien.mapper.storePlantform.StoreOperationalActivityMapper;
import shop.alien.store.service.OperationalActivityService;

import java.util.*;

/**
 * 运营活动服务实现类
 * <p>
 * 提供运营活动的增删改查功能，包括：
 * 1. 活动的创建、更新、删除
 * 2. 活动列表查询、分页查询
 * 3. 活动状态管理
 * </p>
 *
 * @author system
 * @since 2025-11-26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OperationalActivityServiceImpl implements OperationalActivityService {

    private final StoreOperationalActivityMapper activityMapper;

    private final StoreImgMapper imgMapper;

    private final LifeDiscountCouponMapper lifeDiscountCouponMapper;

    private final StoreInfoMapper storeInfoMapper;

    @Override
    public int auditActivity(Integer id, Integer status, String approvalComments) {
        log.info("OperationalActivityServiceImpl.auditActivity: id={}, status={}, approvalComments={}", id, status, approvalComments);

        if (id == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }
        if (status == null) {
            throw new IllegalArgumentException("审核状态不能为空");
        }

        if (!Objects.equals(status, 1) && StringUtils.isBlank(approvalComments)) {
            throw new IllegalArgumentException("驳回原因不能为空");
        }

        StoreOperationalActivity update = new StoreOperationalActivity();
        update.setId(id);
        if (Objects.equals(status, 1)) {
            StoreOperationalActivity activity = activityMapper.selectById(id);
            if (activity == null) {
                throw new IllegalArgumentException("活动不存在");
            }
            update.setStatus(resolveApprovedStatus(activity));
            update.setApprovalComments(null);
        } else {
            update.setStatus(3);
            update.setApprovalComments(approvalComments);
        }

        return activityMapper.updateById(update);
    }

    @Override
    public IPage<StoreOperationalActivityVO> pageActivityDetail(Integer storeId, String storeName, Integer pageNum, Integer pageSize, Integer activityStatus, String activityName) {
        log.info("OperationalActivityServiceImpl.pageActivityDetail: storeId={}, storeName={}, pageNum={}, pageSize={}, activityStatus={}, activityName={}", storeId, storeName, pageNum, pageSize, activityStatus, activityName);

//        if (storeId == null && StringUtils.isBlank(storeName)) {
//            throw new IllegalArgumentException("请至少提供商户ID或商户名称");
//        }

        int current = (pageNum == null || pageNum <= 0) ? 1 : pageNum;
        int size = (pageSize == null || pageSize <= 0) ? 10 : pageSize;

        // 收集门店ID
        LinkedHashSet<Integer> storeIds = new LinkedHashSet<>();
        if (storeId != null) {
            storeIds.add(storeId);
        }
        if (StringUtils.isNotBlank(storeName)) {
            LambdaQueryWrapper<StoreInfo> storeWrapper = new LambdaQueryWrapper<>();
            storeWrapper.like(StoreInfo::getStoreName, storeName)
                    .eq(StoreInfo::getDeleteFlag, 0)
                    .select(StoreInfo::getId, StoreInfo::getStoreName);
            List<StoreInfo> storeList = storeInfoMapper.selectList(storeWrapper);
            for (StoreInfo info : storeList) {
                if (info.getId() != null) {
                    storeIds.add(info.getId());
                }
            }
        }

//        if (storeIds.isEmpty()) {
//            return new Page<>(current, size, 0);
//        }

        LambdaQueryWrapper<StoreOperationalActivity> wrapper = new LambdaQueryWrapper<>();
        if (activityStatus != null) {
            wrapper.eq(StoreOperationalActivity::getStatus, activityStatus);
        }
        if (StringUtils.isNotBlank(activityName)) {
            wrapper.like(StoreOperationalActivity::getActivityName, activityName);
        }
//
//        if (!storeIds.isEmpty()) {
//            wrapper.in(StoreOperationalActivity::getStoreId, storeIds);
//        }
        wrapper.eq(StoreOperationalActivity::getDeleteFlag, 0);
        wrapper.orderByDesc(StoreOperationalActivity::getCreatedTime);

        IPage<StoreOperationalActivity> entityPage = activityMapper.selectPage(new Page<>(current, size), wrapper);

        List<StoreOperationalActivityVO> voRecords = new ArrayList<>(entityPage.getRecords().size());
        Map<Integer, String> storeCache = new LinkedHashMap<>();

        for (StoreOperationalActivity activity : entityPage.getRecords()) {
            StoreOperationalActivityVO vo = new StoreOperationalActivityVO();
            BeanUtils.copyProperties(activity, vo);
            vo.setStatusName(resolveStatusName(activity.getStatus()));

            if (activity.getCouponId() != null) {
                LifeDiscountCoupon coupon = lifeDiscountCouponMapper.selectById(activity.getCouponId());
                if (coupon != null) {
                    vo.setCouponName(coupon.getName());
                }
            }

            attachStoreInfo(vo, storeCache);
            fillActivityImages(vo);
            voRecords.add(vo);
        }

        Page<StoreOperationalActivityVO> voPage = new Page<>(entityPage.getCurrent(), entityPage.getSize(), entityPage.getTotal());
        voPage.setRecords(voRecords);
        return voPage;
    }

    @Override
    public StoreOperationalActivityVO getActivityDetailById(Integer id) {
        log.info("OperationalActivityServiceImpl.getActivityDetailById: id={}", id);

        if (id == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }

        StoreOperationalActivity activity = activityMapper.selectById(id);
        if (activity == null) {
            return null;
        }

        StoreOperationalActivityVO vo = new StoreOperationalActivityVO();
        BeanUtils.copyProperties(activity, vo);
        vo.setStatusName(resolveStatusName(activity.getStatus()));

        if (activity.getCouponId() != null) {
            LifeDiscountCoupon coupon = lifeDiscountCouponMapper.selectById(activity.getCouponId());
            if (coupon != null) {
                vo.setCouponName(coupon.getName());
            }
        }

        attachStoreInfo(vo, new LinkedHashMap<>());
        fillActivityImages(vo);
        return vo;
    }

    private int resolveApprovedStatus(StoreOperationalActivity activity) {
        Date now = new Date();
        if (activity.getStartTime() == null || activity.getEndTime() == null) {
            return 2;
        }
        if (now.before(activity.getStartTime())) {
            return 2;
        }
        if (!now.after(activity.getEndTime())) {
            return 5;
        }
        return 7;
    }

    private String resolveStatusName(Integer status) {
        if (status == null) {
            return null;
        }
        switch (status) {
            case 1:
                return "待审核";
            case 2:
                return "未开始";
            case 3:
                return "审核拒绝";
            case 4:
                return "已售罄";
            case 5:
                return "进行中";
            case 6:
                return "已下架";
            case 7:
                return "已结束";
            default:
                return null;
        }
    }

    private void attachStoreInfo(StoreOperationalActivityVO vo, Map<Integer, String> cache) {
        if (vo == null || vo.getStoreId() == null) {
            return;
        }
        Integer sid = vo.getStoreId();
        if (cache != null && cache.containsKey(sid)) {
            vo.setStoreName(cache.get(sid));
            return;
        }
        StoreInfo storeInfo = storeInfoMapper.selectById(sid);
        if (storeInfo != null) {
            vo.setStoreName(storeInfo.getStoreName());
            if (cache != null) {
                cache.put(sid, storeInfo.getStoreName());
            }
        }
    }

    private void fillActivityImages(StoreOperationalActivityVO vo) {
        if (vo == null || vo.getStoreId() == null || vo.getId() == null) {
            return;
        }
        StoreImg titleImg = imgMapper.selectOne(new LambdaQueryWrapper<StoreImg>()
                .eq(StoreImg::getStoreId, vo.getStoreId())
                .eq(StoreImg::getBusinessId, vo.getId())
                .eq(StoreImg::getImgType, 26)
                .eq(StoreImg::getDeleteFlag, 0));
        if (titleImg != null) {
            vo.setActivityTitleImg(titleImg);
            vo.setActivityTitleImgUrl(titleImg.getImgUrl());
        }

        StoreImg detailImg = imgMapper.selectOne(new LambdaQueryWrapper<StoreImg>()
                .eq(StoreImg::getStoreId, vo.getStoreId())
                .eq(StoreImg::getBusinessId, vo.getId())
                .eq(StoreImg::getImgType, 27)
                .eq(StoreImg::getDeleteFlag, 0));
        if (detailImg != null) {
            vo.setActivityDetailImg(detailImg);
            vo.setActivityDetailImgUrl(detailImg.getImgUrl());
        }
    }
}

