package com.yutou.nas.bangumi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yutou.nas.utils.HttpTools;
import com.yutou.nas.utils.RedisTools;
import com.yutou.nas.utils.Tools;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class BangumiTools {
    private static final String url = "http://api.bgm.tv/";
    private static final String toDayBangumi = url + "calendar";
    private static final String BangumiInfo = url + "/subject/%s?responseGroup=large";
    private static final String SearchBangumi = url + "/search/subject/%s?responseGroup=large";

    /**
     * 获取番剧列表
     *
     * @param day 周几，-1为全部,非1~7范围则为当天
     * @return 当日数据
     */
    public static JSONObject getBangumi(int day) {
        String str = HttpTools.get(toDayBangumi);
        JSONArray main = JSONArray.parseArray(str);
        if (day == -1) {
            JSONObject json = new JSONObject();
            json.put("bangumi", main);
            return json;
        }
        if (day < 1 || day > 7) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
            calendar.setFirstDayOfWeek(Calendar.MONDAY);
            calendar.setTime(new Date());
            day = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            if (day == 0) {
                day = 7;
            }
        }
        if (main != null)
            for (Object o : main) {
                JSONObject json = (JSONObject) o;
                if (json.getJSONObject("weekday").getInteger("id") == day) {
                    return json;
                }
            }
        return null;
    }

    /**
     * 获取番剧详细信息
     *
     * @param id 剧集id
     * @return 详细信息
     */
    public static JSONObject getBangumiInfo(int id) {
        String str = HttpTools.get(String.format(BangumiInfo, id + ""));
        return JSONObject.parseObject(str);
    }

    /**
     * 搜索番剧
     *
     * @param key 关键词
     * @return 详细信息
     */
    public static JSONObject search(String key) {
        String str = HttpTools.get(String.format(SearchBangumi, key));
        return JSONObject.parseObject(str);
    }

    /**
     * 获取下一集播放日期
     *
     * @param id 番剧id
     * @return 日期
     */
    public static String getPlayNextTime(int id) {
        JSONObject info = getBangumiInfo(id);
        JSONArray eps = info.getJSONArray("eps");
        String toDayTime = Tools.getToDayTime();
        for (Object o : eps) {
            JSONObject ep = (JSONObject) o;
            String time = ep.getString("airdate");
            try {
                if (new SimpleDateFormat("yyyy-MM-dd").parse(time).getTime() >=
                        new SimpleDateFormat("yyyy-MM-dd").parse(toDayTime).getTime()) {
                    return time;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 格式化字符串输出番剧详细信息
     *
     * @param id 番剧id
     * @return 详细内容
     */
    public static List<String> reportBangumiInfo(int id) {
        List<String> bangumiList=new ArrayList<>();
        JSONObject json = getBangumiInfo(id);
        if(json.containsKey("code")){
            bangumiList.add("error = "+json.toJSONString());
            return bangumiList;
        }
        JSONArray eps = json.getJSONArray("eps");
        JSONArray crts = json.getJSONArray("crt");
        JSONArray staffs = json.getJSONArray("staff");
        StringBuilder builder = new StringBuilder();
        builder.append("<img ").append(json.getJSONObject("images").getString("large")).append(" /img>").append("\n");
        builder.append("标题:").append(json.getString("name_cn")).append("\n");
        builder.append("日文标题:").append(json.getString("name")).append("\n");
        builder.append("首播时间:").append(json.getString("air_date")).append("\n");
        builder.append("每周").append(json.getInteger("air_weekday")).append("放送").append("\n");
        builder.append("Bangumi地址:").append(json.getString("url")).append("\n");
        builder.append("Bangumi评分:").append(json.getJSONObject("rating").getFloat("score")).append("\n");
        builder.append("预计放送集数:").append(json.getInteger("eps_count")).append("\n");
        if (eps != null) {
            builder.append("已放送集:").append("\n");
            for (Object o : eps) {
                JSONObject ep = (JSONObject) o;
                if (ep.getString("status").equals("Air")) {
                    builder.append("· 第").append(ep.getInteger("sort")).append("话:");
                    builder.append(ep.getString("name"));
                    builder.append("[").append(ep.getString("name_cn")).append("]").append("\n");
                    builder.append("播放日期:").append(ep.getString("airdate")).append(";\n");
                    builder.append("播放时长:").append(ep.getString("duration")).append(";\n");
                    builder.append("单集介绍:").append(ep.getString("desc"));
                    builder.append("\n\n");
                } else {
                    builder.append("下一话:");
                    builder.append(" 第").append(ep.getInteger("sort")).append("话:");
                    builder.append("播放日期:").append(ep.getString("airdate")).append("\n\n");
                    break;
                }
            }
        }
        if (crts != null) {
            builder.append("角色介绍:").append("\n");
            for (Object o : crts) {
                JSONObject crt = (JSONObject) o;
                JSONObject info = crt.getJSONObject("info");
                builder.append(crt.getString("role_name")).append(":");
                builder.append(crt.getString("name"));
                builder.append("(").append(crt.getString("name_cn")).append(")").append("  ");
                builder.append("CV:").append(crt.getJSONArray("actors").getJSONObject(0).getString("name"));
                builder.append("(").append(info.getString("gender")).append(")");
                builder.append("\n");
            }
        }
        Map<String, List<JSONObject>> map = new HashMap<>();
        for (Object o : staffs) {
            JSONObject staff = (JSONObject) o;
            for (Object jobs : staff.getJSONArray("jobs")) {
                String job = (String) jobs;
                List<JSONObject> list;
                if (!map.containsKey(job)) {
                    list = new ArrayList<>();
                } else {
                    list = map.get(job);
                }
                list.add(staff);
                map.put(job, list);
            }
        }
        if (!map.isEmpty()) {
            builder.append("staff:").append("\n");
            for (String key : map.keySet()) {
                builder.append(key).append(":");
                for (JSONObject staff : map.get(key)) {
                    builder.append(staff.getString("name_cn"));
                    builder.append("(").append(staff.getString("name")).append(")");
                    builder.append("、");
                }
                builder.append("\n");
            }
        }
        bangumiList.add(builder.toString());
        return bangumiList;
    }

    /**
     * 格式化输出新番列表
     * @return 新番信息
     */
    public static String reportBangumiList(){
        try {
            JSONObject json=getBangumi(-1);
            StringBuilder builder=new StringBuilder();
            assert json != null;
            JSONArray array=json.getJSONArray("bangumi");
            for (Object o : array) {
                JSONObject data= (JSONObject) o;
                JSONObject weekday=data.getJSONObject("weekday");
                JSONArray items=data.getJSONArray("items");
                builder.append(weekday.getString("cn")).append("(").append(weekday.getString("ja")).append(")");
                builder.append(":").append("\n");
                reportBangumi(builder, items,false);
                builder.append("\n");
            }
            return builder.toString();
        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private static void reportBangumi(StringBuilder builder, JSONArray items,boolean reportEp) {
        int epIndex = 0;
        String epName = "N/A";
        for (Object oj : items) {
            JSONObject item = (JSONObject) oj;
            builder.append("[").append(item.getInteger("id")).append("]");
            builder.append(StringUtils.isEmpty(item.getString("name_cn"))
                    ?item.getString("name"):item.getString("name_cn"));
            if(!reportEp){
                builder.append("\n");
                continue;
            }
            JSONObject info=getBangumiInfo(item.getInteger("id"));
            if(info.get("eps")==null){
                continue;
            }
            JSONArray eps = info.getJSONArray("eps");
            for (Object oe : eps) {
                JSONObject ep = (JSONObject) oe;
                if (ep.getString("status").equals("Air")) {
                    epIndex = ep.getInteger("sort");
                    epName = ep.getString("name");
                } else {
                    break;
                }
            }
            builder.append(" 第").append(epIndex).append("话:");
            builder.append(epName);
            builder.append("\n");
        }
    }

    /**
     * 格式化字符串输出今日播放番剧列表
     *
     * @return 番剧列表
     */
    public static String reportToDayBangumi() {
        String toDayTime = Tools.getToDayTime();
        if (!toDayTime.equals(RedisTools.get("reportToDayBangumi"))) {
            RedisTools.set("reportToDayBangumi", toDayTime);
            StringBuilder builder = new StringBuilder();
            JSONObject toDay = getBangumi(0);
            if (toDay == null) {
                builder.append("今天没有任何番剧放送~");
            } else {
                JSONObject weekday = toDay.getJSONObject("weekday");
                JSONArray items = toDay.getJSONArray("items");
                builder.append("今日 ").append(weekday.get("cn")).append("(").append(weekday.get("ja")).append(")");
                builder.append(" 放送列表:").append("\n");
                reportBangumi(builder, items,true);
            }
            RedisTools.set("toDayBangumi", builder.toString());
            return builder.toString();
        } else {
            return RedisTools.get("toDayBangumi");
        }
    }

    /**
     * 格式化字符串输出搜索动画
     *
     * @param key 关键词
     * @return 详细内容
     */
    public static List<String> reportSearchBangumi(String key) {
        List<String> bangumiList=new ArrayList<>();
        JSONObject main = search(key);
        if (main.getInteger("results") > 0) {
            StringBuilder builder = new StringBuilder();
            List<JSONObject> list = main.getJSONArray("list").toJavaList(JSONObject.class);
            Collections.reverse(list);
            for (Object items : list) {
                JSONObject item = (JSONObject) items;
                builder=new StringBuilder();
                builder.append("标题:").append(item.getString("name_cn")).append("\n");
                builder.append("日文标题:").append(item.getString("name")).append("\n");
                String type;
                switch (item.getInteger("type")) {
                    case 1:
                        type = "书籍";
                        break;
                    case 2:
                        type = "动画";
                        break;
                    case 3:
                        type = "音乐";
                        break;
                    case 4:
                        type = "游戏";
                        break;
                    case 6:
                        type = "真人剧(Real)";
                        break;
                    default:
                        type = item.getInteger("type") + "";
                }
                builder.append("类型:").append(type).append("\n");
                builder.append("id:").append(item.getInteger("id")).append("\n");
                if (item.containsKey("rating"))
                    builder.append("Bangumi评分:").append(item.getJSONObject("rating").getFloat("score")).append("\n");
                builder.append("首播时间:").append(item.getString("air_date")).append("\n");
                builder.append("每周 ").append(item.getInteger("air_weekday")).append(" 放送").append("\n");
                builder.append("放送集数:").append(item.getInteger("eps")).append("\n");
                builder.append("Bangumi地址:").append(item.getString("url")).append("\n");
                builder.append("介绍:").append(item.getString("summary")).append("\n");
                builder.append("\n").append("\n");
                bangumiList.add(builder.toString());
            }
            return bangumiList;
        } else {
            bangumiList.add("搜索不到任何内容:" + key);
            return bangumiList;
        }
    }

    public static void main(String[] args) {
        String str = reportBangumiList();
        com.yutou.nas.utils.Log.i(str);

    }
}
