package com.liquidnet.client.admin.zhengzai.kylin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liquidnet.client.admin.zhengzai.kylin.utils.DataUtils;
import com.liquidnet.client.admin.zhengzai.kylin.utils.SweetArtistCacheUtils;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.kylin.dao.KylinArtistDao;
import com.liquidnet.service.kylin.dao.KylinArtistPerformanceDao;
import com.liquidnet.service.kylin.dto.param.ArtistParam;
import com.liquidnet.service.kylin.dto.param.ArtistSearchParam;
import com.liquidnet.service.kylin.dto.vo.ArtistGoodsOptionVo;
import com.liquidnet.service.kylin.dto.vo.ArtistVo;
import com.liquidnet.service.kylin.entity.KylinArtist;
import com.liquidnet.service.goblin.entity.GoblinGoods;
import com.liquidnet.service.goblin.mapper.GoblinGoodsMapper;
import com.liquidnet.service.kylin.entity.KylinArtistAlbum;
import com.liquidnet.service.kylin.entity.KylinArtistProduct;
import com.liquidnet.service.kylin.mapper.KylinArtistProductMapper;
import com.liquidnet.service.kylin.mapper.KylinArtistAlbumMapper;
import com.liquidnet.service.kylin.mapper.KylinArtistMapper;
import com.liquidnet.service.kylin.mapper.KylinArtistPerformanceMapper;
import com.liquidnet.service.kylin.service.admin.IKylinArtistOperationLogService;
import com.liquidnet.service.kylin.service.admin.IKylinArtistService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 艺人管理 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2026-02-04
 */
@Slf4j
@Service
public class KylinArtistServiceImpl extends ServiceImpl<KylinArtistMapper, KylinArtist> implements IKylinArtistService {

    @Autowired
    private KylinArtistMapper artistMapper;

    @Autowired
    private KylinArtistAlbumMapper artistAlbumMapper;

    @Autowired
    private KylinArtistProductMapper artistProductMapper;

    @Autowired
    private KylinArtistPerformanceMapper artistPerformanceMapper;

    @Autowired
    private IKylinArtistOperationLogService operationLogService;

    @Autowired
    private DataUtils dataUtils;

    @Autowired
    private SweetArtistCacheUtils sweetArtistCacheUtils;

    @Autowired
    private GoblinGoodsMapper goblinGoodsMapper;

