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 com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import shop.alien.entity.store.FitnessEquipmentInfo;
import shop.alien.mapper.FitnessEquipmentInfoMapper;
import shop.alien.store.service.FitnessEquipmentInfoService;

import java.util.Collections;
import java.util.List;

/**
 * 健身设备信息服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class FitnessEquipmentInfoServiceImpl extends ServiceImpl<FitnessEquipmentInfoMapper, FitnessEquipmentInfo>
        implements FitnessEquipmentInfoService {

    /**
     * 删除标志：未删除
     */
    private static final int DELETE_FLAG_NOT_DELETED = 0;

    /**
     * 状态：启用
     */
    private static final int STATUS_ENABLED = 1;

    /**
     * 状态：禁用
     */
    private static final int STATUS_DISABLED = 0;

    /**
     * 默认排序号
     */
    private static final int DEFAULT_SORT_ORDER = 0;

    /**
     * 默认页码
     */
    private static final int DEFAULT_PAGE = 1;

    /**
     * 默认页大小
     */
    private static final int DEFAULT_PAGE_SIZE = 10;

    /**
     * 健身设备信息Mapper
     */
    private final FitnessEquipmentInfoMapper fitnessEquipmentInfoMapper;

    /**
     * 分页查询健身设备信息列表
     *
     * @param pageNum       页码
     * @param pageSize      页大小
     * @param equipmentType 设备类型
     * @param equipmentName 设备名称（模糊查询）
     * @param status        状态
     * @return 健身设备信息分页列表
     */
    @Override
    public IPage<FitnessEquipmentInfo> getPageList(Integer pageNum, Integer pageSize, 
                                                   Integer equipmentType, String equipmentName, Integer status) {
        log.info("分页查询健身设备信息列表，pageNum={}, pageSize={}, equipmentType={}, equipmentName={}, status={}", 
                pageNum, pageSize, equipmentType, equipmentName, status);

        // 参数验证
        if (pageNum == null || pageNum < DEFAULT_PAGE) {
            log.warn("分页查询健身设备信息列表，页码参数无效，使用默认值：{}", pageNum);
            pageNum = DEFAULT_PAGE;
        }
        if (pageSize == null || pageSize < 1) {
            log.warn("分页查询健身设备信息列表，页大小参数无效，使用默认值：{}", pageSize);
            pageSize = DEFAULT_PAGE_SIZE;
        }

        try {
            Page<FitnessEquipmentInfo> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<FitnessEquipmentInfo> queryWrapper = new LambdaQueryWrapper<>();

            queryWrapper.eq(equipmentType != null, FitnessEquipmentInfo::getEquipmentType, equipmentType)
                    .like(StringUtils.hasText(equipmentName), FitnessEquipmentInfo::getEquipmentName, equipmentName)
                    .eq(status != null, FitnessEquipmentInfo::getStatus, status)
                    .eq(FitnessEquipmentInfo::getDeleteFlag, DELETE_FLAG_NOT_DELETED)
                    .orderByAsc(FitnessEquipmentInfo::getSortOrder)
                    .orderByDesc(FitnessEquipmentInfo::getCreatedTime);

            IPage<FitnessEquipmentInfo> result = fitnessEquipmentInfoMapper.selectPage(page, queryWrapper);
            log.info("分页查询健身设备信息列表成功，查询到{}条记录", result.getTotal());
            return result;
        } catch (Exception e) {
            log.error("分页查询健身设备信息列表异常，异常信息：{}", e.getMessage(), e);
            throw new RuntimeException("分页查询健身设备信息列表异常：" + e.getMessage(), e);
        }
    }

    /**
     * 查询健身设备信息列表
     *
     * @param equipmentType 设备类型
     * @param status        状态
     * @return 健身设备信息列表
     */
    @Override
    public List<FitnessEquipmentInfo> getList(Integer equipmentType, Integer status) {
        log.info("查询健身设备信息列表，equipmentType={}, status={}", equipmentType, status);

        try {
            LambdaQueryWrapper<FitnessEquipmentInfo> queryWrapper = new LambdaQueryWrapper<>();

            queryWrapper.eq(equipmentType != null, FitnessEquipmentInfo::getEquipmentType, equipmentType)
                    .eq(status != null, FitnessEquipmentInfo::getStatus, status)
                    .eq(FitnessEquipmentInfo::getDeleteFlag, DELETE_FLAG_NOT_DELETED)
                    .orderByAsc(FitnessEquipmentInfo::getSortOrder)
                    .orderByDesc(FitnessEquipmentInfo::getCreatedTime);

            List<FitnessEquipmentInfo> result = fitnessEquipmentInfoMapper.selectList(queryWrapper);
            log.info("查询健身设备信息列表成功，查询到{}条记录", result.size());
            return result;
        } catch (Exception e) {
            log.error("查询健身设备信息列表异常，异常信息：{}", e.getMessage(), e);
            return Collections.emptyList();
        }
    }

    /**
     * 根据设备类型查询设备列表（用于前端分类展示）
     *
     * @param equipmentType 设备类型
     * @return 健身设备信息列表
     */
    @Override
    public List<FitnessEquipmentInfo> getListByType(Integer equipmentType) {
        log.info("根据设备类型查询设备列表，equipmentType={}", equipmentType);

        if (equipmentType == null || equipmentType <= 0) {
            log.warn("根据设备类型查询设备列表失败，设备类型无效：{}", equipmentType);
            return Collections.emptyList();
        }

        try {
            LambdaQueryWrapper<FitnessEquipmentInfo> queryWrapper = new LambdaQueryWrapper<>();

            queryWrapper.eq(FitnessEquipmentInfo::getEquipmentType, equipmentType)
                    .eq(FitnessEquipmentInfo::getStatus, STATUS_ENABLED)
                    .eq(FitnessEquipmentInfo::getDeleteFlag, DELETE_FLAG_NOT_DELETED)
                    .orderByAsc(FitnessEquipmentInfo::getSortOrder)
                    .orderByDesc(FitnessEquipmentInfo::getCreatedTime);

            List<FitnessEquipmentInfo> result = fitnessEquipmentInfoMapper.selectList(queryWrapper);
            log.info("根据设备类型查询设备列表成功，equipmentType={}，查询到{}条记录", equipmentType, result.size());
            return result;
        } catch (Exception e) {
            log.error("根据设备类型查询设备列表异常，equipmentType={}，异常信息：{}", equipmentType, e.getMessage(), e);
            return Collections.emptyList();
        }
    }

    /**
     * 根据ID查询健身设备信息详情
     *
     * @param id 主键ID
     * @return 健身设备信息
     */
    @Override
    public FitnessEquipmentInfo getDetailById(Integer id) {
        log.info("根据ID查询健身设备信息详情，id={}", id);

        if (id == null || id <= 0) {
            log.warn("根据ID查询健身设备信息详情失败，ID无效：{}", id);
            return null;
        }

        try {
            FitnessEquipmentInfo result = fitnessEquipmentInfoMapper.selectById(id);
            if (result != null && result.getDeleteFlag() != null && result.getDeleteFlag() == DELETE_FLAG_NOT_DELETED) {
                log.info("根据ID查询健身设备信息详情成功，id={}", id);
                return result;
            } else {
                log.warn("根据ID查询健身设备信息详情失败，设备不存在或已删除，id={}", id);
                return null;
            }
        } catch (Exception e) {
            log.error("根据ID查询健身设备信息详情异常，id={}，异常信息：{}", id, e.getMessage(), e);
            return null;
        }
    }

    /**
     * 新增健身设备信息
     *
     * @param fitnessEquipmentInfo 健身设备信息对象
     * @return true表示新增成功，false表示新增失败
     */
    @Override
    public boolean saveEquipment(FitnessEquipmentInfo fitnessEquipmentInfo) {
        log.info("新增健身设备信息，请求参数：{}", fitnessEquipmentInfo);

        if (fitnessEquipmentInfo == null) {
            log.error("新增健身设备信息失败，设备信息对象为空");
            return false;
        }

        // 参数验证
        if (!StringUtils.hasText(fitnessEquipmentInfo.getEquipmentName())) {
            log.error("新增健身设备信息失败，设备名称为空");
            return false;
        }
        if (fitnessEquipmentInfo.getEquipmentType() == null || fitnessEquipmentInfo.getEquipmentType() <= 0) {
            log.error("新增健身设备信息失败，设备类型无效：{}", fitnessEquipmentInfo.getEquipmentType());
            return false;
        }

        try {
            // 设置默认值
            if (fitnessEquipmentInfo.getSortOrder() == null) {
                fitnessEquipmentInfo.setSortOrder(DEFAULT_SORT_ORDER);
            }
            if (fitnessEquipmentInfo.getStatus() == null) {
                fitnessEquipmentInfo.setStatus(STATUS_ENABLED);
            }
            fitnessEquipmentInfo.setDeleteFlag(DELETE_FLAG_NOT_DELETED);
            // createdTime和updatedTime由MyBatis-Plus自动填充

            int insertResult = fitnessEquipmentInfoMapper.insert(fitnessEquipmentInfo);
            if (insertResult > 0) {
                log.info("新增健身设备信息成功，id={}, equipmentName={}", 
                        fitnessEquipmentInfo.getId(), fitnessEquipmentInfo.getEquipmentName());
                return true;
            } else {
                log.warn("新增健身设备信息失败，插入记录数为0");
                return false;
            }
        } catch (Exception e) {
            log.error("新增健身设备信息异常，异常信息：{}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 修改健身设备信息
     *
     * @param fitnessEquipmentInfo 健身设备信息对象
     * @return true表示修改成功，false表示修改失败
     */
    @Override
    public boolean updateEquipment(FitnessEquipmentInfo fitnessEquipmentInfo) {
        log.info("修改健身设备信息，请求参数：{}", fitnessEquipmentInfo);

        if (fitnessEquipmentInfo == null || fitnessEquipmentInfo.getId() == null) {
            log.error("修改健身设备信息失败，设备信息对象为空或ID为空");
            return false;
        }

        // 参数验证
        if (fitnessEquipmentInfo.getId() <= 0) {
            log.error("修改健身设备信息失败，ID无效：{}", fitnessEquipmentInfo.getId());
            return false;
        }

        try {
            // 检查设备是否存在
            FitnessEquipmentInfo existing = fitnessEquipmentInfoMapper.selectById(fitnessEquipmentInfo.getId());
            if (existing == null || existing.getDeleteFlag() == null || existing.getDeleteFlag() != DELETE_FLAG_NOT_DELETED) {
                log.warn("修改健身设备信息失败，设备不存在或已删除，id={}", fitnessEquipmentInfo.getId());
                return false;
            }

            // updatedTime由MyBatis-Plus自动填充

            int updateResult = fitnessEquipmentInfoMapper.updateById(fitnessEquipmentInfo);
            if (updateResult > 0) {
                log.info("修改健身设备信息成功，id={}", fitnessEquipmentInfo.getId());
                return true;
            } else {
                log.warn("修改健身设备信息失败，更新记录数为0，id={}", fitnessEquipmentInfo.getId());
                return false;
            }
        } catch (Exception e) {
            log.error("修改健身设备信息异常，id={}，异常信息：{}", fitnessEquipmentInfo.getId(), e.getMessage(), e);
            return false;
        }
    }

    /**
     * 删除健身设备信息（逻辑删除）
     *
     * @param id 主键ID
     * @return true表示删除成功，false表示删除失败
     */
    @Override
    public boolean deleteEquipment(Integer id) {
        log.info("删除健身设备信息，id={}", id);

        if (id == null || id <= 0) {
            log.error("删除健身设备信息失败，ID无效：{}", id);
            return false;
        }

        try {
            // 检查设备是否存在
            FitnessEquipmentInfo existing = fitnessEquipmentInfoMapper.selectById(id);
            if (existing == null || existing.getDeleteFlag() == null || existing.getDeleteFlag() != DELETE_FLAG_NOT_DELETED) {
                log.warn("删除健身设备信息失败，设备不存在或已删除，id={}", id);
                return false;
            }

            // 逻辑删除
            FitnessEquipmentInfo updateEntity = new FitnessEquipmentInfo();
            updateEntity.setId(id);
            updateEntity.setDeleteFlag(1);
            // updatedTime由MyBatis-Plus自动填充

            int updateResult = fitnessEquipmentInfoMapper.updateById(updateEntity);
            if (updateResult > 0) {
                log.info("删除健身设备信息成功，id={}", id);
                return true;
            } else {
                log.warn("删除健身设备信息失败，更新记录数为0，id={}", id);
                return false;
            }
        } catch (Exception e) {
            log.error("删除健身设备信息异常，id={}，异常信息：{}", id, e.getMessage(), e);
            return false;
        }
    }

    /**
     * 启用/禁用健身设备信息
     *
     * @param id     主键ID
     * @param status 状态(0:禁用, 1:启用)
     * @return true表示操作成功，false表示操作失败
     */
    @Override
    public boolean updateStatus(Integer id, Integer status) {
        log.info("更新健身设备信息状态，id={}, status={}", id, status);

        if (id == null || id <= 0) {
            log.error("更新健身设备信息状态失败，ID无效：{}", id);
            return false;
        }
        if (status == null || (status != STATUS_ENABLED && status != STATUS_DISABLED)) {
            log.error("更新健身设备信息状态失败，状态值无效：{}", status);
            return false;
        }

        try {
            // 检查设备是否存在
            FitnessEquipmentInfo existing = fitnessEquipmentInfoMapper.selectById(id);
            if (existing == null || existing.getDeleteFlag() == null || existing.getDeleteFlag() != DELETE_FLAG_NOT_DELETED) {
                log.warn("更新健身设备信息状态失败，设备不存在或已删除，id={}", id);
                return false;
            }

            FitnessEquipmentInfo updateEntity = new FitnessEquipmentInfo();
            updateEntity.setId(id);
            updateEntity.setStatus(status);
            // updatedTime由MyBatis-Plus自动填充

            int updateResult = fitnessEquipmentInfoMapper.updateById(updateEntity);
            if (updateResult > 0) {
                log.info("更新健身设备信息状态成功，id={}, status={}", id, status);
                return true;
            } else {
                log.warn("更新健身设备信息状态失败，更新记录数为0，id={}", id);
                return false;
            }
        } catch (Exception e) {
            log.error("更新健身设备信息状态异常，id={}, status={}，异常信息：{}", id, status, e.getMessage(), e);
            return false;
        }
    }
}

