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.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import shop.alien.entity.store.SportsEquipmentFacility;
import shop.alien.entity.store.StoreImg;
import shop.alien.entity.store.vo.SportsEquipmentFacilityCategoryVo;
import shop.alien.entity.store.vo.SportsEquipmentFacilityVo;
import shop.alien.mapper.SportsEquipmentFacilityMapper;
import shop.alien.mapper.StoreImgMapper;
import shop.alien.store.service.SportsEquipmentFacilityService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 运动器材设施服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class SportsEquipmentFacilityServiceImpl extends ServiceImpl<SportsEquipmentFacilityMapper, SportsEquipmentFacility>
        implements SportsEquipmentFacilityService {

    private final SportsEquipmentFacilityMapper facilityMapper;
    private final StoreImgMapper storeImgMapper;

    /**
     * 运动器材设施图片类型
     */
    private static final Integer IMG_TYPE_SPORTS_EQUIPMENT = 28;

    /**
     * 设施分类名称映射
     */
    private static final String[] FACILITY_CATEGORY_NAMES = {"", "有氧区", "力量区", "单功能机械区"};

    @Override
    public IPage<SportsEquipmentFacilityVo> getPageList(Integer pageNum, Integer pageSize, Integer storeId, Integer facilityCategory) {
        Page<SportsEquipmentFacility> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SportsEquipmentFacility> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SportsEquipmentFacility::getStoreId, storeId);
        if (facilityCategory != null) {
            queryWrapper.eq(SportsEquipmentFacility::getFacilityCategory, facilityCategory);
        }
        queryWrapper.orderByDesc(SportsEquipmentFacility::getCreatedTime);
        IPage<SportsEquipmentFacility> facilityPage = facilityMapper.selectPage(page, queryWrapper);
        return facilityPage.convert(this::convertToVo);
    }

    @Override
    public List<SportsEquipmentFacilityVo> getList(Integer storeId, Integer facilityCategory) {
        LambdaQueryWrapper<SportsEquipmentFacility> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SportsEquipmentFacility::getStoreId, storeId);
        if (facilityCategory != null) {
            queryWrapper.eq(SportsEquipmentFacility::getFacilityCategory, facilityCategory);
        }
        queryWrapper.orderByDesc(SportsEquipmentFacility::getCreatedTime);
        List<SportsEquipmentFacility> facilityList = facilityMapper.selectList(queryWrapper);
        return facilityList.stream().map(this::convertToVo).collect(Collectors.toList());
    }

    @Override
    public SportsEquipmentFacilityVo getDetail(Integer id) {
        SportsEquipmentFacility facility = facilityMapper.selectById(id);
        if (facility == null) {
            return null;
        }
        return convertToVo(facility);
    }

    @Override
    public SportsEquipmentFacilityVo getStoreDetail(Integer id) {
        SportsEquipmentFacility facility = facilityMapper.selectById(id);
        if (facility == null) {
            return null;
        }
        return convertToVo(facility);
    }

    @Override
    public boolean saveFacility(SportsEquipmentFacility facility, List<String> imageList) {
        // 校验图片数量（最多20张）
        if (!CollectionUtils.isEmpty(imageList) && imageList.size() > 20) {
            throw new RuntimeException("实景图片最多上传20张");
        }
        // 保存设施信息
        boolean result = this.save(facility);
        if (result && !CollectionUtils.isEmpty(imageList) && facility.getFacilityCategory() != null) {
            // 删除该分类下的旧图片（如果存在）
            LambdaQueryWrapper<StoreImg> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.eq(StoreImg::getStoreId, facility.getStoreId())
                    .eq(StoreImg::getBusinessId, facility.getFacilityCategory())
                    .eq(StoreImg::getImgType, IMG_TYPE_SPORTS_EQUIPMENT);
            storeImgMapper.delete(deleteWrapper);
            // 保存新图片，business_id存储facility_category
            saveImages(facility.getFacilityCategory(), facility.getStoreId(), imageList);
        }
        return result;
    }

    @Override
    public boolean updateFacility(SportsEquipmentFacility facility, List<String> imageList) {
        // 校验图片数量（最多20张）
        if (!CollectionUtils.isEmpty(imageList) && imageList.size() > 20) {
            throw new RuntimeException("实景图片最多上传20张");
        }
        // 更新设施信息
        boolean result = this.updateById(facility);
        if (result && !CollectionUtils.isEmpty(imageList) && facility.getFacilityCategory() != null) {
            // 删除该分类下的旧图片
            LambdaQueryWrapper<StoreImg> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.eq(StoreImg::getStoreId, facility.getStoreId())
                    .eq(StoreImg::getBusinessId, facility.getFacilityCategory())
                    .eq(StoreImg::getImgType, IMG_TYPE_SPORTS_EQUIPMENT);
            storeImgMapper.delete(deleteWrapper);
            // 保存新图片，business_id存储facility_category
            saveImages(facility.getFacilityCategory(), facility.getStoreId(), imageList);
        }
        return result;
    }

    @Override
    public boolean deleteFacility(Integer id) {
        // 注意：图片和设施没有关系，只和facility_category有关系，所以删除设施时不删除图片
        // 删除设施
        return this.removeById(id);
    }

    @Override
    public List<SportsEquipmentFacilityCategoryVo> getCategorySummary(Integer storeId) {
        List<SportsEquipmentFacilityCategoryVo> result = new ArrayList<>();
        
        // 遍历所有分类（1:有氧区, 2:力量区, 3:单功能机械区）
        for (int category = 1; category < FACILITY_CATEGORY_NAMES.length; category++) {
            SportsEquipmentFacilityCategoryVo categoryVo = new SportsEquipmentFacilityCategoryVo();
            categoryVo.setFacilityCategory(category);
            categoryVo.setFacilityCategoryName(FACILITY_CATEGORY_NAMES[category]);
            
            // 查询该分类下的设备列表（不分页）
            LambdaQueryWrapper<SportsEquipmentFacility> facilityWrapper = new LambdaQueryWrapper<>();
            facilityWrapper.eq(SportsEquipmentFacility::getStoreId, storeId)
                    .eq(SportsEquipmentFacility::getFacilityCategory, category);
            facilityWrapper.orderByDesc(SportsEquipmentFacility::getCreatedTime);
            List<SportsEquipmentFacility> facilityList = facilityMapper.selectList(facilityWrapper);
            
            // 设置设备数量
            categoryVo.setFacilityCount(facilityList != null ? facilityList.size() : 0);
            
            // 转换为VO列表（不包含图片，避免重复查询）
            List<SportsEquipmentFacilityVo> facilityVoList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(facilityList)) {
                for (SportsEquipmentFacility facility : facilityList) {
                    SportsEquipmentFacilityVo vo = new SportsEquipmentFacilityVo();
                    BeanUtils.copyProperties(facility, vo);
                    // 设置分类名称
                    vo.setFacilityCategoryName(FACILITY_CATEGORY_NAMES[category]);
                    // 设置显示状态文本
                    if (facility.getDisplayInStoreDetail() != null) {
                        vo.setDisplayInStoreDetailText(facility.getDisplayInStoreDetail() == 1 ? "显示" : "隐藏");
                    }
                    facilityVoList.add(vo);
                }
            }
            categoryVo.setFacilityList(facilityVoList);
            
            // 查询该分类下的图片列表
            LambdaQueryWrapper<StoreImg> imageWrapper = new LambdaQueryWrapper<>();
            imageWrapper.eq(StoreImg::getStoreId, storeId)
                    .eq(StoreImg::getBusinessId, category)
                    .eq(StoreImg::getImgType, IMG_TYPE_SPORTS_EQUIPMENT);
            imageWrapper.orderByAsc(StoreImg::getImgSort);
            List<StoreImg> imageList = storeImgMapper.selectList(imageWrapper);
            if (!CollectionUtils.isEmpty(imageList)) {
                categoryVo.setImageList(imageList.stream().map(StoreImg::getImgUrl)
                        .collect(Collectors.toList()));
            } else {
                categoryVo.setImageList(new ArrayList<>());
            }
            
            result.add(categoryVo);
        }
        
        return result;
    }

    /**
     * 保存图片
     * 
     * @param facilityCategory 设施分类
     * @param storeId 门店ID
     * @param imageList 图片列表
     */
    private void saveImages(Integer facilityCategory, Integer storeId, List<String> imageList) {
        for (int i = 0; i < imageList.size(); i++) {
            StoreImg storeImg = new StoreImg();
            storeImg.setStoreId(storeId);
            storeImg.setImgType(IMG_TYPE_SPORTS_EQUIPMENT);
            storeImg.setBusinessId(facilityCategory); // business_id存储facility_category
            storeImg.setImgUrl(imageList.get(i));
            storeImg.setImgSort(i + 1);
            storeImg.setImgDescription("运动器材设施实景图片");
            storeImgMapper.insert(storeImg);
        }
    }

    /**
     * 转换为VO对象
     */
    private SportsEquipmentFacilityVo convertToVo(SportsEquipmentFacility facility) {
        SportsEquipmentFacilityVo vo = new SportsEquipmentFacilityVo();
        BeanUtils.copyProperties(facility, vo);
        // 设置分类名称
        if (facility.getFacilityCategory() != null && facility.getFacilityCategory() > 0
                && facility.getFacilityCategory() < FACILITY_CATEGORY_NAMES.length) {
            vo.setFacilityCategoryName(FACILITY_CATEGORY_NAMES[facility.getFacilityCategory()]);
        }
        // 设置显示状态文本
        if (facility.getDisplayInStoreDetail() != null) {
            vo.setDisplayInStoreDetailText(facility.getDisplayInStoreDetail() == 1 ? "显示" : "隐藏");
        }
        // 查询图片列表，根据store_id和facility_category查询
        LambdaQueryWrapper<StoreImg> imageWrapper = new LambdaQueryWrapper<>();
        imageWrapper.eq(StoreImg::getStoreId, facility.getStoreId())
                .eq(StoreImg::getBusinessId, facility.getFacilityCategory())
                .eq(StoreImg::getImgType, IMG_TYPE_SPORTS_EQUIPMENT);
        imageWrapper.orderByAsc(StoreImg::getImgSort);
        List<StoreImg> imageList = storeImgMapper.selectList(imageWrapper);
        if (!CollectionUtils.isEmpty(imageList)) {
            vo.setImageList(imageList.stream().map(StoreImg::getImgUrl)
                    .collect(Collectors.toList()));
        }
        return vo;
    }


    @Override
    public List<SportsEquipmentFacilityCategoryVo> getstoreCategorySummary(Integer storeId) {
        List<SportsEquipmentFacilityCategoryVo> result = new ArrayList<>();

        // 遍历所有分类（1:有氧区, 2:力量区, 3:单功能机械区）
        for (int category = 1; category < FACILITY_CATEGORY_NAMES.length; category++) {
            SportsEquipmentFacilityCategoryVo categoryVo = new SportsEquipmentFacilityCategoryVo();
            categoryVo.setFacilityCategory(category);
            categoryVo.setFacilityCategoryName(FACILITY_CATEGORY_NAMES[category]);

            // 查询该分类下的设备列表（不分页）
            LambdaQueryWrapper<SportsEquipmentFacility> facilityWrapper = new LambdaQueryWrapper<>();
            facilityWrapper.eq(SportsEquipmentFacility::getStoreId, storeId)
                    .eq(SportsEquipmentFacility::getFacilityCategory, category);
            facilityWrapper.orderByDesc(SportsEquipmentFacility::getCreatedTime);
            List<SportsEquipmentFacility> facilityList = facilityMapper.selectList(facilityWrapper);

            // 设置设备数量
            categoryVo.setFacilityCount(facilityList != null ? facilityList.size() : 0);

            // 转换为VO列表（不包含图片，避免重复查询）
            List<SportsEquipmentFacilityVo> facilityVoList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(facilityList)) {
                for (SportsEquipmentFacility facility : facilityList) {
                    SportsEquipmentFacilityVo vo = new SportsEquipmentFacilityVo();
                    BeanUtils.copyProperties(facility, vo);
                    // 设置分类名称
                    vo.setFacilityCategoryName(FACILITY_CATEGORY_NAMES[category]);
                    // 设置显示状态文本
                    if (facility.getDisplayInStoreDetail() != null) {
                        vo.setDisplayInStoreDetailText(facility.getDisplayInStoreDetail() == 1 ? "显示" : "隐藏");
                    }
                    facilityVoList.add(vo);
                }
            }
            categoryVo.setFacilityList(facilityVoList);

            // 查询该分类下的图片列表
            LambdaQueryWrapper<StoreImg> imageWrapper = new LambdaQueryWrapper<>();
            imageWrapper.eq(StoreImg::getStoreId, storeId)
                    .eq(StoreImg::getBusinessId, category)
                    .eq(StoreImg::getImgType, IMG_TYPE_SPORTS_EQUIPMENT);
            imageWrapper.orderByAsc(StoreImg::getImgSort);
            List<StoreImg> imageList = storeImgMapper.selectList(imageWrapper);
            if (!CollectionUtils.isEmpty(imageList)) {
                categoryVo.setImageList(imageList.stream().map(StoreImg::getImgUrl)
                        .collect(Collectors.toList()));
            } else {
                categoryVo.setImageList(new ArrayList<>());
            }

            result.add(categoryVo);
        }

        return result;
    }
}

