package com.sonic.frog.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sonic.frog.dao.AiUserExtDao;
import com.sonic.frog.domain.entity.AiUserExt;
import com.sonic.frog.domain.input.AiUserExtInput;
import com.sonic.frog.service.AiUserExtService;
import com.sonic.frog.utils.BeanConver;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * AI用户扩展表服务实现类
 */
@Service
@Slf4j
public class AiUserExtServiceImpl extends ServiceImpl<AiUserExtDao, AiUserExt> implements AiUserExtService {
    @Override
    public void saveOrUpdateAiUserExt(Long aiId, AiUserExt aiUserExt, AiUserExtInput input, Long currentUserId) {
        //不储存参考图片
        input.setImageReferenceUrl(null);
        if (aiUserExt == null) {
            // 新增
            aiUserExt = BeanConver.copeBean(input, AiUserExt.class);
            aiUserExt.setAiId(aiId);
            aiUserExt.setUserId(currentUserId);
            aiUserExt.setCreateTime(LocalDateTime.now());
            aiUserExt.setEditorId(currentUserId);
            aiUserExt.setEditTime(LocalDateTime.now());
            save(aiUserExt);
        } else {
            //编辑
            Long id = aiUserExt.getId();
            aiUserExt = BeanConver.copeBean(input, AiUserExt.class);
            aiUserExt.setId(id);
            aiUserExt.setEditorId(currentUserId);
            aiUserExt.setEditTime(LocalDateTime.now());
            updateById(aiUserExt);
        }
    }

    @Override
    public AiUserExt getAiUserExtByAiId(Long aiId) {
        return getOne(Wrappers.<AiUserExt>lambdaQuery().eq(AiUserExt::getAiId, aiId).last("limit 1"));
    }

    @Override
    public void delAiUser(Long aiId) {
        update(Wrappers.<AiUserExt>lambdaUpdate().eq(AiUserExt::getAiId, aiId).set(AiUserExt::getIsDelete, true));
    }

    @Override
    public void updateAiUserDialoguePrologueSound(String url, Long aiId) {
        update(Wrappers.<AiUserExt>lambdaUpdate().eq(AiUserExt::getAiId, aiId).set(AiUserExt::getDialoguePrologueSound, url));
    }

    @Override
    public void updateAiUserSupportingContent(List<String> supContentList, Long aiId) {
        if (Collections.isEmpty(supContentList)) {
            return;
        }
        update(Wrappers.<AiUserExt>lambdaUpdate().eq(AiUserExt::getAiId, aiId).set(AiUserExt::getSupportingContent, JSON.toJSONString(supContentList)));
    }
}