package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.store.PlatformShopMembershipPlan;
import shop.alien.mapper.PlatformShopMembershipPlanMapper;
import shop.alien.store.service.PlatformShopMembershipPlanPlatformService;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class PlatformShopMembershipPlanPlatformServiceImpl
        extends ServiceImpl<PlatformShopMembershipPlanMapper, PlatformShopMembershipPlan>
        implements PlatformShopMembershipPlanPlatformService {

    @Override
    public IPage<PlatformShopMembershipPlan> pagePlans(String planName, Integer enabled, int pageNum, int pageSize) {
        Page<PlatformShopMembershipPlan> p = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<PlatformShopMembershipPlan> w = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(planName)) {
            w.like(PlatformShopMembershipPlan::getPlanName, planName.trim());
        }
        if (enabled != null) {
            w.eq(PlatformShopMembershipPlan::getEnabled, enabled);
        }
        w.orderByDesc(PlatformShopMembershipPlan::getRecommended)
                .orderByAsc(PlatformShopMembershipPlan::getSortOrder)
                .orderByDesc(PlatformShopMembershipPlan::getId);
        IPage<PlatformShopMembershipPlan> result = page(p, w);
        for (PlatformShopMembershipPlan plan : result.getRecords()) {
            plan.setBenefitCount(countEnabledBenefits(plan));
        }
        return result;
    }

    /**
     * 统计方案已开启的权益项数量：8 个 0/1 开关为 1 则各计 1；推广位次数、月算力大于 0 各计 1。
     */
    static int countEnabledBenefits(PlatformShopMembershipPlan plan) {
        if (plan == null) {
            return 0;
        }
        int n = 0;
        if (Integer.valueOf(1).equals(plan.getBenefitAdvancedDataAnalysis())) {
            n++;
        }
        if (Integer.valueOf(1).equals(plan.getBenefitMarketingPriority())) {
            n++;
        }
        if (Integer.valueOf(1).equals(plan.getBenefitFriendCouponManage())) {
            n++;
        }
        if (Integer.valueOf(1).equals(plan.getBenefitOrderingManage())) {
            n++;
        }
        if (Integer.valueOf(1).equals(plan.getBenefitFriendRelationManage())) {
            n++;
        }
        if (Integer.valueOf(1).equals(plan.getBenefitCommentAppealDelete())) {
            n++;
        }
        if (Integer.valueOf(1).equals(plan.getBenefitOperatingData())) {
            n++;
        }
        if (Integer.valueOf(1).equals(plan.getBenefitOperationalActivity())) {
            n++;
        }
        if (plan.getBenefitWeeklyHomepageSlots() != null && plan.getBenefitWeeklyHomepageSlots() > 0) {
            n++;
        }
        if (plan.getBenefitMonthlyComputingPower() != null && plan.getBenefitMonthlyComputingPower() > 0) {
            n++;
        }
        return n;
    }

    @Override
    public boolean saveOrUpdatePlan(PlatformShopMembershipPlan plan) {
        if (plan == null) {
            return false;
        }
        if (StringUtils.isBlank(plan.getPlanName())) {
            throw new IllegalArgumentException("会员卡名称不能为空");
        }
        if (plan.getDurationMonths() == null || plan.getDurationMonths() <= 0) {
            throw new IllegalArgumentException("时长（月）必须大于0");
        }
        if (plan.getPrice() == null || plan.getPrice().signum() <= 0) {
            throw new IllegalArgumentException("价格必须大于0");
        }
        if (plan.getSortOrder() == null) {
            plan.setSortOrder(0);
        }
        if (plan.getEnabled() == null) {
            plan.setEnabled(1);
        }
        if (plan.getRecommended() == null) {
            plan.setRecommended(0);
        }
        applyBenefitDefaults(plan);
        Date now = new Date();
        if (Integer.valueOf(1).equals(plan.getRecommended())) {
            // 全表仅允许一条推荐：新建时尚无 id，先清掉所有推荐；更新时保留当前这条
            clearOtherPlansRecommended(plan.getId());
        }
        if (plan.getId() == null) {
            plan.setCreatedTime(now);
            plan.setUpdatedTime(now);
            return save(plan);
        }
        plan.setUpdatedTime(now);
        return updateById(plan);
    }

    @Override
    public boolean toggleEnabled(Integer id, Integer enabled) {
        if (id == null || enabled == null) {
            return false;
        }
        PlatformShopMembershipPlan plan = getById(id);
        if (plan == null) {
            return false;
        }
        plan.setEnabled(enabled);
        plan.setUpdatedTime(new Date());
        return updateById(plan);
    }

    @Override
    public boolean toggleRecommended(Integer id, Integer recommended) {
        if (id == null || recommended == null) {
            return false;
        }
        if (recommended != 0 && recommended != 1) {
            return false;
        }
        PlatformShopMembershipPlan plan = getById(id);
        if (plan == null) {
            return false;
        }
        if (recommended == 1) {
            clearOtherPlansRecommended(id);
        }
        plan.setRecommended(recommended);
        plan.setUpdatedTime(new Date());
        return updateById(plan);
    }

    /**
     * 将「当前推荐」全部置为非推荐；若 exceptId 非空则跳过该主键（用于保留即将设为推荐的那一条）。
     */
    private void clearOtherPlansRecommended(Integer exceptId) {
        LambdaUpdateWrapper<PlatformShopMembershipPlan> u = new LambdaUpdateWrapper<>();
        u.eq(PlatformShopMembershipPlan::getRecommended, 1);
        if (exceptId != null) {
            u.ne(PlatformShopMembershipPlan::getId, exceptId);
        }
        u.set(PlatformShopMembershipPlan::getRecommended, 0);
        u.set(PlatformShopMembershipPlan::getUpdatedTime, new Date());
        update(u);
    }

    @Override
    public int logicDeleteByIds(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("方案ID列表不能为空");
        }
        List<Integer> clean = ids.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        if (clean.isEmpty()) {
            throw new IllegalArgumentException("方案ID列表不能为空");
        }
        Collection<PlatformShopMembershipPlan> plans = listByIds(clean);
        if (plans == null || plans.isEmpty()) {
            return 0;
        }
        List<Integer> pkIds = plans.stream().map(PlatformShopMembershipPlan::getId).collect(Collectors.toList());
        removeByIds(pkIds);
        return pkIds.size();
    }

    /**
     * 权益开关与数值：null 视为 0；数值类不允许为负。
     */
    private static void applyBenefitDefaults(PlatformShopMembershipPlan plan) {
        if (plan.getBenefitAdvancedDataAnalysis() == null) {
            plan.setBenefitAdvancedDataAnalysis(0);
        }
        if (plan.getBenefitMarketingPriority() == null) {
            plan.setBenefitMarketingPriority(0);
        }
        if (plan.getBenefitFriendCouponManage() == null) {
            plan.setBenefitFriendCouponManage(0);
        }
        if (plan.getBenefitOrderingManage() == null) {
            plan.setBenefitOrderingManage(0);
        }
        if (plan.getBenefitFriendRelationManage() == null) {
            plan.setBenefitFriendRelationManage(0);
        }
        if (plan.getBenefitCommentAppealDelete() == null) {
            plan.setBenefitCommentAppealDelete(0);
        }
        if (plan.getBenefitOperatingData() == null) {
            plan.setBenefitOperatingData(0);
        }
        if (plan.getBenefitOperationalActivity() == null) {
            plan.setBenefitOperationalActivity(0);
        }
        if (plan.getBenefitWeeklyHomepageSlots() == null) {
            plan.setBenefitWeeklyHomepageSlots(0);
        }
        if (plan.getBenefitMonthlyComputingPower() == null) {
            plan.setBenefitMonthlyComputingPower(0);
        }
        if (plan.getBenefitWeeklyHomepageSlots() < 0 || plan.getBenefitMonthlyComputingPower() < 0) {
            throw new IllegalArgumentException("推广位次数与算力不能为负数");
        }
    }
}
