package com.haha.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.common.exception.BusinessException;
import com.haha.common.vo.Result;
import com.haha.entity.ShopReplenisher;
import com.haha.entity.Admin;
import com.haha.mapper.ShopReplenisherMapper;
import com.haha.service.ShopReplenisherService;
import com.haha.service.AdminService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 门店补货员服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ShopReplenisherServiceImpl extends ServiceImpl<ShopReplenisherMapper, ShopReplenisher> implements ShopReplenisherService {

    private final ShopReplenisherMapper shopReplenisherMapper;
    private final AdminService adminService;

    @Override
    public List<ShopReplenisher> getReplenishersByShopId(Long shopId) {
        List<ShopReplenisher> list = shopReplenisherMapper.selectByShopId(shopId);
        // 填充状态标签
        for (ShopReplenisher sr : list) {
            if (sr.getStatus() != null) {
                if (sr.getStatus() == 1) {
                    sr.setStatusLabel("正常");
                    sr.setStatusColor("success");
                } else {
                    sr.setStatusLabel("禁用");
                    sr.setStatusColor("danger");
                }
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> addReplenisher(Long shopId, Long adminId) {
        // 检查管理员是否存在
        Admin admin = adminService.getById(adminId);
        if (admin == null) {
            throw new BusinessException(404, "管理员不存在");
        }

        // 检查是否已存在
        int count = shopReplenisherMapper.countByShopIdAndAdminId(shopId, adminId);
        if (count > 0) {
            throw new BusinessException(400, "该管理员已是此门店的补货员");
        }

        // 创建关联
        ShopReplenisher replenisher = new ShopReplenisher();
        replenisher.setShopId(shopId);
        replenisher.setAdminId(adminId);
        replenisher.setStatus(1);
        replenisher.setCreateTime(LocalDateTime.now());
        replenisher.setUpdateTime(LocalDateTime.now());

        boolean success = this.save(replenisher);
        return success ? Result.success("添加成功") : Result.error(500, "添加失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchAddReplenishers(Long shopId, List<Long> adminIds) {
        if (adminIds == null || adminIds.isEmpty()) {
            return 0;
        }
        
        List<ShopReplenisher> toAdd = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        
        for (Long adminId : adminIds) {
            // 检查管理员是否存在
            Admin admin = adminService.getById(adminId);
            if (admin == null) {
                log.warn("管理员不存在: adminId={}", adminId);
                continue;
            }
            
            // 检查是否已存在
            int count = shopReplenisherMapper.countByShopIdAndAdminId(shopId, adminId);
            if (count > 0) {
                log.warn("该管理员已是此门店的补货员: shopId={}, adminId={}", shopId, adminId);
                continue;
            }
            
            ShopReplenisher replenisher = new ShopReplenisher();
            replenisher.setShopId(shopId);
            replenisher.setAdminId(adminId);
            replenisher.setStatus(1);
            replenisher.setCreateTime(now);
            replenisher.setUpdateTime(now);
            toAdd.add(replenisher);
        }
        
        if (!toAdd.isEmpty()) {
            this.saveBatch(toAdd);
        }
        
        log.info("批量添加补货员完成: shopId={}, 总数={}, 成功={}", shopId, adminIds.size(), toAdd.size());
        return toAdd.size();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> removeReplenisher(Long shopId, Long adminId) {
        LambdaQueryWrapper<ShopReplenisher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShopReplenisher::getShopId, shopId)
                .eq(ShopReplenisher::getAdminId, adminId);

        boolean success = this.remove(wrapper);
        return success ? Result.success("移除成功") : Result.error(500, "移除失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchRemoveReplenishers(Long shopId, List<Long> adminIds) {
        if (adminIds == null || adminIds.isEmpty()) {
            return 0;
        }

        LambdaQueryWrapper<ShopReplenisher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShopReplenisher::getShopId, shopId)
                .in(ShopReplenisher::getAdminId, adminIds);

        long count = this.count(wrapper);
        this.remove(wrapper);
        
        log.info("批量移除补货员完成: shopId={}, 总数={}, 成功={}", shopId, adminIds.size(), count);
        return (int) count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateStatus(Long id, Integer status) {
        ShopReplenisher replenisher = this.getById(id);
        if (replenisher == null) {
            throw new BusinessException(404, "记录不存在");
        }

        replenisher.setStatus(status);
        replenisher.setUpdateTime(LocalDateTime.now());

        boolean success = this.updateById(replenisher);
        return success ? Result.success("状态更新成功") : Result.error(500, "状态更新失败");
    }

    @Override
    public boolean isReplenisher(Long shopId, Long adminId) {
        return shopReplenisherMapper.countByShopIdAndAdminId(shopId, adminId) > 0;
    }
}
