<template>
    <div>
        <div class="content">
            <div class="container">
                <div>
                    <h4 class="color-blue">
                        <i class="glyphicon glyphicon-filter"></i>
                        {{ lang.qc }}
                    </h4>
                    <div class="well">
                        <form action="" method="get" role="form" class="form-inline form-filter">
                            <div class="form-group" style="margin-right: 10px;">
                                <div class="input-group">
                                    <div class="input-group-addon">{{ lang.time }}</div>
                                    <select name="type" class="form-control" id="type" v-on:change="onChange">
                                        <option value="day">{{ lang.today }}</option>
                                        <option value="week">{{ lang.week }}</option>
                                        <option value="halfmonth">{{ lang.half_month }}</option>
                                        <option value="month">{{ lang.month }}</option>
                                        <option value="season">{{ lang.season }}</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group" style="margin-right: 10px;">
                                <div class="input-group">
                                    <div class="input-group-addon">{{ lang.source }}</div>
                                    <select name="server" class="form-control" id="server" v-on:change="onChange">
                                        <option value="mycard">MCPro</option>
                                        <option value="233">233</option>
                                        <option value="koishi">Koishi</option>
                                        <option value="koishi_tcg">Koishi_tcg</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group" style="margin-right: 10px;">
                                <div class="input-group">
                                    <div class="input-group-addon">{{ lang.type }}</div>
                                    <select name="source" class="form-control" id="source" v-on:change="onChange">
                                        <option value="athletic">{{ lang.athletic }}</option>
                                        <option value="entertain">{{ lang.entertain }}</option>
                                        <option value="custom">{{ lang.custom }}</option>
                                        <option value="tag">{{ lang.tag }}</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group" style="margin-right: 10px;">
                                <div class="input-group">
                                    <div class="input-group-addon">{{ lang.totalDeck }}</div>
                                    <span class="form-control">{{ totalDeck }}</span>
                                </div>
                            </div>

                            <div class="form-group" style="display:none">
                                <button type="submit" id="search"
                                        class="form-control btn btn-primary">{{ lang.search }}
                                </button>
                            </div>

                        </form>
                    </div>

                    <h4 class="color-blue"><i class="glyphicon glyphicon-list-alt"></i> {{ lang.table_data }} </h4>

                    <div>
                        <ul class="nav nav-tabs">
                        <li :class="{ active: activeTab === 'Deck' }">
                            <a href="#tab-0" role="tab" data-toggle="tab" @click="setActive('Deck')">
                            <img class="tab-img" :src="getTabImage('Deck')" />
                            </a>
                        </li>
                        <li :class="{ active: activeTab === 'Monster' }">
                            <a href="#tab-1" role="tab" data-toggle="tab" @click="setActive('Monster')">
                            <img class="tab-img" :src="getTabImage('Monster')" />
                            </a>
                        </li>
                        <li :class="{ active: activeTab === 'Spell' }">
                            <a href="#tab-2" role="tab" data-toggle="tab" @click="setActive('Spell')">
                            <img class="tab-img" :src="getTabImage('Spell')" />
                            </a>
                        </li>
                        <li :class="{ active: activeTab === 'Trap' }">
                            <a href="#tab-3" role="tab" data-toggle="tab" @click="setActive('Trap')">
                            <img class="tab-img" :src="getTabImage('Trap')" />
                            </a>
                        </li>
                        <li :class="{ active: activeTab === 'Side' }">
                            <a href="#tab-4" role="tab" data-toggle="tab" @click="setActive('Side')">
                            <img class="tab-img" :src="getTabImage('Side')" />
                            </a>
                        </li>
                        <li :class="{ active: activeTab === 'Extra' }">
                            <a href="#tab-5" role="tab" data-toggle="tab" @click="setActive('Extra')">
                            <img class="tab-img" :src="getTabImage('Extra')" />
                            </a>
                        </li>
                        </ul>


                        <div class="tab-content">

                            <div role="tabpanel" class="tab-pane" :class="{ active: activeTab === 'Deck' }" v-show="activeTab === 'Deck'" id="tab-0">
                                <br>
                                <div class="table-responsive" style="width:100%;overflow-x:auto;overflow-y:hidden;">
                                    <table id="deck" class="table table-striped table-bordered table-hover example"
                                           :width="width"></table>
                                </div>
                            </div>

                            <div role="tabpanel" class="tab-pane" :class="{ active: activeTab === 'Monster' }" v-show="activeTab === 'Monster'" id="tab-1">
                                <br>
                                <div class="table-responsive" style="width:100%;overflow-x:auto;overflow-y:hidden;">
                                    <table id="monster" class="table table-striped table-bordered table-hover example"
                                           :width="width"></table>
                                </div>
                            </div>

                            <div role="tabpanel" class="tab-pane" :class="{ active: activeTab === 'Spell' }" v-show="activeTab === 'Spell'" id="tab-2">
                                <br>
                                <div class="table-responsive" style="width:100%;overflow-x:auto;overflow-y:hidden;">
                                    <table id="spell" class="table table-striped table-bordered table-hover example"
                                           :width="width"></table>
                                </div>
                            </div>

                            <div role="tabpanel" class="tab-pane" :class="{ active: activeTab === 'Trap' }" v-show="activeTab === 'Trap'" id="tab-3">
                                <br>
                                <div class="table-responsive" style="width:100%;overflow-x:auto;overflow-y:hidden;">
                                    <table id="trap" class="table table-striped table-bordered table-hover example"
                                           :width="width"></table>
                                </div>
                            </div>

                            <div role="tabpanel" class="tab-pane" :class="{ active: activeTab === 'Side' }" v-show="activeTab === 'Side'" id="tab-4">
                                <br>
                                <div class="table-responsive" style="width:100%;overflow-x:auto;overflow-y:hidden;">
                                    <table id="side" class="table table-striped table-bordered table-hover example"
                                           :width="width"></table>
                                </div>
                            </div>

                            <div role="tabpanel" class="tab-pane" :class="{ active: activeTab === 'Extra' }" v-show="activeTab === 'Extra'" id="tab-5">
                                <br>
                                <div class="table-responsive" style="width:100%;overflow-x:auto;overflow-y:hidden;">
                                    <table id="ex" class="table table-striped table-bordered table-hover example"
                                           :width="width"></table>
                                </div>
                            </div>

                            <div class="form-group" style="display:none">
                                <button type="submit" id="search"
                                        class="form-control btn btn-primary">{{ lang.search }}
                                </button>
                            </div>

                        </div>
                    </div>

                </div>
                <Footads></Footads>
            </div>
        </div>

    </div>