    /**
     * 创建艺人
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean create(ArtistParam param) {
        try {
            // 校验艺人名称是否已存在
            KylinArtist existArtist = artistMapper.selectByArtistName(param.getArtistName());
            if (existArtist != null) {
                log.warn("艺人名称已存在: {}", param.getArtistName());
                return false;
            }

            String artistId = IDGenerator.nextSnowId();
            LocalDateTime createdAt = LocalDateTime.now();

            // 保存艺人基本信息
            KylinArtist kylinArtist = param.getFields(artistId, createdAt);
            artistMapper.insert(kylinArtist);

            // 保存相册图片
            if (param.getAlbumImages() != null && !param.getAlbumImages().isEmpty()) {
                saveAlbumImages(artistId, param.getAlbumImages());
            }

            // 记录操作日志
            operationLogService.recordLog(artistId, 1, buildCreateLogContent(param));

            return true;
        } catch (Exception e) {
            log.error("创建艺人失败", e);
            throw new RuntimeException("创建艺人失败", e);
        }
    }

    /**
     * 修改艺人
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(ArtistParam param) {
        try {
            String artistId = param.getArtistId();

            // 获取原始数据用于对比
            KylinArtist oldArtist = artistMapper.selectOne(
                    new UpdateWrapper<KylinArtist>().eq("artist_id", artistId).eq("status", 1)
            );

            if (oldArtist == null) {
                log.warn("艺人不存在: {}", artistId);
                return false;
            }

            // 校验艺人名称是否已被其他艺人使用
            KylinArtist existArtist = artistMapper.selectByArtistName(param.getArtistName());
            if (existArtist != null && !existArtist.getArtistId().equals(artistId)) {
                log.warn("艺人名称已被其他艺人使用: {}", param.getArtistName());
                return false;
            }

            LocalDateTime updatedAt = LocalDateTime.now();

            // 更新艺人基本信息
            KylinArtist params = param.getFields(null, null);
            params.setUpdatedAt(updatedAt);
            artistMapper.update(params, new UpdateWrapper<KylinArtist>().eq("artist_id", artistId));

            // 删除旧的相册图片（逻辑删除）
            artistAlbumMapper.deleteByArtistId(artistId);

            // 保存新的相册图片
            if (param.getAlbumImages() != null && !param.getAlbumImages().isEmpty()) {
                saveAlbumImages(artistId, param.getAlbumImages());
            }

            // 记录操作日志（对比变更）
            String logContent = buildUpdateLogContent(oldArtist, param);
            if (logContent != null && !logContent.isEmpty()) {
                operationLogService.recordLog(artistId, 2, logContent);
            }

            // 根据艺人ID查询所有关联的演出，然后删除缓存中对应的演出阵容
            List<String> performanceIdList = artistPerformanceMapper.selectPerformanceIdsByArtistIds(Collections.singletonList(artistId));
            if (!performanceIdList.isEmpty()) {
                for (String p : performanceIdList) {
                    dataUtils.delPerformanceArtists(p);
                }
            }
            sweetArtistCacheUtils.invalidateByArtistId(artistId);
            dataUtils.delArtistDetailAndAlbumCache(artistId);
            return true;
        } catch (Exception e) {
            log.error("修改艺人失败", e);
            throw new RuntimeException("修改艺人失败", e);
        }
    }

    /**
     * 艺人详情
     */
    public ArtistVo detail(String artistId) {
        KylinArtist data = artistMapper.selectOne(
                new UpdateWrapper<KylinArtist>().eq("artist_id", artistId).eq("status", 1)
        );

        ArtistVo artistVo = new ArtistVo();
        if (data != null) {
            BeanUtils.copyProperties(data, artistVo);

            // 设置艺人类型名称
            if (data.getArtistType() != null) {
                String typeName = "";
                switch (data.getArtistType()) {
                    case 1:
                        typeName = "音乐人";
                        break;
                    case 2:
                        typeName = "艺术家";
                        break;
                    case 3:
                        typeName = "厂牌";
                        break;
                    case 4:
                        typeName = "品牌方";
                        break;
                    default:
                        typeName = "未知";
                        break;
                }
                artistVo.setArtistTypeName(typeName);
            }

            // 查询相册图片
            List<KylinArtistAlbum> albumList = artistAlbumMapper.selectByArtistId(artistId);
            if (albumList != null && !albumList.isEmpty()) {
                List<String> imageUrls = albumList.stream()
                        .map(KylinArtistAlbum::getImageUrl)
                        .collect(Collectors.toList());
                artistVo.setAlbumImages(imageUrls);
            }

            // 格式化时间显示
            if (data.getCreatedAt() != null) {
                artistVo.setCreatedAt(DateUtil.Formatter.yyyyMMddHHmmss.format(data.getCreatedAt()));
            }
            if (data.getUpdatedAt() != null) {
                artistVo.setUpdatedAt(DateUtil.Formatter.yyyyMMddHHmmss.format(data.getUpdatedAt()));
            }

            // 设置关联演出
            List<KylinArtistPerformanceDao> performanceList = artistPerformanceMapper.selectPerformanceDaoByArtistId(artistId);
            if (performanceList != null && !performanceList.isEmpty()) {
                List<ArtistVo.PerformanceVo> performanceVoList = performanceList.stream()
                        .map(performance -> {
                            ArtistVo.PerformanceVo vo = new ArtistVo.PerformanceVo();
                            vo.setPerformanceId(performance.getPerformanceId());
                            vo.setTitle(performance.getTitle());
                            vo.setTimeStart(performance.getTimeStart());
                            vo.setTimesId(performance.getTimesId());
                            vo.setTimeTitle(performance.getTimeTitle());
                            return vo;
                        })
                        .collect(Collectors.toList());
                artistVo.setPerformanceVoList(performanceVoList);
            } else {
                artistVo.setPerformanceVoList(Collections.emptyList());
            }

        } else {
            log.error("[detail] query artist is null, artistId: {}", artistId);
            return null;
        }

        return artistVo;
    }

