package org.jeecg.modules.ctop.controller;

import cn.com.ctop.kuaishou.modules.graphql.entity.KuaishouVideo;
import cn.com.ctop.kuaishou.modules.graphql.service.IKuaishouVideoService;
import cn.com.ctop.kuaishou.modules.graphql.service.IKuaishouWebInterfaceService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jeecg-boot
 */
@RestController
@RequestMapping("/graphql")
public class GraphqlController {
    @Autowired
    private IKuaishouWebInterfaceService kuaishouWebInterfaceService;
    @Autowired
    private IKuaishouVideoService kuaishouVideoService;

    @RequestMapping("/video")
    public void getVideoList(@RequestParam("uid") String uid){
        try {
            kuaishouWebInterfaceService.getVideoList(uid);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/addkuaishouuser")
    public Result<Map<String,Object>> addKuaishouUser(@RequestBody JSONObject jsonObject){
        String url = jsonObject.getString("url");
        String uid = kuaishouWebInterfaceService.checkKuaishouUser(url);
        Map<String, Object> resultMap = new HashMap<>();
        if(uid == null){
            resultMap.put("hasUser",false);
        }else {
            resultMap.put("hasUser",true);
            Thread thread = new Thread(){
                @Override
                public void run() {
                    try {
                        kuaishouWebInterfaceService.getVideoList(uid);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.start();
        }
        Result<Map<String, Object>> result = new Result<>();
        result.setSuccess(true);
        result.setResult(resultMap);
        return result;
    }

    @GetMapping("/publicfeeds")
    public Result<IPage<KuaishouVideo>> getVideoList(@RequestParam(name = "num", defaultValue = "99999999") Integer num) {
        Result<IPage<KuaishouVideo>> result = new Result<>();
        KuaishouVideo video = new KuaishouVideo();
        QueryWrapper<KuaishouVideo> queryWrapper = QueryGenerator.initQueryWrapper(video,null);
        queryWrapper.orderByDesc("num");
        queryWrapper.le("num",num);
        Page<KuaishouVideo> page = new Page<>(1, 20);
        IPage<KuaishouVideo> pageList = kuaishouVideoService.page(page,queryWrapper);
        result.setResult(pageList);
        result.setSuccess(true);
        return result;
    }
}
