package com.aiup.api.controller;

import com.aiup.service.domain.R;
import com.aiup.service.domain.query.*;
import com.aiup.service.domain.response.ListBaseResponse;
import com.aiup.service.domain.response.NotesDetailResponse;
import com.aiup.service.domain.response.WeChatLoginResponse;
import com.aiup.service.entity.*;
import com.aiup.service.service.*;
import com.aiup.service.utils.LoginUserUtils;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@Api(tags = "笔记相关接口")
@RestController
@RequestMapping("/v1/notes")
@RequiredArgsConstructor
@Slf4j
public class NodesController {

    @Autowired
    NoteService noteService;

    @Autowired
    XhsNotesBaseService xhsNotesBaseService;
    @Autowired
    XhsUserBaseService xhsUserBaseService;

    @Autowired
    UserLicenseService userLicenseService;

    @Autowired
    UserNotesCntService userNotesCntService;
    @Autowired
    UserNotesTaskService userNotesTaskService;
    @Autowired
    TemplateInfoService templateInfoService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Value("${notes.category}")
    private String category;

    @ApiOperation(value = "获取内容列表")
    @PostMapping("/getNotesList")
    public R<ListBaseResponse<XhsNotesBase>> getNotes(@Validated @RequestBody PageBaseQuery<NotesListQuery> query) {
        ListBaseResponse<XhsNotesBase> notesList = noteService.getNotesList(query);
        return R.ok(notesList);
    }

    @ApiOperation(value = "根据帖子ID获取帖子明细")
    @PostMapping("/getNotesDetail")
    public R<NotesDetailResponse> getNotesDetail(@Validated @RequestBody NotesDetailQuery query){
        XhsNotesBase xhsNotesBase = xhsNotesBaseService.queryById(query.getId());
        if(xhsNotesBase == null){
            return R.error("帖子不存在，请刷新后重试！");
        }
//        PageRequest pageRequest = PageRequest.of(0,100);
//        XhsUserBase xhsUserBase = new XhsUserBase();
//        xhsUserBase.setIsDel(0);
//        xhsUserBase.setUserId(xhsNotesBase.getUserId());
//        List<XhsUserBase> content = xhsUserBaseService.queryByPage(xhsUserBase, pageRequest).getContent();
        NotesDetailResponse response = new NotesDetailResponse();
        response.setNotesBase(xhsNotesBase);
//        if(content != null && content.size()>0) {
//            response.setUserBase(content.get(0));
//        }
        return R.ok(response);
    }

    @ApiOperation(value = "获取分类列表")
    @PostMapping("/getCategoryList")
    public R<String[]> getCategoryList(){
        //分类列表暂时存放在配置文件中，
        //理论上应该从数据库中实时查询，但考虑效率问题，手动进行更新
        String[] categoryArray = category.split(",");
        return R.ok(categoryArray);
    }

    @ApiOperation(value = "创建内容")
    @PostMapping("/createNotes")
    public R<String> createNotes(@Validated @RequestBody CreateNodesQuery query){
        TemplateInfo templateInfo = templateInfoService.queryById(query.getTemplateId());
        if(templateInfo == null || templateInfo.getIsDeleted() ==1){
            return R.error("模板信息无效");
        }
        //分类列表暂时存放在配置文件中，
        //理论上应该从数据库中实时查询，但考虑效率问题，手动进行更新
        //验证用户许可是否到期
        boolean todayIfFree = false;
        Integer userId = LoginUserUtils.getLoginUser().getUserId();
        UserLicense userLicense = new UserLicense();
        userLicense.setIsDeleted(0);
        userLicense.setUserId(userId);
        PageRequest pageRequest = PageRequest.of(0,5);
        //判断用户当日免费使用次数
        UserNotesCnt userNotesCnt = new UserNotesCnt();
        userNotesCnt.setUserId(userId);
        DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        userNotesCnt.setCDate(dateformat.format(new Date()));
        List<UserNotesCnt> unList = userNotesCntService.queryByPage(userNotesCnt, pageRequest).getContent();
        if(unList != null && unList.size()>=1){
            userNotesCnt = unList.get(0);
        }
        else{
            userNotesCnt.setCount(0);
        }
        if(userNotesCnt.getCount() >=3){
            todayIfFree =false;
        }
        else{
            todayIfFree = true;
        }
        if(!todayIfFree) {
            List<UserLicense> llist = userLicenseService.queryByPage(userLicense, pageRequest).getContent();
            if (llist == null || llist.size() <= 0) {
                return R.error("您的账号无授权许可，请购买许可");
            }
            UserLicense license = llist.get(0);
            if (license.getEndTime() == null) {
                return R.error("您的账号许可无效，请购买许可");
            }
            long endTime = license.getEndTime().getTime();
            long nowTime = (new Date()).getTime();
            if (endTime < nowTime) {
                return R.error("您的账号已过期，请购买许可");
            }
        }

 //         String content = noteService.createNotes(query);
//        userNotesCnt.setCount(userNotesCnt.getCount()+1);
//        if(userNotesCnt.getId() == null || userNotesCnt.getId() <=0){
//            userNotesCntService.insert(userNotesCnt);
//        }
//        else {
//            userNotesCntService.update(userNotesCnt);
//        }
        //改为异步队列生成
        UserNotesTask task = new UserNotesTask();
        task.setUserId(LoginUserUtils.getLoginUser().getUserId());
        task.setCount(query.getCount());
        Date now = new Date();
        task.setCreateTime(now);
        task.setStatus(0);
        task.setTemplateId(query.getTemplateId());
        task.setPostUrl(query.getPostUrl());
        dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String cT = dateformat.format(now);
        task.setTitle(templateInfo.getTemplateName()+"("+cT+")");
        UserNotesTask insert = userNotesTaskService.insert(task);
        rabbitTemplate.convertAndSend("Ex_New_Note","Rk_New_Note", JSON.toJSONString(insert));
        return R.ok();
    }
}