    /**
     * 艺人列表
     */
    public PageInfo<KylinArtistDao> artistList(ArtistSearchParam param) {
        PageInfo<KylinArtistDao> pageInfoTmp = null;
        try {
            PageHelper.startPage(param.getPageNum(), param.getPageSize());

            Map<String, Object> paramMap = BeanUtil.convertBeanToMap(param);
            log.info("艺人列表查询参数: {}", paramMap);

            List<KylinArtistDao> list = artistMapper.searchArtistList(paramMap);

            pageInfoTmp = new PageInfo<>(list);
        } catch (Exception e) {
            log.error("获取艺人列表失败", e);
            return new PageInfo<>();
        }
        return pageInfoTmp;
    }

    /**
     * 删除艺人（逻辑删除）
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(List<String> artistIds) {
        try {
            LocalDateTime updatedAt = LocalDateTime.now();

            // 删除艺人基本信息
            KylinArtist kylinArtist = new KylinArtist();
            kylinArtist.setUpdatedAt(updatedAt);
            kylinArtist.setStatus(0);

            artistMapper.update(
                    kylinArtist,
                    new UpdateWrapper<KylinArtist>().in("artist_id", artistIds)
            );

            // 逻辑删除艺人，保留相册/商品/演出关联等历史数据；关联与展示内容未变，缓存自然过期即可
            for (String artistId : artistIds) {
                KylinArtist artist = artistMapper.selectOne(
                        new UpdateWrapper<KylinArtist>().eq("artist_id", artistId)
                );

                String logContent = "删除艺人：" + (artist != null ? artist.getArtistName() + "（ID：" + artistId + "）" : artistId);
                operationLogService.recordLog(artistId, 3, logContent);
            }

            return true;
        } catch (Exception e) {
            log.error("删除艺人失败", e);
            throw new RuntimeException("删除艺人失败", e);
        }
    }

    @Override
    public List<ArtistVo.ProductVo> listArtistProducts(String artistId) {
        KylinArtist artist = artistMapper.selectOne(
                new UpdateWrapper<KylinArtist>().eq("artist_id", artistId).eq("status", 1)
        );
        if (artist == null) {
            return Collections.emptyList();
        }
        List<KylinArtistProduct> productRelations = artistProductMapper.selectByArtistId(artistId);
        if (productRelations == null || productRelations.isEmpty()) {
            return Collections.emptyList();
        }
        List<ArtistVo.ProductVo> productVoList = new ArrayList<>();
        for (KylinArtistProduct relation : productRelations) {
            ArtistVo.ProductVo productVo = buildProductVo(relation.getSpuId());
            if (productVo != null) {
                productVoList.add(productVo);
            }
        }
        return productVoList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveArtistProducts(String artistId, List<String> spuIds) {
        KylinArtist artist = artistMapper.selectOne(
                new UpdateWrapper<KylinArtist>().eq("artist_id", artistId).eq("status", 1)
        );
        if (artist == null) {
            return false;
        }
        LinkedHashSet<String> uniqueSpuIds = new LinkedHashSet<>();
        if (spuIds != null) {
            for (String spuId : spuIds) {
                if (spuId != null && !spuId.trim().isEmpty()) {
                    uniqueSpuIds.add(spuId.trim());
                }
            }
        }
        artistProductMapper.deleteByArtistId(artistId);
        if (!uniqueSpuIds.isEmpty()) {
            saveProductRelations(artistId, new ArrayList<>(uniqueSpuIds));
        }
        operationLogService.recordLog(artistId, 2, "更新了艺人关联商品");
        dataUtils.delArtistProductsCache(artistId);
        return true;
    }

    @Override
    public List<ArtistGoodsOptionVo> searchGoods(String keyword, String artistId, List<String> excludeSpuIds) {
        Set<String> excludeSet = buildExcludeSpuIds(artistId, excludeSpuIds);
        boolean hasKeyword = keyword != null && !keyword.trim().isEmpty();
        LambdaQueryWrapper<GoblinGoods> query = Wrappers.lambdaQuery(GoblinGoods.class)
                .ne(GoblinGoods::getDelFlg, "1")
                .orderByDesc(GoblinGoods::getMid);
        if (!excludeSet.isEmpty()) {
            query.notIn(GoblinGoods::getSpuId, excludeSet);
        }
        if (hasKeyword) {
            query.like(GoblinGoods::getName, keyword.trim());
        } else {
            query.last("LIMIT 20");
        }
        List<GoblinGoods> goodsList = goblinGoodsMapper.selectList(query);
        List<ArtistGoodsOptionVo> result = new ArrayList<>();
        for (GoblinGoods goods : goodsList) {
            result.add(buildGoodsOption(goods));
        }
        return result;
    }

    private Set<String> buildExcludeSpuIds(String artistId, List<String> excludeSpuIds) {
        Set<String> excludeSet = new HashSet<>();
        if (artistId != null && !artistId.isEmpty()) {
            List<KylinArtistProduct> relations = artistProductMapper.selectByArtistId(artistId);
            if (relations != null) {
                for (KylinArtistProduct relation : relations) {
                    if (relation.getSpuId() != null && !relation.getSpuId().isEmpty()) {
                        excludeSet.add(relation.getSpuId());
                    }
                }
            }
        }
        if (excludeSpuIds != null) {
            for (String spuId : excludeSpuIds) {
                if (spuId != null && !spuId.trim().isEmpty()) {
                    excludeSet.add(spuId.trim());
                }
            }
        }
        return excludeSet;
    }

    private ArtistGoodsOptionVo buildGoodsOption(GoblinGoods goods) {
        ArtistGoodsOptionVo vo = new ArtistGoodsOptionVo();
        vo.setSpuId(goods.getSpuId());
        vo.setSpuNo(goods.getSpuNo());
        vo.setName(goods.getName());
        vo.setCoverPic(goods.getCoverPic());
        vo.setShelfStatusLabel(resolveShelfStatusLabel(goods.getShelvesStatus(), goods.getDelFlg()));
        vo.setSelectable(!"1".equals(goods.getDelFlg()));
        return vo;
    }

    private String resolveShelfStatusLabel(String shelvesStatus, String delFlg) {
        if (!"0".equals(delFlg)) {
            return "已删除";
        }
        if ("3".equals(shelvesStatus)) {
            return "已上架";
        }
        if ("0".equals(shelvesStatus)) {
            return "待上架";
        }
        if ("1".equals(shelvesStatus)) {
            return "未上架";
        }
        return "不可售";
    }

    /**
     * 检查艺人名称是否存在
     */
    public Boolean checkArtistNameExists(String artistName, String artistId) {
        KylinArtist existArtist = artistMapper.selectByArtistName(artistName);
        if (existArtist == null) {
            return false;
        }
        // 如果是编辑操作，排除自己
        if (artistId != null && existArtist.getArtistId().equals(artistId)) {
            return false;
        }
        return true;
    }

