<template>
    <div>
        <div class="content">
            <div class="container">
                <div>
                    <div class='winRateTitle'>
                        <div id="winRateTitle-1"> 这个表体现了环境主流之间胜率,显示的胜率为 <div class="winRateTitle-color-1">左边的卡组</div>
                            VS <div class="winRateTitle-color-2">上边的卡组</div>
                        </div>
                     <!--    <div id="winRateTitle-2">更新:在每个月<div class="winRateTitle-color-3">20日</div>之前，胜率为<div
                                class="winRateTitle-color-3">上月胜率</div>。在每个月<div class="winRateTitle-color-3">20日</div>
                            以及之后，胜率为<div class="winRateTitle-color-3">当月胜率</div> </div>-->
                            <div id="winRateTitle-2">更新:<div class="winRateTitle-color-3">每天更新,当月胜率</div></div>
                          
                        
                    </div>
                    <div class='winRateContent'>
                        <div class='winRateContent-Tabs'>

                            <el-tabs v-model='winRateButtonDefault' @tab-click="showClickWinRate">
                                <el-tab-pane :label=winRateButtonText[0] name='0'> </el-tab-pane>
                                <el-tab-pane :label=winRateButtonText[1] name='1'> </el-tab-pane>
                                <el-tab-pane :label=winRateButtonText[2] name='2'> </el-tab-pane>

                            </el-tabs>

                        </div>

                        <div class='winRateTable'>
                            <el-table  ref="tableList" :data="tableData" border style="width: 100%" :header-cell-style="hdMonitor"
                                :cell-style="csMonitor" @sort-change='sortChange'>

                                <el-table-column v-for="item in tableHead" :key="item.key" :label='item.label'
                                    :property='item.prop' :sortable="item.sortable" :resizable="item.resizable"
                                    :render-header="labelFunction">
                                    <template slot-scope="scope">
                                        <div>{{item.key== 0  ? scope.row[item.label]: scope.row[item.label]+'%'}}

                                        </div>
                                    </template>
                                </el-table-column>

                            </el-table>
                        </div>
                    </div>
                    <div class='winRateFooter'>查看线上各卡组与单卡使用数据请进入<a class="winRateTitle-color-4"
                            href="#/cards">【卡片排行】</a></div>
                </div>

            </div>
        </div>
    </div>
</template>

