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

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.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.ArtistVo;
import com.liquidnet.service.kylin.entity.KylinArtist;
import com.liquidnet.service.kylin.entity.KylinArtistAlbum;
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.Collections;
import java.util.List;
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 KylinArtistPerformanceMapper artistPerformanceMapper;

    @Autowired
    private IKylinArtistOperationLogService operationLogService;

    @Autowired
    private DataUtils dataUtils;

    /**
     * 创建艺人
     */
    @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);
            }

            // TODO 根据艺人ID查询所有关联的演出，然后删除缓存中对应的演出阵容

            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)
                );

                artistAlbumMapper.deleteByArtistId(artistId);

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

            // TODO 根据艺人ID查询所有关联的演出

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

    /**
     * 检查艺人名称是否存在
     */
    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 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 "未知";
        }
    }
}