</template>

<script>
import Footads from './Footads'
import tb_language from './tb_lang.js'
import {
    mapGetters
} from 'vuex'
import API from '../api';
import deck1 from '../assets/img/deck1.png'
import deck2 from '../assets/img/deck2.png'

import monster1 from '../assets/img/monster1.png'
import monster2 from '../assets/img/monster2.png'

import spell1 from '../assets/img/spell1.png'
import spell2 from '../assets/img/spell2.png'

import trap1 from '../assets/img/trap1.png'
import trap2 from '../assets/img/trap2.png'

import side1 from '../assets/img/side1.png'
import side2 from '../assets/img/side2.png'

import extra1 from '../assets/img/extra1.png'
import extra2 from '../assets/img/extra2.png'

var dt = require('datatables.net')
var dt2 = require('datatables.net-bs')
import "../assets/css/dataTables.bootstrap.min.css"

var monsterTable;
var spellTable;
var trapTable;
var exTable;
var sideTable;
var deckTable;
const placeholder = {
    Deck: '请输入卡组名..',
    Monster: '请输入怪兽卡名..',
    Spell: '请输入魔法卡名..',
    Trap: '请输入陷阱卡名..',
    Side: '请输入卡片名..',
    Extra: '请输入卡片名..',
}
export default {
    components: {
        Footads
    },
    created: function () {
        var regex_match =
            /(nokia|iphone|android|motorola|^mot-|softbank|foma|docomo|kddi|up.browser|up.link|htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte-|longcos|pantech|gionee|^sie-|portalmmm|jigs browser|hiptop|^benq|haier|^lct|operas*mobi|opera*mini|320x320|240x320|176x220)/i;
        var u = navigator.userAgent;
        if (null == u) {
            return true;
        }
        var result = regex_match.exec(u);
        if (null == result) {
        } else {
            this.width = "250%"
        }
        var lang = localStorage.getItem('lang') || 'cn';
        this.init(lang)
    },
    mounted: function () {
        this.preloadTabImages();
        this.init2();
    },
    data() {
        return {
            totalDeck: 0,
            type: "",
            activeTab: 'Deck', // default selected tab
            width: "100%",
            tabImages: {
            Deck: { A: deck1, B: deck2 },
            Monster: { A: monster1, B: monster2 },
            Spell: { A: spell1, B: spell2 },
            Trap: { A: trap1, B: trap2 },
            Side: { A: side1, B: side2 },
            Extra: { A: extra1, B: extra2 },
            },
        }
    },
    computed: {
        ...mapGetters({
            lang: 'getLang',
        }),
    },
    watch: {
        lang: function (val) {
            // console.log('lang change1', val)
            this.init2()
        },
    },
    methods: {
        // 计算禁卡表发布时间间隔
        // period() {
        //   const today = new Date();
        //   const year = today.getFullYear();
        //   const dates = [
        //     new Date(year, 0, 1),
        //     new Date(year, 3, 1),
        //     new Date(year, 6, 1),
        //     new Date(year, 9, 1),
        //   ];
        //   const season = dates.reduce((min, date) => {
        //     const diff = Math.floor((today - date) / (1000 * 60 * 60 * 24));
        //     if (today >= date && diff >= 0 && diff < min) {
        //       return diff;
        //     }
        //     return min;
        //   }, Infinity);
        //   // 根据select设定对应天数
        //   const periodMap = {
        //     day: 1,
        //     week: 7,
        //     halfmonth: 15,
        //     month: 30,
        //     season: season
        //   };
        //   var selectedType = $("#type").val();
        //   return periodMap[selectedType] || 1;
        // },
        
        navClick(tab) {
            this.activeTab = tab;
            $(".input-sm").attr("placeholder", placeholder[tab]);
        },

        setActive(tab) {
            this.activeTab = tab;
            $(".input-sm").attr("placeholder", placeholder[tab]);
        },
        preloadTabImages() {
            const imgs = []
            Object.values(this.tabImages).forEach(({A, B}) => {
            [A, B].forEach(src => {
                const im = new Image()
                im.src = src
                imgs.push(im)
            })
            })
            // Keep a reference so GC doesn’t drop them immediately
            this._preloaded = imgs
        },
        getTabImage(tab) {
            return this.activeTab === tab ? this.tabImages[tab].B : this.tabImages[tab].A
        },

        init: function (lang) {
            if (lang === "cn") {
                this.isActive = true;
            } else {
                this.isActive = false;
            }
            // this.lang = language[lang]
            this.getCount()
        },
        init2: function () {
            var lang = localStorage.getItem('lang') || 'cn';
            if (lang === "cn") {
                this.isActive = true;
            } else {
                this.isActive = false;
            }

            var self = this;

            function renderPage() {
                if (monsterTable) {
                    monsterTable.clear();
                    monsterTable.destroy();
                }
                if (spellTable) {
                    spellTable.clear();
                    spellTable.destroy();
                }
                if (trapTable) {
                    trapTable.clear();
                    trapTable.destroy();
                }
                if (exTable) {
                    exTable.clear();
                    exTable.destroy();
                }
                if (sideTable) {
                    sideTable.clear();
                    sideTable.destroy();
                }

                var server = $("#server").val() || "mycard"
                var source = $("#source").val() || "athletic"
                var final_source = server + "-" + source

                $.get('https://sapi.moecube.com:444/ygopro/analytics/single/type', {
                    type: $("#type").val(),
                    lang: localStorage.getItem('lang') || 'cn',
                    extra: 'name',
                    source: final_source
                }, function (data) {
                    var monster = data.monster;
                    var spell = data.spell;
                    var trap = data.trap;
                    var side = data.side;
                    var ex = data.ex;

                    monsterTable = renderTable("#monster", monster);
                    spellTable = renderTable("#spell", spell);
                    trapTable = renderTable("#trap", trap);
                    exTable = renderTable("#ex", ex);
                    sideTable = renderTable("#side", side);
                });

                var lang = localStorage.getItem('lang') || 'cn';
                if (lang === "cn") {
                    if (deckTable) {
                        deckTable.clear();
                        deckTable.destroy();
                    }

                    $.get('https://sapi.moecube.com:444/ygopro/analytics/deck/type', {
                        type: $("#type").val(),
                        source: final_source
                    }, function (data) {
                        var obj = data;
                        if (typeof obj === 'string')
                            obj = JSON.parse(data);

                        var rank = 1;
                        var processData = obj.map(function (x) {
                            var tagStr = [];
                            var deckName = x.name;
                            for (var i = 0; i < x.tags.length; i++) {
                                var tagName = x.tags[i].name || x.tags[i].toString() || "";
                                var short_tagName = tagName.replace(deckName + "-", "");
                                tagStr.push(short_tagName)
                            }
                            var PickRate = (0 < (x.count / (self.totalDeck)) && (x.count / (self.totalDeck)) < 1)
                                ? ((x.count / (self.totalDeck) * 100)).toFixed(2) + "%" : "-";

                            // 出现-是数据算出来不在0-1之间
                            return [rank++, x.name, x.count, PickRate, tagStr.join(" , ")];
                        });

                        deckTable = $("#deck").DataTable({
                            data: processData,
                            pageLength: 25,
                            order: [
                                [2, "desc"]
                            ],
                            ordering: true,
                            columns: [
                                {title: tb_language[lang].rank},
                                {title: tb_language[lang].deck},
                                {title: tb_language[lang].count},
                                {title: tb_language[lang].PickRate},
                                {title: tb_language[lang].topTags},
                            ],
                            columnDefs: [
                                {
                                    render: function (data, type, row) {
                                        return "<a href='?name=" + data + "#/deck'>" + data + "</a>";
                                    },
                                    targets: 1
                                }
                            ],
                            language: tb_language[lang]
                        });
                    });
                }
            }

            function renderTable(tableID, tableData) {
                tableData = tableData || [];
                var lang = localStorage.getItem('lang') || 'cn';
                var langIndex = (lang === 'en' ? 'en-US' : 'zh-CN');
                var rank = 1;
                var processData = tableData.map(function (d) {
                    // var period = self.period();
                    var PickRate = (parseInt(d.putone) + parseInt(d.puttwo) + parseInt(d.putthree)) / self.totalDeck;
                    PickRate = (0 < PickRate && PickRate < 1) ? (PickRate * 100).toFixed(2) + "%" : "-";

                    // 使用率出现-是数据算出来不在0-1之间
                    return [
                        rank++, d.name ? d.name[langIndex] : "未知卡片",
                        d.frequency,
                        PickRate,
                        d.putone,
                        d.puttwo,
                        d.putthree,
                        d.id
                    ];
                });

                var table = $(tableID).DataTable({
                    data: processData,
                    pageLength: 50,
                    order: [[2, "desc"]],
                    ordering: true,
                    columns: [
                        {title: tb_language[lang].rank},
                        {title: tb_language[lang].cardName},
                        {title: tb_language[lang].used},
                        {title: tb_language[lang].PickRate},
                        {title: tb_language[lang].put1},
                        {title: tb_language[lang].put2},
                        {title: tb_language[lang].put3},
                    ],
                    columnDefs: [
                        {
                            render: function (data, type, row) {
                                return "<a href='https://ygocdb.com/card/" + row[7] + "' target='_blank'>" + data + "</a>";
                            },
                            targets: 1
                        },
                    ],
                    language: tb_language[lang]
                });

                $(".input-sm").attr("placeholder", placeholder.Deck);

                return table;
            }

            renderPage();

            $("#search").click(function () {
                renderPage();
                return false;
            });
        },
        onChange: function () {
            var self = this;
            this.getCount().then(function () {
                self.init2();
            });
        },


        getCount: function () {
            var server = $("#server").val() || "mycard"
            var source = $("#source").val() || "athletic"
            var opt = {
                type: $("#type").val() || "day",
                source: server + "-" + source
            };
            var self = this;
            return API.getCount(opt).then((res) => {
                if (isNaN(res.data)) {
                    return 0;
                } else {
                    this.totalDeck = res.data;
                    return res.data;
                }
            });
        }
    },
    events: {
        'lang-change': function (lang) {
            this.init(lang)
            this.onChange()
        }
    },
}
</script>

<style scoped>

</style>