    /**
     * 保存相册图片
     */
    private void saveAlbumImages(String artistId, List<String> imageUrls) {
        LocalDateTime now = LocalDateTime.now();
        int sort = imageUrls.size();

        for (String imageUrl : imageUrls) {
            KylinArtistAlbum album = new KylinArtistAlbum();
            album.setAlbumId(IDGenerator.nextSnowId());
            album.setArtistId(artistId);
            album.setImageUrl(imageUrl);
            album.setSort(sort--);
            album.setStatus(1);
            album.setCreatedAt(now);
            album.setUpdatedAt(now);

            artistAlbumMapper.insert(album);
        }
    }

    private void saveProductRelations(String artistId, List<String> spuIds) {
        LocalDateTime now = LocalDateTime.now();
        int sort = spuIds.size();
        for (String spuId : spuIds) {
            if (spuId == null || spuId.trim().isEmpty()) {
                continue;
            }
            KylinArtistProduct product = KylinArtistProduct.getNew();
            product.setRelationId(IDGenerator.nextSnowId());
            product.setArtistId(artistId);
            product.setSpuId(spuId.trim());
            product.setSort(sort--);
            product.setStatus(1);
            product.setCreatedAt(now);
            product.setUpdatedAt(now);
            artistProductMapper.insert(product);
        }
    }

