package com.backendsys.modules.crt.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.backendsys.exception.CustException;
import com.backendsys.modules.common.config.security.utils.SecurityUtil;
import com.backendsys.modules.crt.dao.CrtLoraStyleCategoryDao;
import com.backendsys.modules.crt.dao.CrtLoraStyleCollectDao;
import com.backendsys.modules.crt.dao.CrtLoraStyleDao;
import com.backendsys.modules.crt.entity.CrtLoraStyle;
import com.backendsys.modules.crt.entity.CrtLoraStyleCategory;
import com.backendsys.modules.crt.entity.CrtLoraStyleCollect;
import com.backendsys.modules.crt.service.CrtLoraStyleService;
import com.backendsys.utils.response.PageEntity;
import com.backendsys.utils.response.PageInfoResult;
import com.backendsys.utils.v2.PageUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class CrtLoraStyleServiceImpl implements CrtLoraStyleService {

    @Autowired
    private CrtLoraStyleDao crtLoraStyleDao;
    @Autowired
    private CrtLoraStyleCollectDao crtLoraStyleCollectDao;
    @Autowired
    private CrtLoraStyleCategoryDao crtLoraStyleCategoryDao;

    /**
     * 获取短剧创作-风格LoRA列表
     */
    @Override
    public PageEntity selectCrtLoraStyleList(CrtLoraStyle crtLoraStyle) {
        PageUtils.startPage();  // 分页

        List<Map<String, Object>> list = crtLoraStyleDao.selectCrtLoraStyleList(crtLoraStyle);

        // 1) 完成分页实体渲染
        PageEntity pageEntity = new PageInfoResult(list).toEntity();

        // 2) 分页列表格式化
        if (!list.isEmpty()) {

            // 查询风格LoRA-当前用户的收藏状态，将收藏状态添加到 list 中
            LambdaQueryWrapper<CrtLoraStyleCollect> wrapperCollect = new LambdaQueryWrapper<>();
            wrapperCollect.eq(CrtLoraStyleCollect::getUser_id, SecurityUtil.getUserId());
            List<CrtLoraStyleCollect> collectList = crtLoraStyleCollectDao.selectList(wrapperCollect);
            List<Long> collect_lora_style_ids = collectList.stream().map(item -> item.getLora_style_id()).collect(Collectors.toList());

            // 将收藏状态添加到 list 中
            list = list.stream().map(item -> {
                item.put("is_collect", (collect_lora_style_ids.contains(Convert.toLong(item.get("id")))) ? 1 : -1);
                return item;
            }).collect(Collectors.toList());

        }

        // 3) 分页实体重新赋值
        List<Object> objectList = list.stream().map(item -> (Object) item).collect(Collectors.toList());
        pageEntity.setList(objectList);

        return new PageInfoResult(list).toEntity();
    }

    /**
     * 获取短剧创作-风格分类列表
     */
    @Override
    public List<CrtLoraStyleCategory> selectCrtLoraStyleCategoryList() {
        PageUtils.startPage();  // 分页
        return crtLoraStyleCategoryDao.selectList(null);
    }

    /**
     * 获取短剧创作-风格LoRA列表-用户收藏的
     */
    @Override
    public PageEntity selectCrtLoraStyleListByCollect(CrtLoraStyle crtLoraStyle) {

        // 查询当前用户，已经收藏的风格ID集合 (按创建时间倒序)
        LambdaQueryWrapper<CrtLoraStyleCollect> wrapperCollect = new LambdaQueryWrapper<>();
        wrapperCollect.eq(CrtLoraStyleCollect::getUser_id, crtLoraStyle.getUser_id());
        wrapperCollect.orderByDesc(CrtLoraStyleCollect::getCreate_time);
        List<CrtLoraStyleCollect> crtLoraStyleCollectList = crtLoraStyleCollectDao.selectList(wrapperCollect);


        PageUtils.startPage();  // 分页

        // 根据ID集合，查询风格LoRA列表
        List<CrtLoraStyle> list = new ArrayList<>();
        if (!crtLoraStyleCollectList.isEmpty()) {

            // 获得已经收藏的风格LoRA ID集合
            List<Long> collect_lora_style_ids = crtLoraStyleCollectList.stream()
                .map(CrtLoraStyleCollect::getLora_style_id)
                .collect(Collectors.toList());

            LambdaQueryWrapper<CrtLoraStyle> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(CrtLoraStyle::getId, collect_lora_style_ids);
            if (!crtLoraStyle.getName().isEmpty()) wrapper.like(CrtLoraStyle::getName, crtLoraStyle.getName());
            if (crtLoraStyle.getCategory_id() != null) wrapper.eq(CrtLoraStyle::getCategory_id, crtLoraStyle.getCategory_id());

            // [DB] 查询风格LoRA列表 (已经收藏的
            list = crtLoraStyleDao.selectList(wrapper);

            // 1) 完成分页实体渲染
            PageEntity pageEntity = new PageInfoResult(list).toEntity();

            // 2) 分页列表格式化
            // 按照 lora_style_ids 的顺序 (按创建时间倒序) 对 list 进行重新排序
            CollUtil.sort(list, Comparator.comparingInt(item -> collect_lora_style_ids.indexOf(item.getId())));

            list = list.stream()
                .map(item -> {
                    item.setUser_id(crtLoraStyle.getUser_id());
                    item.setIs_collect(1);
                    return item;
                }).collect(Collectors.toList());

            // 3) 分页实体重新赋值
            List<Object> objectList = list.stream().map(item -> (Object) item).collect(Collectors.toList());
            pageEntity.setList(objectList);
        }

        return new PageInfoResult(list).toEntity();
    }

    /**
     * 获取短剧创作-风格LoRA列表-加入/取消收藏
     */
    @Override
    public Map<String, Object> setLoraStyleCollect(CrtLoraStyleCollect crtLoraStyleCollect) {

        // 是否收藏 (-1取消收藏, 1加入收藏)
        Integer is_collect = crtLoraStyleCollect.getIs_collect();
        Long lora_style_id = crtLoraStyleCollect.getLora_style_id();

        // 查询当前用户，是否已经收藏过该风格
        LambdaQueryWrapper<CrtLoraStyleCollect> wrapperCollect = new LambdaQueryWrapper<>();
        wrapperCollect.eq(CrtLoraStyleCollect::getUser_id, crtLoraStyleCollect.getUser_id());
        wrapperCollect.eq(CrtLoraStyleCollect::getLora_style_id, lora_style_id);

        if (is_collect == 1) {
            // 如果已经收藏过，则不变
            CrtLoraStyleCollect detail = crtLoraStyleCollectDao.selectOne(wrapperCollect);
            if (detail == null) {

                // [DB] 判断风格LoRA是否存在
                Boolean is_exist = crtLoraStyleDao.exists(new LambdaQueryWrapper<CrtLoraStyle>().eq(CrtLoraStyle::getId, lora_style_id));
                if (!is_exist) throw new CustException("风格LoRA不存在");

                // [DB] 加入收藏
                crtLoraStyleCollectDao.insert(crtLoraStyleCollect);
            }
        } else {
            // [DB] 取消收藏
            crtLoraStyleCollectDao.delete(wrapperCollect);
        }

        return Map.of("lora_style_id", crtLoraStyleCollect.getLora_style_id());
    }

}