<script>
    //这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
    //例如：import 《组件名称》 from '《组件路径》';
    import API from '../api';
    const winRateButtonText = ['先攻胜率', '后攻胜率', '综合胜率']
    const builtInColumnTitle = {
        deckType: '卡组种类',
        avgWinRate: '均胜率'
    }
    export default {
        //import引入的组件需要注入到对象中才能使用
        components: {},
        data() {
            //这里存放数据
            return {
                builtInColumnTitle,
                tableChangeCount: 0,
                winRateColumnTitle: [],
                winRateButtonDefault: '0',
                winRateButtonText,
                tableFlag: 0, //0 先攻 1 后攻 2 总 
                queryJsonStr: [],
                tableHead: [],
                tableData: [],
                totalWinRateData: [],
                tableOrder: null,
            };
        },
        //监听属性 类似于data概念
        computed: {},
        //监控data中的数据变化
        watch: {},
        //方法集合
        methods: {
            gradientColor(startColor, endColor, startPercent,endPercent,curPercent) {
                let startRGB = this.colorRgb(startColor); //转换为rgb数组模式
                let startR = startRGB[0];
                let startG = startRGB[1];
                let startB = startRGB[2];
                let endRGB = this.colorRgb(endColor);
                let endR = endRGB[0];
                let endG = endRGB[1];
                let endB = endRGB[2];
                let sR = (endR - startR) / ((endPercent-startPercent)*100); //总差值
                let sG = (endG - startG) / ((endPercent-startPercent)*100);
                let sB = (endB - startB) / ((endPercent-startPercent)*100);
                let colorRet = '';
                let tempPercent=(curPercent-startPercent)*100
                let rgbStr = 'rgb(' + parseInt((sR * tempPercent + startR)) + ',' + parseInt((sG *
                        tempPercent + startG)) +
                    ',' +
                    parseInt((sB * tempPercent + startB)) + ')'
          
                let hex = this.colorHex(rgbStr);
                colorRet = hex
             
                return  colorRet;
            },
            colorRgb(sColor) {
                let reg = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
                sColor = sColor.toLowerCase();
                if (sColor && reg.test(sColor)) {
                    if (sColor.length === 4) {
                        let sColorNew = "#";
                        for (let i = 1; i < 4; i += 1) {
                            sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
                        }
                        sColor = sColorNew;
                    }
                    //处理六位的颜色值
                    let sColorChange = [];
                    for (let i = 1; i < 7; i += 2) {
                        sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
                    }
                    return sColorChange;
                } else {
                    return sColor;
                }
            },
            colorHex(rgb) {
                let _this = rgb;
                let reg = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
                if (/^(rgb|RGB)/.test(_this)) {
                    let aColor = _this.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
                    let strHex = "#";
                    for (let i = 0; i < aColor.length; i++) {
                        let hex = Number(aColor[i]).toString(16);
                        hex = hex < 10 ? 0 + '' + hex : hex; // 保证每个rgb的值为2位
                        if (hex === "0") {
                            hex += hex;
                        }
                        strHex += hex;
                    }
                    if (strHex.length !== 7) {
                        strHex = _this;
                    }
                    return strHex;
                } else if (reg.test(_this)) {
                    let aNum = _this.replace(/#/, "").split("");
                    if (aNum.length === 6) {
                        return _this;
                    } else if (aNum.length === 3) {
                        let numHex = "#";
                        for (let i = 0; i < aNum.length; i += 1) {
                            numHex += (aNum[i] + aNum[i]);
                        }
                        return numHex;
                    }
                } else {
                    return _this;
                }
            },
            labelFunction(h, l, fontSize) {
                let index = l['$index']
                let f = 15;
                if (typeof(fontSize) != "undefined" && fontSize != null) {
                    f = fontSize;
                }
                //列頭的實際寬度
                let width = l.column.realWidth;
                let maxFontCount = Math.floor((width - 32) / f) - 1;
                let chars = l.column.label.split("");
                var label = "";
                if (maxFontCount < chars.length && index != 0 && index != 11) {
                    for (let i = 0; i < maxFontCount; i++) {
                        label += chars[i];
                    }
                    label += "..";
                } else {
                    label = l.column.label;
                }
                return label;
            },
            sortChange(para) {
                let curChangeColName = para.prop //排序列名
                this.tableOrder = para.order //排序方式
                let tempOrderTable = [...this.tableData]
                tempOrderTable = this.tableBubbleSort(curChangeColName, tempOrderTable)
                this.tableData = tempOrderTable
            },
            tableBubbleSort(OrderKey, curTable) {
                let arr = curTable
                for (let i = 0; i < arr.length; i++) {
                    for (let j = 0; j < arr.length - 1 - i; j++) {
                        let curOrderItem = arr[j][OrderKey]
                        let curOrderNextItem = arr[j + 1][OrderKey]
                        if (curOrderItem < curOrderNextItem) {
                            [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
                        }
                    }
                } //降序
                if (this.tableOrder == 'ascending') {
                    curTable = curTable.reverse()
                }
                if (this.tableOrder == null) {
                    curTable = [...this.totalWinRateData[this.tableFlag]]
                }
                return [...curTable]
            },
            toPoint(percent) {
                percent = percent + ''
                let str = percent.replace("%", "");
                str = str * 1;
                return str;
            },
            hdMonitor(cell) {
                let tempCellCss = {}
                tempCellCss["color"] = '#3AB6BA'
                tempCellCss["border-color"] = 'black'
                if (cell.rowIndex === 0 && cell.columnIndex != 0) {
                    {
                        tempCellCss["background-color"] = '#1a4861' //第一行
                        tempCellCss["border-bottom"] = '0px solid #111822'
                        if (cell.columnIndex == 11) {
                            tempCellCss["background-color"] = '#123345' //最后一格
                            tempCellCss["color"] = '#FFC850'
                        }
                    }
                }
                if (cell.rowIndex === 0 && cell.columnIndex == 0) {
                    tempCellCss["background-color"] = '#103346' //第一格
                    tempCellCss["border-bottom"] = '0px solid #111822'
                    tempCellCss["color"] = '#FFC850'
                }
                return tempCellCss
            },
            csMonitor(cell) {
                let tempCellCss = {}
                let tempCellWinRate = this.toPoint(cell.row[cell.column.property])
                tempCellCss["color"] = '#50ffeb'
                tempCellCss["border-color"] = '#1a4861'
                if (cell.columnIndex != 0) { //表格内
                    tempCellCss["color"] = '#e2f2ff'
                    if (tempCellWinRate <= 30) {
                        tempCellCss["color"] = '#ff7945'
                    }
                    if (tempCellWinRate >= 70) {
                        tempCellCss["color"] = '#b9ff5c'
                    }
                    if (tempCellWinRate > 30 && tempCellWinRate < 50) {
                        tempCellCss["color"] = this.gradientColor('#ff7945', '#e2f2ff', 30,50,tempCellWinRate)
                    
                    }
                    if (tempCellWinRate > 50 && tempCellWinRate < 70) {
                        tempCellCss["color"] = this.gradientColor('#e2f2ff', '#b9ff5c', 50,70,tempCellWinRate)
                    }
                    tempCellCss["border-bottom"] = '10px solid #111822'
                    tempCellCss["border-right"] = '1px solid #111822'
                }
                if (cell.rowIndex % 2 == 0) {
                    tempCellCss["background-color"] = '#1b2738'
                } else {
                    tempCellCss["background-color"] = '#283044'
                }
                if (cell.columnIndex == 0) {
                    {
                        tempCellCss["background-color"] = '#1a4861' //第一列
                        tempCellCss["border-color"] = 'black'
                        tempCellCss["border-bottom"] = '10px solid #111822'
                        tempCellCss["font-weight"] = 'bold'
                    }
                }
                if (cell.columnIndex == 11) {
                    {
                        if (cell.rowIndex % 2 == 0) {
                            tempCellCss["background-color"] = '#1a4861'
                        } else {
                            tempCellCss["background-color"] = '#1a4861'
                        }
                        //最后一列
                        tempCellCss["color"] = '#e2f2ff'
                        if (tempCellWinRate >= 50) {
                            tempCellCss["color"] = '#55FF00'
                        } else {
                            tempCellCss["color"] = '#e2f2ff'
                        }
                        tempCellCss["font-weight"] = 'bold'
                    }
                }
                let tempLabel = cell.column.label //当前格子的列名
                let tempContent = this.tableData[cell.rowIndex][this.builtInColumnTitle.deckType] //当前格子的行名
                if (tempLabel == tempContent) {
                    {
                        if (this.tableFlag == '2') {
                            tempCellCss["color"] = '#39485C'
                        }
                        tempCellCss["background-color"] = '#141A21' //胜率50的斜线
                    }
                }
                return tempCellCss
            },
            showClickWinRate(tab, event) {
                this.$refs.tableList.clearSort()
                let curTabNo = parseInt(tab.name)
                this.tableData = [...this.totalWinRateData[curTabNo]]
                this.tableFlag = curTabNo
            },
            handleColumn(jsonTxT) {
                let tempColumnTitle = []
                let tempObj = {
                    label: this.builtInColumnTitle.deckType,
                    prop: this.builtInColumnTitle.deckType,
                    key: 0
                }
                tempObj['resizable'] = false
                tempObj['sortable'] = false
                tempColumnTitle.push(tempObj)
                for (let index = 0; index < 10; index++) {
                    const element = jsonTxT[index].deckb;
                    tempObj = {
                        label: element,
                        prop: element,
                        key: index + 1
                    }
                    tempObj['resizable'] = false
                    tempObj['sortable'] = 'custom'
                    tempColumnTitle.push(tempObj)
                    this.winRateColumnTitle.push(element)
                }
                tempObj = {
                    label: this.builtInColumnTitle.avgWinRate,
                    prop: this.builtInColumnTitle.avgWinRate,
                    key: 11
                }
                tempObj['resizable'] = false
                tempObj['sortable'] = 'custom'
                tempColumnTitle.push(tempObj)
                this.tableHead = tempColumnTitle
                for (let x = 0; x < 3; x++) {
                    let tempRowList = []
                    for (let j = 0; j < 10; j++) {
                        let tempRow = {}
                        tempRow[this.builtInColumnTitle.deckType] = tempColumnTitle[j + 1].label
                        let avgRowRateList = []
                        for (let i = 0; i < 10; i++) {
                            let secondStrikeJson = jsonTxT[10 * i + j]
                            let firstStrikeJson = jsonTxT[i + 10 * j]
                            let totalFsMatch = (firstStrikeJson.win + firstStrikeJson.lose + firstStrikeJson.draw)
                            let totalScMatch = (
                                secondStrikeJson.win + secondStrikeJson.lose + secondStrikeJson.draw)
                            let tempWinRate = []
                            let tempFirstStrikeWinRate = Math.round(firstStrikeJson.win / (totalFsMatch) * 10000) /
                                100
                            let tempSecondStrikeWinRate = Math.round(secondStrikeJson.lose / (totalScMatch) * 10000) /
                                100 //该卡组对手先攻输-该卡组后攻赢
                            let totalWinrate = Math.round((firstStrikeJson.win + secondStrikeJson.lose) / (
                                    totalFsMatch + totalScMatch) * 10000) /
                                (100)
                            //(勇者先攻赢+勇者后攻赢)/(勇者先攻赢+勇者先攻平+勇者先攻输+勇者后攻赢+勇者后攻输+勇者后攻平)
                            tempWinRate.push(tempFirstStrikeWinRate)
                            tempWinRate.push(tempSecondStrikeWinRate)
                            tempWinRate.push(totalWinrate)
                            tempRow[tempColumnTitle[i + 1].label] = tempWinRate[x]
                            avgRowRateList.push(tempWinRate[x])
                        }
                        tempRow[this.builtInColumnTitle.avgWinRate] = (Math.round((avgRowRateList.reduce((prev, current,
                            index, avgRowRateList) => {
                            return prev + current
                        }) / 10 * 100)) / 100)
                        tempRowList.push(tempRow)
                    }
                    tempRowList.push()
                    this.totalWinRateData.push(tempRowList)
                }
                this.tableData = [...this.totalWinRateData[0]] //包含三种场次的数据
            }
        },
        //生命周期 - 创建完成（可以访问当前this实例）
        created() {
            API.getMonthlyWinRate().then((res) => {
                if (isNaN(res.data)) {
                    this.queryJsonStr = res.data
                    this.handleColumn(res.data)
                } else {}
            });
        },
        //生命周期 - 挂载完成（可以访问DOM元素）
        mounted() {},
        beforeCreate() {}, //生命周期 - 创建之前
        beforeMount() {}, //生命周期 - 挂载之前
        beforeUpdate() {}, //生命周期 - 更新之前
        updated() {}, //生命周期 - 更新之后
        beforeDestroy() {}, //生命周期 - 销毁之前
        destroyed() {}, //生命周期 - 销毁完成
        activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
    }
</script>
<style>
    #winRateTitle-1 {
        color: #bbcddb;
    }

    #winRateTitle-2 {
        color: #95d144;
    }

    .winRateTitle-color-1 {
        display: inline-block;
        color: #50ffeb;
    }

    .winRateTitle-color-2 {
        display: inline-block;
        color: #3AB6BA;
    }

    .winRateTitle-color-3 {
        display: inline-block;
        color: #FFC850;
    }

    .winRateTitle {
        float: right;
        display: block;
    }

    .winRateContent {
        clear: both;
    }

    .winRateContent-Tabs .el-tabs__item {
        color: white;
        font-size: 18px;
    }

    .winRateContent-Tabs .el-tabs__item.is-active {
        color: #409eff;

    }

    .winRateContent-Tabs .el-tabs__item:hover {
        color: #409eff;

    }

    .winRateContent-Tabs .el-tabs__active-bar {
        background: #409eff;

    }

    .winRateContent .el-tabs__nav-wrap::after {
        background-color: black;
    }

    .el-table,
    .el-table__expanded-cell {
        background-color: black !important;
    }

    .el-table--border,
    .el-table--group,
    .el-table::before {
        border-color: black !important;
    }

    .el-table--border::after,
    .el-table--group::after,
    .el-table::before {
        content: "";
        position: absolute;
        background-color: black !important;
        z-index: 1;
    }

    .winRateTable {
        margin-bottom: 20px;
        margin-left: 20px;
        margin-right: 20px;
    }

    .winRateFooter {
        text-align: center;

        margin-bottom: 20px;

    }

    .winRateTitle-color-4 {

        color: #409eff;
    }
</style>