<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: isActive }" v-if="isActive">
                                <a href="#tab-0" role="tab" data-toggle="tab" @click='navClick("Deck")'><img class="tab-img"
                                                                                                             :src="img0"></a>
                            </li>
                            <li :class="{ active: !isActive }">
                                <a href="#tab-1" role="tab" data-toggle="tab" @click='navClick("Monster")'><img class="tab-img"
                                                                                                                :src="img1"></a>
                            </li>
                            <li>
                                <a href="#tab-2" role="tab" data-toggle="tab" @click='navClick("Spell")'><img class="tab-img"
                                                                                                              :src="img2"></a>
                            </li>
                            <li>
                                <a href="#tab-3" role="tab" data-toggle="tab" @click='navClick("Trap")'><img class="tab-img"
                                                                                                             :src="img3"></a>
                            </li>
                            <li>
                                <a href="#tab-4" role="tab" data-toggle="tab" @click='navClick("Side")'><img class="tab-img"
                                                                                                             :src="img4"></a>
                            </li>
                            <li>
                                <a href="#tab-5" role="tab" data-toggle="tab" @click='navClick("Extra")'><img class="tab-img"
                                                                                                              :src="img5"></a>
                            </li>
                        </ul>

                        <div class="tab-content">

                            <div role="tabpanel" class="tab-pane" :class="{ active: isActive }" v-if="isActive"
                                 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: !isActive }" 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" 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" 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" 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" 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 img0 from '../assets/img/500x300_deck.png'

import img1 from '../assets/img/500x300_monster.png'

import img2 from '../assets/img/500x300_Spell.png'

import img3 from '../assets/img/500x300_Trap.png'

import img4 from '../assets/img/500x300_side.png'
import img5 from '../assets/img/ExtraWithBorder.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.init2();
    },
    data() {
        return {
            totalDeck: 0,
            type: "",
            isActive: true,
            width: "100%",
            img0: img0,
            img1: img1,
            img2: img2,
            img3: img3,
            img4: img4,
            img5: img5,
        }
    },
    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(data) {
            // console.log('%c ---------------------src' + '\\' + 'components' + '\\' + 'Cards.vue---------------------%c:238', 'background:#f034c6', 'background:#14f1a4',
            //   data)
            $(".input-sm").attr("placeholder", placeholder[data])
        },
        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://www.ourocg.cn/search/" + row[7] + "'>" + 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>
#deck {
    margin-top: 20px !important;
    border: 1px solid black;
}

</style>