    private ArtistVo.ProductVo buildProductVo(String spuId) {
        GoblinGoods goods = goblinGoodsMapper.selectOne(
                Wrappers.lambdaQuery(GoblinGoods.class)
                        .eq(GoblinGoods::getSpuId, spuId)
                        .ne(GoblinGoods::getDelFlg, "1")
        );
        if (goods == null) {
            ArtistVo.ProductVo vo = new ArtistVo.ProductVo();
            vo.setSpuId(spuId);
            vo.setProductCode(spuId);
            vo.setProductName("商品不存在");
            vo.setStatus(0);
            return vo;
        }
        ArtistVo.ProductVo vo = new ArtistVo.ProductVo();
        vo.setSpuId(goods.getSpuId());
        vo.setProductCode(goods.getSpuNo() != null ? goods.getSpuNo() : goods.getSpuId());
        vo.setProductName(goods.getName());
        vo.setImageUrl(goods.getCoverPic());
        vo.setCategory("--");
        vo.setStatus("3".equals(goods.getShelvesStatus()) ? 1 : 0);
        return vo;
    }

    /**
     * 构建新增操作的日志内容
     */
    private String buildCreateLogContent(ArtistParam param) {
        StringBuilder content = new StringBuilder();
        content.append("新增艺人: [").append(param.getArtistName()).append("];");
        content.append("类型: [").append(getArtistTypeName(param.getArtistType())).append("];");

//        if (param.getIntroduction() != null && !param.getIntroduction().isEmpty()) {
//            String intro = param.getIntroduction();
//            content.append("介绍: ").append(intro.length() > 50 ? intro.substring(0, 50) + "..." : intro);
//        }

        return content.toString();
    }

    /**
     * 构建修改操作的日志内容（逐字段对比）
     */
    private String buildUpdateLogContent(KylinArtist oldArtist, ArtistParam newParam) {
        StringBuilder content = new StringBuilder();
        boolean hasChange = false;

        // 对比艺人名称
        if (!oldArtist.getArtistName().equals(newParam.getArtistName())) {
            content.append("名称从[").append(oldArtist.getArtistName()).append("]")
                    .append("改为[").append(newParam.getArtistName()).append("];");
            hasChange = true;
        }

        // 对比艺人类型
        if (!oldArtist.getArtistType().equals(newParam.getArtistType())) {
            content.append("类型从[").append(getArtistTypeName(oldArtist.getArtistType()))
                    .append("]改为[").append(getArtistTypeName(newParam.getArtistType())).append("];");
            hasChange = true;
        }

        // 对比艺人头像
        String oldAvatar = oldArtist.getAvatarUrl() != null ? oldArtist.getAvatarUrl() : "";
        String newAvatar = newParam.getAvatarUrl() != null ? newParam.getAvatarUrl() : "";
        if (!oldAvatar.equals(newAvatar)) {
            content.append("更新了艺人头像;");
            hasChange = true;
        }

        // 对比艺人简介
        String oldIntro = oldArtist.getIntroduction() != null ? oldArtist.getIntroduction() : "";
        String newIntro = newParam.getIntroduction() != null ? newParam.getIntroduction() : "";
        if (!oldIntro.equals(newIntro)) {
            content.append("更新了艺人简介;");
            hasChange = true;
        }

        // 对比排序权重
        Integer oldSort = oldArtist.getSort() != null ? oldArtist.getSort() : 0;
        Integer newSort = newParam.getSort() != null ? newParam.getSort() : 0;
        if (!oldSort.equals(newSort)) {
            content.append("排序权重从").append(oldSort).append("改为").append(newSort).append(";");
            hasChange = true;
        }

        // 注意：相册图片每次都会删除重建，所以不对比相册
        // 如果其他字段都没变化，说明只是更新了相册
        if (!hasChange && newParam.getAlbumImages() != null && !newParam.getAlbumImages().isEmpty()) {
            content.append("更新了艺人相册图片");
            hasChange = true;
        }

        return hasChange ? content.toString() : null;
    }

    /**
     * 获取艺人类型名称
     */
    private String getArtistTypeName(Integer artistType) {
        if (artistType == null) return "未知";
        switch (artistType) {
            case 1:
                return "音乐人";
            case 2:
                return "艺术家";
            case 3:
                return "厂牌";
            case 4:
                return "品牌方";
            default:
                return "未知";
        }
    }
}
