package com.aiup.task.listener;

import com.aiup.service.domain.query.CreateNodesQuery;
import com.aiup.service.entity.UserNotesCnt;
import com.aiup.service.entity.UserNotesTask;
import com.aiup.service.service.NoteService;
import com.aiup.service.service.TemplateInfoService;
import com.aiup.service.service.UserNotesCntService;
import com.aiup.service.service.UserNotesTaskService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class NoteCreaterListener {

    @Autowired
    NoteService noteService;
    @Autowired
    UserNotesTaskService userNotesTaskService;
    @Autowired
    UserNotesCntService userNotesCntService;

    @RabbitHandler
    @RabbitListener(queues = "Qu_note_create_new",containerFactory = "customContainerFactory")
    public void subscribe(String message) {
        log.info("接收到新消息：{}",message);
        UserNotesTask task = JSON.parseObject(message,UserNotesTask.class);
        CreateNodesQuery query = new CreateNodesQuery();
        query.setCount(task.getCount());
        query.setPostUrl(task.getPostUrl());
        query.setTemplateId(task.getTemplateId());
        List<String> list = noteService.createNotes(query);
        task.setPrompt(list.get(0));
        task.setContent(list.get(1));
        task.setStatus(1);
        task.setFinishTime(new Date());
        userNotesTaskService.update(task);
        //记录用户免费条数
        //判断用户当日免费使用次数
        UserNotesCnt userNotesCnt = new UserNotesCnt();
        userNotesCnt.setUserId(task.getUserId());
        DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        userNotesCnt.setCDate(dateformat.format(new Date()));
        PageRequest pageRequest = PageRequest.of(0,5);
        List<UserNotesCnt> unList = userNotesCntService.queryByPage(userNotesCnt, pageRequest).getContent();
        if(unList != null && unList.size()>=1){
            userNotesCnt = unList.get(0);
        }
        else{
            userNotesCnt.setCount(0);
        }
        userNotesCnt.setCount(userNotesCnt.getCount()+1);
        if(userNotesCnt.getId() == null || userNotesCnt.getId() <=0){
            userNotesCntService.insert(userNotesCnt);
        }
        else {
            userNotesCntService.update(userNotesCnt);
        }
        log.info("生成帖子完成");
    }
}
